* add unsloth studio desktop app
* Fix review findings
- studio/src-tauri/tauri.conf.json: retarget updater to staging repo
(danielhanchen/unsloth-staging-2); switch to unslothai/unsloth on upstream merge.
- studio/src-tauri/linux/postremove.sh: drop the interactive read loop and the
/home/* iteration. Package maintainer scripts must stay non-interactive and
must not touch other users' data.
- studio/frontend/src/app/auth-guards.ts: honor tauriAutoAuth() boolean. Failed
auto-auth now redirects to /login; requireGuest/requirePasswordChangeFlow
only redirect to /chat when auth succeeds. The new early-return on failed
auth is intentional so the login / change-password flows remain reachable
when desktop auth is not yet established.
- studio/frontend/src/config/env.ts: keep fetched=false on health failure so
later calls retry instead of caching the client-side platform guess.
- studio/src-tauri/src/install.rs: pick the available system package manager
(apt-get, dnf, zypper, pacman); AppImage bundles run on non-Debian distros.
- studio/frontend/src/lib/open-link.ts + markdown-text/sources callers: return
boolean from openLink so callers only preventDefault on handled URLs; relative
hrefs now navigate natively.
- studio/frontend/src/features/settings/tabs/about-tab.tsx: fetch(apiUrl(...))
so the version request targets the backend port in desktop mode. The bare
/api/health predates the Tauri webview (blame: the earlier onboarding commit,
which ran with same-origin frontend/backend); in desktop mode the webview
origin is tauri://localhost so the bare path fails.
- install.ps1: gate the install_python_stack.py hotfix on a sentinel comment
instead of a content regex; append the sentinel after applying so reruns
are unambiguous.
- unsloth_cli/commands/studio.py _write_auth_secret: use the atomic mkstemp +
os.replace path on Windows too; chmod calls are wrapped in try/except OSError.
- studio/src-tauri/src/preflight.rs probe_existing_backends: fan out the health
probes concurrently; desktop-auth status still runs sequentially per candidate.
reqwest::Client is internally Arc-wrapped so the in-loop .clone() is a
refcount bump, not a deep clone; annotated inline.
- studio/src-tauri/src/preflight.rs run_cli_probe: wait() after kill() to reap
the child, matching probe_cli_capability.
- studio/src-tauri/src/process.rs + main.rs: add stop_backend_detached and use
it from the tray quit handler so the 5s graceful-wait does not block the
Tauri main loop. RunEvent::Exit keeps the synchronous safety-net call.
- studio/backend/main.py: drop the permissive localhost CORS regex in
api-only mode; the explicit allow_origins list is sufficient.
- .github/workflows/release-desktop.yml: drop max-parallel: 1 so platform
builds run in parallel, and lift releaseBody to an env var so the three
tauri-action invocations share one source of truth.
* Fix review findings (loop 2)
- studio/backend/auth/storage.py update_password: clear_desktop_secret()
alongside clear_bootstrap_password() so rotating the admin password
also revokes any previously provisioned .desktop_secret. Without this,
an old local desktop credential keeps minting fresh admin tokens via
/api/auth/desktop-login after a password rotation.
- studio/src-tauri/src/desktop_auth.rs provision_desktop_auth: wrap
cmd.output().await in tokio::time::timeout(30s). DESKTOP_AUTH_LOCK is
held across the whole desktop_auth flow, and previously a hanging
`unsloth studio provision-desktop-auth` subprocess would pin the lock
indefinitely and freeze every subsequent desktop_auth call.
* Add review tests
* Consolidate review tests
Merge review-added tests into the existing studio/backend/tests/test_desktop_auth.py
(the PR's authoritative desktop-auth test file). Drops three scaffolding files under
tests/python/ in favor of five focused tests next to the tests they extend:
- test_update_password_clears_desktop_secret (runtime)
- test_update_password_on_unknown_user_leaves_desktop_secret_intact (runtime)
- test_cli_provisioning_delegates_to_storage_create_desktop_secret (source-level)
- test_cli_connect_auth_db_reads_storage_db_path (source-level)
- test_desktop_auth_provision_has_bounded_timeout (Rust source-level)
* Revert auth-guards.ts Tauri branches to unconditional form
The review loop on PR 5144 introduced a regression: the isTauri branch of
requireAuth redirected to /login when tauriAutoAuth() returned false, and
requireGuest / requirePasswordChangeFlow silently fell through on the same
condition. The Tauri desktop app authenticates via a local auto-generated
secret; it must never surface /login or /change-password to the user. A
failed auto-auth should let the startup layer retry, not expose a password
form.
Restore the three Tauri branches to the author's original unconditional
form (requireAuth: return; requireGuest / requirePasswordChangeFlow: throw
redirect({to: '/chat'})). Keep the rest of the review fixes -- the
apiUrl() fetch wrapping, authRedirect helper, and fetchAuthStatus refactor
are all legitimate improvements and are preserved.
* Revert release-desktop.yml to author's version
The review loop's workflow-file tweaks (drop max-parallel: 1, lift releaseBody
to an env var) are cosmetic. OAuth tokens cannot push workflow-file changes,
and fine-grained PATs cannot honor maintainerCanModify on a third-party fork.
Reverting the workflow file to wasimysaid's version lets the push go through
without needing a classic PAT with both repo and workflow scopes.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
---------
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
Co-authored-by: Daniel Han <unslothai@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
476 lines
15 KiB
Rust
476 lines
15 KiB
Rust
use crate::install;
|
|
use crate::process::{self, BackendState, ShutdownFlag};
|
|
use crate::update;
|
|
use log::{error, info, warn};
|
|
use tauri::{AppHandle, Emitter};
|
|
|
|
async fn managed_install_ready_after_repair() -> bool {
|
|
crate::preflight::managed_install_ready().await
|
|
}
|
|
|
|
fn should_emit_repair_failed(msg: &str) -> bool {
|
|
!msg.contains("NEEDS_ELEVATION")
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn desktop_preflight() -> crate::preflight::DesktopPreflightResult {
|
|
crate::preflight::desktop_preflight_result().await
|
|
}
|
|
|
|
/// Check if unsloth is installed AND functional.
|
|
/// Runs `unsloth -h` to verify the import chain works — a partial install
|
|
/// (binary exists but deps missing) will fail on import and return false,
|
|
/// which sends the user to the install screen for a clean re-install.
|
|
#[tauri::command]
|
|
pub async fn check_install_status() -> bool {
|
|
let Some(bin) = process::find_unsloth_binary() else {
|
|
return false;
|
|
};
|
|
|
|
let mut cmd = tokio::process::Command::new(&bin);
|
|
cmd.arg("-h")
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::null());
|
|
|
|
#[cfg(windows)]
|
|
{
|
|
cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
|
|
}
|
|
|
|
// Match the same AppImage env clearing used in process.rs and install.rs,
|
|
// otherwise the probe can fail due to bundled libs even when the install is fine.
|
|
#[cfg(target_os = "linux")]
|
|
if std::env::var_os("APPIMAGE").is_some() {
|
|
cmd.env_remove("LD_LIBRARY_PATH");
|
|
cmd.env_remove("PYTHONHOME");
|
|
cmd.env_remove("PYTHONPATH");
|
|
}
|
|
|
|
let mut child = match cmd.spawn() {
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
warn!("Install check: failed to spawn {:?}: {}", bin, e);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
match tokio::time::timeout(std::time::Duration::from_secs(10), child.wait()).await {
|
|
Ok(Ok(status)) => {
|
|
let ok = status.success();
|
|
if !ok {
|
|
warn!("Install check: `unsloth -h` exited with {}", status);
|
|
}
|
|
ok
|
|
}
|
|
Ok(Err(e)) => {
|
|
warn!("Install check: wait failed: {}", e);
|
|
false
|
|
}
|
|
Err(_) => {
|
|
warn!("Install check: `unsloth -h` timed out after 10s");
|
|
let _ = child.kill().await;
|
|
false
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Start the backend server on the given port.
|
|
/// Also spawns a health watchdog that monitors the backend and emits
|
|
/// `server-crashed` if it becomes unresponsive (deadlock, OOM, etc.).
|
|
#[tauri::command]
|
|
pub async fn start_server(
|
|
app: AppHandle,
|
|
state: tauri::State<'_, BackendState>,
|
|
shutdown: tauri::State<'_, ShutdownFlag>,
|
|
port: u16,
|
|
) -> Result<(), String> {
|
|
info!("start_server command called with port {}", port);
|
|
|
|
process::start_backend(&app, &state, port, &shutdown)?;
|
|
|
|
// Spawn health watchdog for the owned backend — detects
|
|
// deadlocks and hangs that stdout-based crash detection misses.
|
|
let watchdog_state = state.inner().clone();
|
|
let watchdog_shutdown = shutdown.inner().clone();
|
|
let watchdog_app = app.clone();
|
|
tokio::spawn(async move {
|
|
health_watchdog(watchdog_app, watchdog_state, watchdog_shutdown).await;
|
|
});
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Start the managed backend without reusing an existing backend.
|
|
#[tauri::command]
|
|
pub async fn start_managed_server(
|
|
app: AppHandle,
|
|
state: tauri::State<'_, BackendState>,
|
|
shutdown: tauri::State<'_, ShutdownFlag>,
|
|
port: u16,
|
|
) -> Result<(), String> {
|
|
info!("start_managed_server command called with port {}", port);
|
|
process::start_backend(&app, &state, port, &shutdown)?;
|
|
|
|
let watchdog_state = state.inner().clone();
|
|
let watchdog_shutdown = shutdown.inner().clone();
|
|
let watchdog_app = app.clone();
|
|
tokio::spawn(async move {
|
|
health_watchdog(watchdog_app, watchdog_state, watchdog_shutdown).await;
|
|
});
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Stop the backend server.
|
|
/// Sends SIGTERM to the process group, which triggers uvicorn's graceful
|
|
/// shutdown (same codepath as /api/shutdown). Falls back to SIGKILL after 5s.
|
|
#[tauri::command]
|
|
pub fn stop_server(
|
|
state: tauri::State<'_, BackendState>,
|
|
shutdown: tauri::State<'_, ShutdownFlag>,
|
|
) -> Result<(), String> {
|
|
info!("stop_server command called");
|
|
process::stop_backend(&state, &shutdown)
|
|
}
|
|
|
|
/// Check if a healthy Unsloth backend is running on the given port.
|
|
/// Expects JSON response with status=="healthy" AND service=="Unsloth UI Backend".
|
|
#[tauri::command]
|
|
pub async fn check_health(port: u16) -> Result<bool, String> {
|
|
match check_health_inner(port).await {
|
|
Ok(healthy) => Ok(healthy),
|
|
Err(e) => {
|
|
// Network errors are not command errors — just means not healthy
|
|
info!("Health check on port {} failed: {}", port, e);
|
|
Ok(false)
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn check_health_inner(port: u16) -> Result<bool, reqwest::Error> {
|
|
let url = format!("http://127.0.0.1:{}/api/health", port);
|
|
let client = reqwest::Client::builder()
|
|
.timeout(std::time::Duration::from_secs(2))
|
|
.build()?;
|
|
let resp = client.get(&url).send().await?;
|
|
let json: serde_json::Value = resp.json().await?;
|
|
|
|
let healthy = json
|
|
.get("status")
|
|
.and_then(|v| v.as_str())
|
|
.map(|s| s == "healthy")
|
|
.unwrap_or(false);
|
|
let correct_service = json
|
|
.get("service")
|
|
.and_then(|v| v.as_str())
|
|
.map(|s| s == "Unsloth UI Backend")
|
|
.unwrap_or(false);
|
|
|
|
Ok(healthy && correct_service)
|
|
}
|
|
|
|
/// Return buffered server logs.
|
|
#[tauri::command]
|
|
pub fn get_server_logs(state: tauri::State<'_, BackendState>) -> Vec<String> {
|
|
match state.lock() {
|
|
Ok(proc) => proc.logs.iter().cloned().collect(),
|
|
Err(e) => {
|
|
error!("Failed to lock state for logs: {}", e);
|
|
vec![]
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Open the Unsloth Studio directory in the system file manager.
|
|
#[tauri::command]
|
|
pub fn open_logs_dir() -> Result<(), String> {
|
|
let home = dirs::home_dir().ok_or("Could not determine home directory")?;
|
|
let dir = home.join(".unsloth").join("studio");
|
|
|
|
if !dir.exists() {
|
|
return Err(format!("Directory does not exist: {}", dir.display()));
|
|
}
|
|
|
|
open::that(&dir).map_err(|e| format!("Failed to open directory: {}", e))
|
|
}
|
|
|
|
/// Start the first-launch installation process.
|
|
/// Runs the platform installer script with --tauri flag and streams progress events.
|
|
/// Returns "NEEDS_ELEVATION" if system packages need elevated install (Linux only).
|
|
#[tauri::command]
|
|
pub async fn start_install(
|
|
app: AppHandle,
|
|
state: tauri::State<'_, install::InstallState>,
|
|
) -> Result<(), String> {
|
|
let state = state.inner().clone();
|
|
tokio::task::spawn_blocking(move || install::run_install(app, state))
|
|
.await
|
|
.map_err(|e| format!("Install task panicked: {e}"))?
|
|
}
|
|
|
|
/// Install system packages with elevated permissions (Linux only).
|
|
/// Called by frontend after user approves the elevation dialog.
|
|
/// Only allows packages that the install script reported as needed.
|
|
#[cfg(target_os = "linux")]
|
|
#[tauri::command]
|
|
pub fn install_system_packages(
|
|
packages: Vec<String>,
|
|
state: tauri::State<'_, install::InstallState>,
|
|
) -> Result<(), String> {
|
|
// Cross-check against the packages the install script actually reported
|
|
let allowed = state
|
|
.lock()
|
|
.map(|s| s.needed_packages.clone())
|
|
.unwrap_or_default();
|
|
for pkg in &packages {
|
|
if !allowed.contains(pkg) {
|
|
return Err(format!(
|
|
"Package '{}' was not requested by the install script",
|
|
pkg
|
|
));
|
|
}
|
|
}
|
|
install::install_system_packages(&packages)
|
|
}
|
|
|
|
/// Stub for non-Linux platforms — elevation is handled by the scripts themselves.
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[tauri::command]
|
|
pub fn install_system_packages(
|
|
_packages: Vec<String>,
|
|
_state: tauri::State<'_, install::InstallState>,
|
|
) -> Result<(), String> {
|
|
Err("Elevated package install is only supported on Linux".to_string())
|
|
}
|
|
|
|
/// Run backend update: stop server, run `unsloth studio update`, emit progress.
|
|
/// Does NOT restart the backend — the frontend handles shell update + relaunch after.
|
|
#[tauri::command]
|
|
pub async fn start_backend_update(
|
|
app: AppHandle,
|
|
backend_state: tauri::State<'_, BackendState>,
|
|
shutdown: tauri::State<'_, ShutdownFlag>,
|
|
update_state: tauri::State<'_, update::UpdateState>,
|
|
install_state: tauri::State<'_, install::InstallState>,
|
|
) -> Result<(), String> {
|
|
info!("start_backend_update command called");
|
|
|
|
// Signal the health watchdog to exit immediately, before any guards.
|
|
// This closes the race window where the watchdog could emit server-crashed
|
|
// between our command being called and stop_backend completing.
|
|
shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
|
|
// Guard: reject if install is running
|
|
if install_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("Cannot update while installation is in progress.".to_string());
|
|
}
|
|
|
|
// Guard: reject if update is already running
|
|
if update_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("Update is already running.".to_string());
|
|
}
|
|
|
|
// Stop backend if running
|
|
if backend_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
info!("Stopping backend before update...");
|
|
process::stop_backend(&backend_state, &shutdown)?;
|
|
}
|
|
|
|
// Run update in a blocking thread
|
|
let state = update_state.inner().clone();
|
|
tokio::task::spawn_blocking(move || update::run_backend_update(app, state))
|
|
.await
|
|
.map_err(|e| format!("Update task panicked: {e}"))?
|
|
}
|
|
|
|
/// Repair a stale managed Studio install.
|
|
#[tauri::command]
|
|
pub async fn start_managed_repair(
|
|
app: AppHandle,
|
|
backend_state: tauri::State<'_, BackendState>,
|
|
shutdown: tauri::State<'_, ShutdownFlag>,
|
|
update_state: tauri::State<'_, update::UpdateState>,
|
|
install_state: tauri::State<'_, install::InstallState>,
|
|
) -> Result<(), String> {
|
|
info!("start_managed_repair command called");
|
|
|
|
if install_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("Cannot repair while installation is in progress.".to_string());
|
|
}
|
|
|
|
if update_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("Repair is already running.".to_string());
|
|
}
|
|
|
|
shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
|
|
if backend_state
|
|
.lock()
|
|
.map(|s| s.child.is_some())
|
|
.unwrap_or(false)
|
|
{
|
|
info!("Stopping backend before repair...");
|
|
process::stop_backend(&backend_state, &shutdown)?;
|
|
}
|
|
|
|
let _ = app.emit("repair-progress", "Updating existing Studio install...");
|
|
let update_app = app.clone();
|
|
let update_state = update_state.inner().clone();
|
|
let update_result = tokio::task::spawn_blocking(move || {
|
|
update::run_backend_update_for_repair(update_app, update_state)
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Repair update task panicked: {e}"))?;
|
|
|
|
match update_result {
|
|
Ok(()) if managed_install_ready_after_repair().await => {
|
|
info!("Managed repair complete after update");
|
|
let _ = app.emit("repair-complete", ());
|
|
return Ok(());
|
|
}
|
|
Ok(()) => {
|
|
warn!("Managed repair update finished, but preflight is still not ready; falling back to installer");
|
|
let _ = app.emit(
|
|
"repair-progress",
|
|
"Update finished, but Studio is still not ready. Running bundled installer...",
|
|
);
|
|
}
|
|
Err(msg) => {
|
|
if msg.to_ascii_lowercase().contains("already running") {
|
|
error!("Managed repair update conflict: {}", msg);
|
|
let _ = app.emit("repair-failed", &msg);
|
|
return Err(msg);
|
|
}
|
|
|
|
warn!(
|
|
"Managed repair update failed, falling back to bundled installer: {}",
|
|
msg
|
|
);
|
|
let _ = app.emit(
|
|
"repair-progress",
|
|
"Update failed. Running bundled installer...",
|
|
);
|
|
}
|
|
}
|
|
|
|
let install_app = app.clone();
|
|
let install_state = install_state.inner().clone();
|
|
let install_result = tokio::task::spawn_blocking(move || {
|
|
install::run_install_for_repair(install_app, install_state)
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Repair install task panicked: {e}"))?;
|
|
|
|
if let Err(msg) = install_result {
|
|
if should_emit_repair_failed(&msg) {
|
|
error!("Managed repair installer failed: {}", msg);
|
|
let _ = app.emit("repair-failed", &msg);
|
|
}
|
|
return Err(msg);
|
|
}
|
|
|
|
if managed_install_ready_after_repair().await {
|
|
info!("Managed repair complete after installer");
|
|
let _ = app.emit("repair-complete", ());
|
|
return Ok(());
|
|
}
|
|
|
|
let msg = "Repair finished, but Studio install is still not desktop-ready.".to_string();
|
|
error!("{}", msg);
|
|
let _ = app.emit("repair-failed", &msg);
|
|
Err(msg)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#[test]
|
|
fn repair_elevation_is_not_a_terminal_repair_failure() {
|
|
assert!(!super::should_emit_repair_failed("NEEDS_ELEVATION"));
|
|
assert!(super::should_emit_repair_failed(
|
|
"Installer exited with code 1"
|
|
));
|
|
}
|
|
}
|
|
|
|
/// Periodic health check that detects deadlocked or hung backends.
|
|
/// Starts 30s after the backend is launched (to allow initial startup),
|
|
/// then pings /api/health every 15s. After 3 consecutive failures (45s)
|
|
/// with the process still alive, emits `server-crashed` so the frontend
|
|
/// can offer a restart.
|
|
async fn health_watchdog(app: AppHandle, state: BackendState, shutdown: ShutdownFlag) {
|
|
use std::sync::atomic::Ordering;
|
|
|
|
// Give the backend time to start up
|
|
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
|
|
|
let mut consecutive_failures: u32 = 0;
|
|
|
|
loop {
|
|
tokio::time::sleep(std::time::Duration::from_secs(15)).await;
|
|
|
|
if shutdown.load(Ordering::SeqCst) {
|
|
info!("Health watchdog: shutdown flag set, exiting");
|
|
break;
|
|
}
|
|
|
|
let (port, has_child) = {
|
|
let proc = match state.lock() {
|
|
Ok(p) => p,
|
|
Err(_) => break,
|
|
};
|
|
(proc.port, proc.child.is_some())
|
|
};
|
|
|
|
// Stop watching if the backend is gone
|
|
if !has_child {
|
|
info!("Health watchdog: backend stopped, exiting");
|
|
break;
|
|
}
|
|
|
|
let Some(port) = port else {
|
|
continue; // Port not yet known
|
|
};
|
|
|
|
match check_health_inner(port).await {
|
|
Ok(true) => {
|
|
consecutive_failures = 0;
|
|
}
|
|
_ => {
|
|
consecutive_failures += 1;
|
|
warn!(
|
|
"Health watchdog: failure {}/3 on port {}",
|
|
consecutive_failures, port
|
|
);
|
|
if consecutive_failures >= 3 {
|
|
error!(
|
|
"Health watchdog: backend unresponsive for 45s, killing and declaring dead"
|
|
);
|
|
// Kill the zombie process so retry can start fresh
|
|
let _ = process::stop_backend(&state, &shutdown);
|
|
let _ = app.emit("server-crashed", ());
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|