From df15bdc55f3242af839aee1be7bf2fb351898680 Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:02:51 +0100 Subject: [PATCH 1/2] app: create projects and download base models A project needs a base model on disk before anything can train, and the app could neither make a project nor fetch a model. It now does both. New project asks for where the model will be published (org/name) and a base model from the catalog the terminal UI offers. A project page has a Base model card that shows where the model is, or a Download button with the current file's progress and a Cancel button. Progress follows the file being fetched, not the file count: a model is ten small files and one of over a gigabyte, so a bar counted in files sat near 60% with almost nothing in. "Downloaded" now means the weights are all there. models::is_complete checks config.json, tokenizer.json and either model.safetensors or every shard the index names, and a file only gets its real name once it is whole, so a cancelled download never counts. base_model_dir also finds a model kept next to the projects, as in ~/.onde/base/Qwen3-1.7B, which the cache lookup alone missed. Only catalog models can be downloaded from the app, repo ids are checked before they become paths, and a second download of the same model is refused. Checked in the running app against the real Hugging Face: the form lists the catalog with its download state, the card shows a download and a connection timeout as an error with the button back, and Cancel stops the transfer (the cache stopped growing). A library test cancels a real download of Qwen3-0.6B and checks the half-written model is not complete. Not checked: a download that finishes, and creating a project through the form. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- .../app/src-tauri/src/commands/base_models.rs | 114 +++++++++++ packaging/app/src-tauri/src/commands/mod.rs | 1 + .../app/src-tauri/src/desktop/base_models.rs | 85 ++++++++ packaging/app/src-tauri/src/desktop/mod.rs | 1 + .../app/src-tauri/src/desktop/projects.rs | 5 +- packaging/app/src-tauri/src/lib.rs | 6 + .../app/src-tauri/src/state_downloads.rs | 62 ++++++ .../src/features/projects/BaseModelCard.tsx | 108 ++++++++++ .../src/features/projects/NewProjectForm.tsx | 94 +++++++++ .../src/features/projects/ProjectDetail.tsx | 2 + .../src/features/projects/ProjectsView.tsx | 28 ++- packaging/app/src/lib/ipc.ts | 15 +- packaging/app/src/lib/types.ts | 27 +++ src/models.rs | 186 +++++++++++++++++- 14 files changed, 721 insertions(+), 13 deletions(-) create mode 100644 packaging/app/src-tauri/src/commands/base_models.rs create mode 100644 packaging/app/src-tauri/src/desktop/base_models.rs create mode 100644 packaging/app/src-tauri/src/state_downloads.rs create mode 100644 packaging/app/src/features/projects/BaseModelCard.tsx create mode 100644 packaging/app/src/features/projects/NewProjectForm.tsx diff --git a/packaging/app/src-tauri/src/commands/base_models.rs b/packaging/app/src-tauri/src/commands/base_models.rs new file mode 100644 index 0000000..cb2ecb8 --- /dev/null +++ b/packaging/app/src-tauri/src/commands/base_models.rs @@ -0,0 +1,114 @@ +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, 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 { + 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, + 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, + )); + if !downloads.begin(&repo_id, task.abort_handle()) { + 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); + // The channel closing with no final message means the task was aborted. + if matches!(last, DownloadMsg::Cancelled) { + let _ = on_event.send(DownloadMsg::Cancelled); + } + Ok(()) +} + +#[tauri::command] +pub fn cancel_base_download(repo_id: String, downloads: State<'_, Downloads>) -> bool { + downloads.cancel(&repo_id) +} diff --git a/packaging/app/src-tauri/src/commands/mod.rs b/packaging/app/src-tauri/src/commands/mod.rs index 853d900..3d74966 100644 --- a/packaging/app/src-tauri/src/commands/mod.rs +++ b/packaging/app/src-tauri/src/commands/mod.rs @@ -1,5 +1,6 @@ pub mod app; pub mod auth; +pub mod base_models; pub mod links; pub mod oauth; pub mod projects; diff --git a/packaging/app/src-tauri/src/desktop/base_models.rs b/packaging/app/src-tauri/src/desktop/base_models.rs new file mode 100644 index 0000000..fb940eb --- /dev/null +++ b/packaging/app/src-tauri/src/desktop/base_models.rs @@ -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, +} + +pub fn list() -> Vec { + 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 { + 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()); + } +} diff --git a/packaging/app/src-tauri/src/desktop/mod.rs b/packaging/app/src-tauri/src/desktop/mod.rs index 843bf25..479725a 100644 --- a/packaging/app/src-tauri/src/desktop/mod.rs +++ b/packaging/app/src-tauri/src/desktop/mod.rs @@ -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; diff --git a/packaging/app/src-tauri/src/desktop/projects.rs b/packaging/app/src-tauri/src/desktop/projects.rs index 8a2ec31..881877b 100644 --- a/packaging/app/src-tauri/src/desktop/projects.rs +++ b/packaging/app/src-tauri/src/desktop/projects.rs @@ -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}, @@ -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, pub runs: Vec, /// An `eval/eval_inputs.json` exists, so the project can be evaluated. pub has_eval: bool, @@ -134,6 +136,7 @@ pub fn detail(repo_id: &str) -> Result { 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(), }) diff --git a/packaging/app/src-tauri/src/lib.rs b/packaging/app/src-tauri/src/lib.rs index 1a39b49..361b742 100644 --- a/packaging/app/src-tauri/src/lib.rs +++ b/packaging/app/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod desktop; mod error; mod picker; mod state; +mod state_downloads; #[cfg(test)] mod capability_tests; @@ -28,11 +29,16 @@ 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::projects::list_projects, commands::projects::project_detail, commands::projects::run_steps, diff --git a/packaging/app/src-tauri/src/state_downloads.rs b/packaging/app/src-tauri/src/state_downloads.rs new file mode 100644 index 0000000..3ee2574 --- /dev/null +++ b/packaging/app/src-tauri/src/state_downloads.rs @@ -0,0 +1,62 @@ +//! The base-model downloads in flight, so one can be cancelled by name. + +use std::{collections::HashMap, sync::Mutex}; + +use tokio::task::AbortHandle; + +#[derive(Default)] +pub struct Downloads(Mutex>); + +impl Downloads { + /// Record a download. Returns `false`, and records nothing, when one for + /// the same model is already running. + pub fn begin(&self, repo_id: &str, handle: AbortHandle) -> bool { + let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if map.contains_key(repo_id) { + return false; + } + map.insert(repo_id.to_string(), handle); + true + } + + pub fn finish(&self, repo_id: &str) { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(repo_id); + } + + /// Stop a running download. Returns whether there was one. + pub fn cancel(&self, repo_id: &str) -> bool { + match self + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(repo_id) + { + Some(handle) => { + handle.abort(); + true + } + None => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn one_download_per_model_and_cancel_stops_it() { + let downloads = Downloads::default(); + let task = tokio::spawn(std::future::pending::<()>()); + assert!(downloads.begin("Qwen/Qwen3-0.6B", task.abort_handle())); + let second = tokio::spawn(std::future::pending::<()>()); + assert!(!downloads.begin("Qwen/Qwen3-0.6B", second.abort_handle())); + assert!(downloads.cancel("Qwen/Qwen3-0.6B")); + assert!(task.await.unwrap_err().is_cancelled()); + assert!(!downloads.cancel("Qwen/Qwen3-0.6B")); + second.abort(); + } +} diff --git a/packaging/app/src/features/projects/BaseModelCard.tsx b/packaging/app/src/features/projects/BaseModelCard.tsx new file mode 100644 index 0000000..294a1c1 --- /dev/null +++ b/packaging/app/src/features/projects/BaseModelCard.tsx @@ -0,0 +1,108 @@ +import { useEffect, useRef, useState } from "react"; +import { ipc } from "@/lib/ipc"; +import { errorMessage, type BaseModelView, type DownloadMsg, type ProjectDetail } from "@/lib/types"; +import { formatBytes, shortPath } from "./format"; + +type Progress = Extract; + +/** How far along the file being fetched is, 0 to 1, or undefined when its size is + * not known. A model is ten small files and one of over a gigabyte, so a bar + * counted in files would sit near 60% while almost nothing had arrived. */ +export function fileFraction(p: Progress): number | undefined { + return p.file_bytes_total > 0 ? Math.min(1, p.file_bytes_done / p.file_bytes_total) : undefined; +} + +/** The project's base model: where it is, or a button to fetch it. */ +export function BaseModelCard({ detail, onChanged }: { detail: ProjectDetail; onChanged: () => void }) { + const [catalog, setCatalog] = useState([]); + const [progress, setProgress] = useState(null); + const [downloading, setDownloading] = useState(false); + const [error, setError] = useState(null); + const alive = useRef(true); + + useEffect(() => { + alive.current = true; + ipc.baseModels().then(setCatalog).catch(() => {}); + return () => { + alive.current = false; + }; + }, []); + + const entry = catalog.find((m) => m.repo_id === detail.base_model_id); + + async function download() { + setError(null); + setDownloading(true); + try { + await ipc.downloadBaseModel(detail.base_model_id, (msg) => { + if (!alive.current) return; + if (msg.event === "progress") setProgress(msg); + if (msg.event === "failed") setError(msg.message); + }); + } catch (e) { + if (alive.current) setError(errorMessage(e)); + } finally { + if (alive.current) { + setDownloading(false); + setProgress(null); + onChanged(); + } + } + } + + return ( +
+
+
+

Base model

+

+ {entry ? `${entry.display_name} · ${entry.params} · ${entry.size_display}` : detail.base_model_id} +

+
+ {detail.base_dir == null && !downloading && entry && ( + + )} + {downloading && ( + + )} +
+ {detail.base_dir != null ? ( +

+ {shortPath(detail.base_dir)} +

+ ) : downloading ? ( +
+ +

+ {progress + ? `File ${progress.file_index + 1} of ${progress.total_files}: ${progress.filename}${ + progress.file_bytes_total ? ` (${formatBytes(progress.file_bytes_done)} of ${formatBytes(progress.file_bytes_total)})` : "" + }` + : "Starting…"} +

+
+ ) : ( +

+ {entry ? "Not downloaded yet. Fine-tuning needs the weights on this Mac." : "This base model is not in the app's list, so it cannot be downloaded here."} +

+ )} + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/packaging/app/src/features/projects/NewProjectForm.tsx b/packaging/app/src/features/projects/NewProjectForm.tsx new file mode 100644 index 0000000..0b91636 --- /dev/null +++ b/packaging/app/src/features/projects/NewProjectForm.tsx @@ -0,0 +1,94 @@ +import { useEffect, useState } from "react"; +import { ipc } from "@/lib/ipc"; +import { errorMessage, type BaseModelView } from "@/lib/types"; + +// The same shape the backend accepts: org/name, letters, digits, . - and _, +// and neither half may be "." or "..". +const REPO_ID = /^(?!\.{1,2}\/)(?!.*\/\.{1,2}$)[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; + +export function NewProjectForm({ + onCreated, + onCancel, +}: { + onCreated: (repoId: string) => void; + onCancel: () => void; +}) { + const [models, setModels] = useState([]); + const [repoId, setRepoId] = useState(""); + const [base, setBase] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + ipc + .baseModels() + .then((m) => { + setModels(m); + setBase((current) => current || m[0]?.repo_id || ""); + }) + .catch((e) => setError(errorMessage(e))); + }, []); + + const valid = REPO_ID.test(repoId.trim()) && base !== ""; + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + try { + const made = await ipc.createProject(repoId.trim(), base); + onCreated(made.repo_id); + } catch (err) { + setError(errorMessage(err)); + } finally { + setBusy(false); + } + } + + const field = "w-full rounded-md border border-fog-line bg-transparent px-3 py-2 text-sm outline-none focus:border-ink"; + return ( +
+

New project

+ + + {base &&

{models.find((m) => m.repo_id === base)?.description}

} + {error && ( +

+ {error} +

+ )} +
+ + +
+
+ ); +} diff --git a/packaging/app/src/features/projects/ProjectDetail.tsx b/packaging/app/src/features/projects/ProjectDetail.tsx index 17662b0..f97895a 100644 --- a/packaging/app/src/features/projects/ProjectDetail.tsx +++ b/packaging/app/src/features/projects/ProjectDetail.tsx @@ -8,6 +8,7 @@ import { type RunRecord, type StepRecord, } from "@/lib/types"; +import { BaseModelCard } from "./BaseModelCard"; import { LossChart } from "./LossChart"; import { formatBytes, formatDate, formatLoss, formatLr } from "./format"; @@ -234,6 +235,7 @@ export function ProjectDetail({ repoId, onBack }: { repoId: string; onBack: () = {error &&

{error}

} {detail && ( <> +

Runs

diff --git a/packaging/app/src/features/projects/ProjectsView.tsx b/packaging/app/src/features/projects/ProjectsView.tsx index 34e3802..7d24688 100644 --- a/packaging/app/src/features/projects/ProjectsView.tsx +++ b/packaging/app/src/features/projects/ProjectsView.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import { ipc } from "@/lib/ipc"; import { errorMessage, type ProjectSummary, type ProjectsLocation } from "@/lib/types"; +import { NewProjectForm } from "./NewProjectForm"; import { ProjectDetail } from "./ProjectDetail"; import { ProjectList } from "./ProjectList"; import { ProjectsFolder } from "./ProjectsFolder"; @@ -10,6 +11,7 @@ export function ProjectsView() { const [projects, setProjects] = useState(null); const [open, setOpen] = useState(null); const [error, setError] = useState(null); + const [creating, setCreating] = useState(false); const refresh = useCallback(() => { setError(null); @@ -27,10 +29,30 @@ export function ProjectsView() { return (
-
-

Projects

-

Datasets and fine-tune runs, one project per model.

+
+
+

Projects

+

Datasets and fine-tune runs, one project per model.

+
+ {!creating && ( + + )}
+ {creating && ( + setCreating(false)} + onCreated={(id) => { + setCreating(false); + setOpen(id); + }} + /> + )} {error &&

{error}

} {location && ( invoke("project_detail", { repoId }), runSteps: (repoId: string, run: string) => invoke("run_steps", { repoId, run }), importDataset: (repoId: string) => invoke("import_dataset", { repoId }), + baseModels: () => invoke("list_base_models"), + createProject: (repoId: string, baseModelId: string) => + invoke("create_project", { repoId, baseModelId }), + /** Resolves when the download finishes, fails or is cancelled; progress + * arrives on `onEvent` meanwhile. */ + downloadBaseModel: (repoId: string, onEvent: (msg: DownloadMsg) => void) => { + const channel = new Channel(); + channel.onmessage = onEvent; + return invoke("download_base_model", { repoId, onEvent: channel }); + }, + cancelBaseDownload: (repoId: string) => invoke("cancel_base_download", { repoId }), }; diff --git a/packaging/app/src/lib/types.ts b/packaging/app/src/lib/types.ts index d26fb28..094fd67 100644 --- a/packaging/app/src/lib/types.ts +++ b/packaging/app/src/lib/types.ts @@ -105,12 +105,39 @@ export interface StepRecord { t_ms: number; } +/** Mirrors `desktop::base_models::BaseModelView`. */ +export interface BaseModelView { + repo_id: string; + display_name: string; + size_display: string; + params: string; + description: string; + /** Where the complete model is on disk, or null when it is not downloaded. */ + dir: string | null; +} + +/** Mirrors `commands::base_models::DownloadMsg`. */ +export type DownloadMsg = + | { + event: "progress"; + filename: string; + file_index: number; + total_files: number; + file_bytes_done: number; + file_bytes_total: number; + } + | { event: "done" } + | { event: "failed"; message: string } + | { event: "cancelled" }; + /** Mirrors `desktop::projects::ProjectDetail`. */ export interface ProjectDetail { repo_id: string; base_model_id: string; created_at: number; dataset: DatasetState; + /** Where the complete base model is on disk, or null when it is not. */ + base_dir: string | null; runs: RunRecord[]; has_eval: boolean; } diff --git a/src/models.rs b/src/models.rs index d6db845..e213d26 100644 --- a/src/models.rs +++ b/src/models.rs @@ -37,22 +37,79 @@ pub fn resolve_snapshot(repo_id: &str) -> Option { hub_dirs().iter().find_map(|hub| snapshot_in(hub, repo_id)) } -/// `{hub}/models--{org}--{name}/snapshots/{commit}` for the first commit -/// directory. Directories that are not a hex commit id are skipped: fine-tuning -/// creates siblings such as `lora-adapter` that are not model snapshots. -fn snapshot_in(hub: &Path, repo_id: &str) -> Option { - let snapshots = hub +/// Every `{hub}/models--{org}--{name}/snapshots/{commit}` directory. Directories +/// that are not a hex commit id are skipped: fine-tuning creates siblings such +/// as `lora-adapter` that are not model snapshots. +fn snapshots(hub: &Path, repo_id: &str) -> Vec { + let dir = hub .join(format!("models--{}", repo_id.replace('/', "--"))) .join("snapshots"); - std::fs::read_dir(snapshots) - .ok()? + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec = entries .flatten() - .find(|entry| { + .filter(|entry| { let name = entry.file_name(); let name = name.to_string_lossy(); entry.path().is_dir() && name.len() >= 7 && name.chars().all(|c| c.is_ascii_hexdigit()) }) .map(|entry| entry.path()) + .collect(); + found.sort(); + found +} + +fn snapshot_in(hub: &Path, repo_id: &str) -> Option { + snapshots(hub, repo_id).into_iter().next() +} + +/// True when `dir` holds a base model the trainer can load: `config.json`, +/// `tokenizer.json`, and all the weights, which is either one +/// `model.safetensors` or every shard that `model.safetensors.index.json` names. +/// A download that was cancelled or is still running fails this, because a +/// file only gets its final name once it is whole. +pub fn is_complete(dir: &Path) -> bool { + if !dir.join("config.json").is_file() || !dir.join("tokenizer.json").is_file() { + return false; + } + if dir.join("model.safetensors").is_file() { + return true; + } + let Ok(raw) = std::fs::read_to_string(dir.join("model.safetensors.index.json")) else { + return false; + }; + let Ok(index) = serde_json::from_str::(&raw) else { + return false; + }; + let Some(map) = index.get("weight_map").and_then(|m| m.as_object()) else { + return false; + }; + let shards: std::collections::HashSet<&str> = map.values().filter_map(|v| v.as_str()).collect(); + !shards.is_empty() && shards.iter().all(|f| dir.join(f).is_file()) +} + +/// `{base_root}/{name}` for a repo id such as `Qwen/Qwen3-1.7B`, when that folder +/// holds a complete model. This is where models fetched by hand live, next to +/// the projects, as in `~/.onde/base/Qwen3-1.7B`. +fn base_in(base_root: &Path, repo_id: &str) -> Option { + let name = repo_id.rsplit('/').next().filter(|n| !n.is_empty())?; + let dir = base_root.join(name); + is_complete(&dir).then_some(dir) +} + +/// Where a complete copy of the base model `repo_id` is on this machine, or +/// `None`. A Hugging Face cache snapshot wins, then a folder under `base/` next +/// to the projects folder. +pub fn base_model_dir(repo_id: &str) -> Option { + hub_dirs() + .iter() + .flat_map(|hub| snapshots(hub, repo_id)) + .find(|dir| is_complete(dir)) + .or_else(|| { + let root = crate::paths::projects_dir(); + base_in(&root.parent()?.join("base"), repo_id) + }) } #[cfg(test)] @@ -77,4 +134,117 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); assert_eq!(snapshot_in(tmp.path(), "Qwen/Qwen3-0.6B"), None); } + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn single(dir: &Path) { + write(&dir.join("config.json"), "{}"); + write(&dir.join("tokenizer.json"), "{}"); + write(&dir.join("model.safetensors"), "w"); + } + + #[test] + fn a_single_file_model_is_complete_only_with_config_tokenizer_and_weights() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("m"); + single(&dir); + assert!(is_complete(&dir)); + std::fs::remove_file(dir.join("tokenizer.json")).unwrap(); + assert!(!is_complete(&dir)); + assert!(!is_complete(&tmp.path().join("missing"))); + } + + #[test] + fn a_sharded_model_needs_every_shard() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("m"); + write(&dir.join("config.json"), "{}"); + write(&dir.join("tokenizer.json"), "{}"); + write( + &dir.join("model.safetensors.index.json"), + r#"{"weight_map":{"a":"s-1.safetensors","b":"s-2.safetensors","c":"s-1.safetensors"}}"#, + ); + write(&dir.join("s-1.safetensors"), "w"); + assert!(!is_complete(&dir), "shard 2 is missing"); + write(&dir.join("s-2.safetensors"), "w"); + assert!(is_complete(&dir)); + // A half-downloaded shard still has its .tmp name, not the real one. + std::fs::remove_file(dir.join("s-2.safetensors")).unwrap(); + write(&dir.join("s-2.safetensors.tmp"), "w"); + assert!(!is_complete(&dir)); + } + + #[test] + fn a_base_folder_next_to_the_projects_is_found_by_the_name_part() { + let tmp = tempfile::tempdir().unwrap(); + single(&tmp.path().join("Qwen3-1.7B")); + assert_eq!( + base_in(tmp.path(), "Qwen/Qwen3-1.7B"), + Some(tmp.path().join("Qwen3-1.7B")) + ); + assert_eq!(base_in(tmp.path(), "Qwen/Qwen3-4B"), None); + // An incomplete folder does not count. + write(&tmp.path().join("Qwen3-4B/config.json"), "{}"); + assert_eq!(base_in(tmp.path(), "Qwen/Qwen3-4B"), None); + } + + #[test] + fn snapshots_skip_non_commit_directories_and_come_back_in_order() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("models--Qwen--Qwen3-0.6B/snapshots"); + std::fs::create_dir_all(root.join("lora-adapter")).unwrap(); + std::fs::create_dir_all(root.join("bbbbbbbbbb")).unwrap(); + std::fs::create_dir_all(root.join("aaaaaaaaaa")).unwrap(); + assert_eq!( + snapshots(tmp.path(), "Qwen/Qwen3-0.6B"), + vec![root.join("aaaaaaaaaa"), root.join("bbbbbbbbbb")] + ); + } + + /// Start the real download of the smallest catalog model into a temporary + /// hub, stop it as soon as the weights file begins, and check the half + /// finished model is not reported as complete. Needs the network. + #[test] + #[ignore = "downloads from huggingface.co"] + fn a_cancelled_download_is_not_a_complete_model() { + use crate::hf_search::DownloadEvent; + + let hub = tempfile::tempdir().unwrap(); + let repo = "Qwen/Qwen3-0.6B"; + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(crate::hf_search::download_model( + repo.to_string(), + hub.path().to_path_buf(), + tx, + )); + while let Some(event) = rx.recv().await { + match event { + DownloadEvent::Progress(p) if p.filename == "model.safetensors" => { + task.abort(); + break; + } + DownloadEvent::Failed(e) => panic!("download failed: {e}"), + DownloadEvent::Complete => panic!("finished before the weights began"), + _ => {} + } + } + let _ = task.await; + }); + let snapshot = snapshot_in(hub.path(), repo).expect("a snapshot directory exists"); + assert!( + snapshot.join("config.json").is_file(), + "small files finished" + ); + assert!( + snapshot.join("model.safetensors.tmp").exists() + && !snapshot.join("model.safetensors").exists(), + "the weights are still a .tmp file" + ); + assert!(!is_complete(&snapshot)); + } } From ebc419548221d0abc82e192399d4788c28c8ee39 Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:57:54 +0100 Subject: [PATCH 2/2] app: keep the download guard honest and show a download in progress Cancelling a download removes its entry at once, and the cancelled handler then wakes up and called finish by model name. If the user had started the model again in between, finish removed the new download's entry. That defeated the one-download guard and left the new transfer impossible to cancel. Each download now has a ticket, and finish only clears the entry when the ticket is still the one on record. A project page opened while a download ran showed a Download button again, because the card only knew about downloads it started itself. It now asks the backend, shows that the download is going on in the background, offers Cancel, and refreshes when it ends. Progress from before the page was opened is not available. A failure to load the base model list was swallowed, so the card claimed the model was not in the app's list. It now says the list could not be loaded and shows the error. Checked in the running app: leaving a download and reopening the project shows it in progress, and Cancel from there stops the transfer. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- .../app/src-tauri/src/commands/base_models.rs | 13 +- packaging/app/src-tauri/src/lib.rs | 1 + .../app/src-tauri/src/state_downloads.rs | 127 ++++++++++++++---- .../src/features/projects/BaseModelCard.tsx | 45 ++++++- packaging/app/src/lib/ipc.ts | 1 + 5 files changed, 155 insertions(+), 32 deletions(-) diff --git a/packaging/app/src-tauri/src/commands/base_models.rs b/packaging/app/src-tauri/src/commands/base_models.rs index cb2ecb8..936a955 100644 --- a/packaging/app/src-tauri/src/commands/base_models.rs +++ b/packaging/app/src-tauri/src/commands/base_models.rs @@ -73,12 +73,12 @@ pub async fn download_base_model( hf::preferred_download_hub(), tx, )); - if !downloads.begin(&repo_id, task.abort_handle()) { + 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 { @@ -100,7 +100,7 @@ pub async fn download_base_model( break; } } - downloads.finish(&repo_id); + 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); @@ -108,6 +108,13 @@ pub async fn download_base_model( 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) diff --git a/packaging/app/src-tauri/src/lib.rs b/packaging/app/src-tauri/src/lib.rs index 361b742..b20104a 100644 --- a/packaging/app/src-tauri/src/lib.rs +++ b/packaging/app/src-tauri/src/lib.rs @@ -39,6 +39,7 @@ pub fn run() { 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, diff --git a/packaging/app/src-tauri/src/state_downloads.rs b/packaging/app/src-tauri/src/state_downloads.rs index 3ee2574..0193ae4 100644 --- a/packaging/app/src-tauri/src/state_downloads.rs +++ b/packaging/app/src-tauri/src/state_downloads.rs @@ -1,62 +1,141 @@ //! The base-model downloads in flight, so one can be cancelled by name. -use std::{collections::HashMap, sync::Mutex}; +use std::{ + collections::HashMap, + sync::{ + Mutex, + atomic::{AtomicU64, Ordering}, + }, +}; use tokio::task::AbortHandle; +/// Identifies one download. A cancelled download's handler wakes up after a new +/// download of the same model may have started, and must only clear its own entry. +pub type Ticket = u64; + #[derive(Default)] -pub struct Downloads(Mutex>); +pub struct Downloads { + running: Mutex>, + next: AtomicU64, +} impl Downloads { - /// Record a download. Returns `false`, and records nothing, when one for - /// the same model is already running. - pub fn begin(&self, repo_id: &str, handle: AbortHandle) -> bool { - let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner()); + /// Record a download and return its ticket. `None`, with nothing recorded, + /// when one for the same model is already running. + pub fn begin(&self, repo_id: &str, handle: AbortHandle) -> Option { + let mut map = self.running.lock().unwrap_or_else(|e| e.into_inner()); if map.contains_key(repo_id) { - return false; + return None; } - map.insert(repo_id.to_string(), handle); - true + let ticket = self.next.fetch_add(1, Ordering::Relaxed); + map.insert(repo_id.to_string(), (ticket, handle)); + Some(ticket) } - pub fn finish(&self, repo_id: &str) { - self.0 - .lock() - .unwrap_or_else(|e| e.into_inner()) - .remove(repo_id); + /// Forget a download, but only if `ticket` is still the one on record. After + /// a cancel and a restart the entry belongs to the newer download. + pub fn finish(&self, repo_id: &str, ticket: Ticket) { + let mut map = self.running.lock().unwrap_or_else(|e| e.into_inner()); + if map.get(repo_id).is_some_and(|(t, _)| *t == ticket) { + map.remove(repo_id); + } } /// Stop a running download. Returns whether there was one. pub fn cancel(&self, repo_id: &str) -> bool { - match self - .0 + let removed = self + .running .lock() .unwrap_or_else(|e| e.into_inner()) - .remove(repo_id) - { - Some(handle) => { + .remove(repo_id); + match removed { + Some((_, handle)) => { handle.abort(); true } None => false, } } + + pub fn is_running(&self, repo_id: &str) -> bool { + self.running + .lock() + .unwrap_or_else(|e| e.into_inner()) + .contains_key(repo_id) + } } #[cfg(test)] mod tests { use super::*; + fn task() -> tokio::task::JoinHandle<()> { + tokio::spawn(std::future::pending::<()>()) + } + #[tokio::test] async fn one_download_per_model_and_cancel_stops_it() { let downloads = Downloads::default(); - let task = tokio::spawn(std::future::pending::<()>()); - assert!(downloads.begin("Qwen/Qwen3-0.6B", task.abort_handle())); - let second = tokio::spawn(std::future::pending::<()>()); - assert!(!downloads.begin("Qwen/Qwen3-0.6B", second.abort_handle())); + let first = task(); + assert!( + downloads + .begin("Qwen/Qwen3-0.6B", first.abort_handle()) + .is_some() + ); + let second = task(); + assert!( + downloads + .begin("Qwen/Qwen3-0.6B", second.abort_handle()) + .is_none() + ); + assert!(downloads.is_running("Qwen/Qwen3-0.6B")); assert!(downloads.cancel("Qwen/Qwen3-0.6B")); - assert!(task.await.unwrap_err().is_cancelled()); + assert!(first.await.unwrap_err().is_cancelled()); + assert!(!downloads.is_running("Qwen/Qwen3-0.6B")); assert!(!downloads.cancel("Qwen/Qwen3-0.6B")); second.abort(); } + + /// The race from the review: cancel, start again, then the cancelled + /// download's handler finishes. It must not unregister the new one. + #[tokio::test] + async fn a_cancelled_downloads_finish_does_not_remove_its_replacement() { + let downloads = Downloads::default(); + let old = task(); + let old_ticket = downloads + .begin("Qwen/Qwen3-0.6B", old.abort_handle()) + .unwrap(); + assert!(downloads.cancel("Qwen/Qwen3-0.6B")); + + let new = task(); + let new_ticket = downloads + .begin("Qwen/Qwen3-0.6B", new.abort_handle()) + .unwrap(); + assert_ne!(old_ticket, new_ticket); + + downloads.finish("Qwen/Qwen3-0.6B", old_ticket); + assert!( + downloads.is_running("Qwen/Qwen3-0.6B"), + "the new download is still registered" + ); + assert!( + downloads.cancel("Qwen/Qwen3-0.6B"), + "and can still be cancelled" + ); + + downloads.finish("Qwen/Qwen3-0.6B", new_ticket); // nothing left to remove, no panic + old.abort(); + new.abort(); + } + + #[tokio::test] + async fn finishing_with_the_right_ticket_frees_the_slot() { + let downloads = Downloads::default(); + let t = task(); + let ticket = downloads.begin("a/b", t.abort_handle()).unwrap(); + downloads.finish("a/b", ticket); + assert!(!downloads.is_running("a/b")); + t.abort(); + } } diff --git a/packaging/app/src/features/projects/BaseModelCard.tsx b/packaging/app/src/features/projects/BaseModelCard.tsx index 294a1c1..511eb8e 100644 --- a/packaging/app/src/features/projects/BaseModelCard.tsx +++ b/packaging/app/src/features/projects/BaseModelCard.tsx @@ -17,16 +17,38 @@ export function BaseModelCard({ detail, onChanged }: { detail: ProjectDetail; on const [catalog, setCatalog] = useState([]); const [progress, setProgress] = useState(null); const [downloading, setDownloading] = useState(false); + // A download that was started before this card was shown (the user went to + // another screen and came back). Its progress is gone, but it can be cancelled + // and the card notices when it ends. + const [resumed, setResumed] = useState(false); const [error, setError] = useState(null); + const [catalogError, setCatalogError] = useState(null); const alive = useRef(true); + const baseModelId = detail.base_model_id; useEffect(() => { alive.current = true; - ipc.baseModels().then(setCatalog).catch(() => {}); + ipc.baseModels().then(setCatalog).catch((e) => setCatalogError(errorMessage(e))); + ipc.baseDownloadRunning(baseModelId).then((r) => alive.current && setResumed(r)).catch(() => {}); return () => { alive.current = false; }; - }, []); + }, [baseModelId]); + + useEffect(() => { + if (!resumed) return; + const timer = window.setInterval(() => { + ipc + .baseDownloadRunning(baseModelId) + .then((r) => { + if (r || !alive.current) return; + setResumed(false); + onChanged(); + }) + .catch(() => {}); + }, 2000); + return () => window.clearInterval(timer); + }, [resumed, baseModelId, onChanged]); const entry = catalog.find((m) => m.repo_id === detail.base_model_id); @@ -59,7 +81,7 @@ export function BaseModelCard({ detail, onChanged }: { detail: ProjectDetail; on {entry ? `${entry.display_name} · ${entry.params} · ${entry.size_display}` : detail.base_model_id}

- {detail.base_dir == null && !downloading && entry && ( + {detail.base_dir == null && !downloading && !resumed && entry && ( )} - {downloading && ( + {(downloading || resumed) && (