The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(mac): the HuggingFace token rides along on MLX downloads too
purple15b7947835bd
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.tsindex 2a0898d1..8ddfae20 100644--- a/e2e/support/tauri-mock.ts+++ b/e2e/support/tauri-mock.ts@@ -275,6 +275,16 @@ export function tauriMockInit(opts: TauriMockOptions) {return Promise.resolve({ ok: true, was_loaded: false, running: true })case 'mlx_image_models':return Promise.resolve(mlxImageCatalog.map((m) => ({ ...m, installed: mlx.images.has(m.id) })))+ // Rust holds the HF token in memory only, so a spec has to be able to+ // see that the frontend pushed it down — not just that it was stored.+ case 'set_hf_token': {+ const token = String(m?.token ?? '').trim()+ w.__E2E_HF_TOKEN__ = token || null+ record('__E2E_MLX_CALLS__', { cmd, present: !!token })+ return Promise.resolve({ ok: true, present: !!token })+ }+ case 'hf_token_present':+ return Promise.resolve({ present: !!w.__E2E_HF_TOKEN__ })case 'install_mlx_diffusion':slot.imageEngine = 0record('__E2E_MLX_CALLS__', { cmd })diff --git a/src-tauri/resources/mlx/server.py b/src-tauri/resources/mlx/server.pyindex 3341f3a0..991509a1 100644--- a/src-tauri/resources/mlx/server.py+++ b/src-tauri/resources/mlx/server.py@@ -67,7 +67,13 @@ def _idle_unload_loop():_release_pipe()-def _ensure_pipe(repo: str, dtype: str, variant: Optional[str], disable_safety_checker: bool):+def _ensure_pipe(+ repo: str,+ dtype: str,+ variant: Optional[str],+ disable_safety_checker: bool,+ local_files_only: bool = False,+):global _pipe, _pipe_repo# Caller already holds _pipe_lock.if _pipe is not None and _pipe_repo == repo:@@ -83,6 +89,13 @@ def _ensure_pipe(repo: str, dtype: str, variant: Optional[str], disable_safety_ctorch_dtype = torch.bfloat16 if dtype == "bfloat16" else torch.float16kwargs = {"torch_dtype": torch_dtype}+ # A model the app already installed must load from disk alone. Without+ # this, diffusers re-validates all ~18 files against the hub on every+ # load: measured at 26 s per already-present file when the hub throttles+ # anonymous traffic, and an outright failure with no network — so "local"+ # image generation silently depended on being online.+ if local_files_only:+ kwargs["local_files_only"] = Trueif variant:kwargs["variant"] = variantif disable_safety_checker:@@ -117,6 +130,8 @@ class GenerateRequest(BaseModel):guidance: float = 0.0cfg_param: str = "guidance_scale"disable_safety_checker: bool = False+ # Set by the bridge when it has verified the model is fully on disk.+ local_files_only: bool = False@app.get("/health")@@ -147,7 +162,13 @@ def generate(req: GenerateRequest):with _pipe_lock:try:- pipe = _ensure_pipe(req.model_repo, req.dtype, req.variant, req.disable_safety_checker)+ pipe = _ensure_pipe(+ req.model_repo,+ req.dtype,+ req.variant,+ req.disable_safety_checker,+ req.local_files_only,+ )except Exception as exc:# A half-loaded pipeline must not shadow the previous model._release_pipe()diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rsindex 32d15e49..fa1b527b 100644--- a/src-tauri/src/commands/media_cmds.rs+++ b/src-tauri/src/commands/media_cmds.rs@@ -48,6 +48,16 @@ pub fn mlx_image_models(state: State<'_, AppState>, args: Value) -> Result<Valuecrate::commands::mlx::mlx_image_models(state.inner(), &args)}+#[tauri::command]+pub fn set_hf_token(state: State<'_, AppState>, args: Value) -> Result<Value, String> {+ crate::commands::mlx::set_hf_token(state.inner(), &args)+}++#[tauri::command]+pub fn hf_token_present(state: State<'_, AppState>, args: Value) -> Result<Value, String> {+ crate::commands::mlx::hf_token_present(state.inner(), &args)+}+#[tauri::command]pub fn mlx_image_install_model(state: State<'_, AppState>, args: Value) -> Result<Value, String> {crate::commands::mlx::mlx_image_install_model(state.inner(), &args)diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex 87948f2b..38a18edd 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -43,6 +43,49 @@ fn venv_pip() -> PathBuf {mlx_root().join("venv/bin/pip")}+/// The HuggingFace token the user stored in Settings, held in memory for the+/// lifetime of the process. `None` until the frontend pushes one.+static HF_TOKEN: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);++/// Every HuggingFace download this app makes goes out through here, so the+/// hub credentials are attached the same way in all of them.+///+/// Anonymous hub traffic is rate-limited hard: it does not fail outright, it+/// *crawls* — which reads as a broken app, not as a throttle (a pull measured+/// at 2.6 KB/s was misdiagnosed as a dead network line). Gated repos are out+/// of reach entirely without a token. HF_HOME stays with the caller: the image+/// lane shares one cache, the video lane downloads into per-model directories.+pub(crate) fn apply_hf_token(cmd: &mut Command) {+ let token = HF_TOKEN.read().ok().and_then(|t| t.clone());+ if let Some(t) = token {+ cmd.env("HF_TOKEN", t);+ }+}++/// Store the token from Settings. An empty string clears it — that is how the+/// user removes the token again, so it must not be stored as `Some("")`.+pub fn set_hf_token(_state: &AppState, args: &Value) -> CmdResult {+ let token = args+ .get("token")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .trim()+ .to_string();+ let present = !token.is_empty();+ *HF_TOKEN+ .write()+ .map_err(|_| crate::commands::internal("hf token lock poisoned"))? =+ present.then_some(token);+ Ok(json!({ "ok": true, "present": present }))+}++/// Whether a token is set. Never returns the token itself — the frontend+/// already has it, and nothing else has any business reading it back.+pub fn hf_token_present(_state: &AppState, _args: &Value) -> CmdResult {+ let present = HF_TOKEN.read().ok().and_then(|t| t.clone()).is_some();+ Ok(json!({ "present": present }))+}+fn sidecar_running() -> bool {std::net::TcpStream::connect_timeout(&format!("127.0.0.1:{MLX_PORT}").parse().unwrap(),@@ -212,9 +255,12 @@ fn install_mlx_steps(slot: &crate::install_state::InstallSlot) -> Result<(), Strp = patterns,);let prefetch = prefetch.as_str();- let out = Command::new(venv_python())+ let mut prefetch_cmd = Command::new(venv_python());+ prefetch_cmd.args(["-c", prefetch])- .env("HF_HOME", mlx_root().join("cache"))+ .env("HF_HOME", mlx_root().join("cache"));+ apply_hf_token(&mut prefetch_cmd);+ let out = prefetch_cmd.output().map_err(|e| format!("model prefetch spawn: {e}"))?;if !out.status.success() {@@ -569,6 +615,7 @@ pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {let mut cmd = Command::new(&python);cmd.args(["-c", &script]).env("HF_HOME", mlx_root().join("cache"));+ apply_hf_token(&mut cmd);if let Err(e) = crate::commands::video::run_streamed(&slot2, &mut cmd) {slot2.fail(e);} else if !image_model_is_installed(&entry2) {@@ -654,6 +701,9 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {"guidance": entry.guidance,"cfg_param": entry.cfg_param,"disable_safety_checker": entry.disable_safety_checker,+ // We already own every file of this model — say so, and the load stops+ // going to the hub. That is what makes an offline render possible.+ "local_files_only": image_model_is_installed(entry),});let res = client.post(format!("http://127.0.0.1:{MLX_PORT}/generate"))@@ -745,12 +795,17 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {.try_clone().map_err(|e| crate::commands::internal(e.to_string()))?;- Command::new(venv_python())+ // The sidecar re-validates every file of a model against the hub when it+ // loads one, so it needs the token as much as the installer does.+ let mut server_cmd = Command::new(venv_python());+ server_cmd.arg(&server).env("LU_MLX_PORT", MLX_PORT.to_string()).env("HF_HOME", mlx_root().join("cache")).stdout(stdout)- .stderr(stderr)+ .stderr(stderr);+ apply_hf_token(&mut server_cmd);+ server_cmd.spawn().map_err(|e| crate::commands::internal(format!("spawn mlx server: {e}")))?;@@ -772,6 +827,59 @@ const SERVER_PY: &str = include_str!("../../resources/mlx/server.py");mod tests {use super::*;+ /// The token is a process-wide secret, so these run as one test — two+ /// #[test]s would race each other through the same lock.+ #[test]+ fn hf_token_round_trip_and_clear() {+ let state = AppState::new();++ // Absent by default: a fresh install has no token and must not send one.+ *HF_TOKEN.write().unwrap() = None;+ let mut cmd = Command::new("true");+ apply_hf_token(&mut cmd);+ assert!(+ !cmd.get_envs().any(|(k, _)| k == "HF_TOKEN"),+ "no token stored → no HF_TOKEN on the download process"+ );++ set_hf_token(&state, &json!({ "token": " hf_secret " })).unwrap();+ assert_eq!(+ hf_token_present(&state, &json!({})).unwrap()["present"],+ json!(true)+ );+ let mut cmd = Command::new("true");+ apply_hf_token(&mut cmd);+ let sent = cmd+ .get_envs()+ .find(|(k, _)| *k == "HF_TOKEN")+ .and_then(|(_, v)| v)+ .map(|v| v.to_string_lossy().into_owned());+ // Trimmed: a token pasted with a trailing newline must still work.+ assert_eq!(sent.as_deref(), Some("hf_secret"));++ // Clearing is how the user removes the token — an empty string must+ // not be stored as a token that then goes out as an empty header.+ set_hf_token(&state, &json!({ "token": " " })).unwrap();+ assert_eq!(+ hf_token_present(&state, &json!({})).unwrap()["present"],+ json!(false)+ );+ let mut cmd = Command::new("true");+ apply_hf_token(&mut cmd);+ assert!(!cmd.get_envs().any(|(k, _)| k == "HF_TOKEN"));+ }++ /// `hf_token_present` answers yes/no; leaking the value back to any caller+ /// would put a live credential into logs and remote responses.+ #[test]+ fn hf_token_status_never_returns_the_token() {+ let state = AppState::new();+ set_hf_token(&state, &json!({ "token": "hf_do_not_leak" })).unwrap();+ let body = hf_token_present(&state, &json!({})).unwrap();+ assert!(!body.to_string().contains("hf_do_not_leak"));+ *HF_TOKEN.write().unwrap() = None;+ }+#[test]fn mlx_root_lives_under_data_dir() {let r = mlx_root();diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rsindex 4989663a..b055a965 100644--- a/src-tauri/src/commands/video.rs+++ b/src-tauri/src/commands/video.rs@@ -511,6 +511,7 @@ fn install_model_steps();let mut cmd = Command::new(python);cmd.args(["-c", &script]);+ crate::commands::mlx::apply_hf_token(&mut cmd);run_streamed(slot, &mut cmd)?;if !entry.needs_convert {diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 1082a9d2..a4caa9af 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -213,6 +213,8 @@ fn main() {commands::media_cmds::mlx_unload,commands::media_cmds::mlx_generate,commands::media_cmds::mlx_image_models,+ commands::media_cmds::set_hf_token,+ commands::media_cmds::hf_token_present,commands::media_cmds::mlx_image_install_model,commands::media_cmds::mlx_image_install_status,commands::media_cmds::mlx_image_delete_model,diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.tsindex f60b50a8..9464a94f 100644--- a/src/api/mlx-image.ts+++ b/src/api/mlx-image.ts@@ -128,6 +128,28 @@ export async function getMlxImageEngineStatus(): Promise<MlxInstallStatus> {return invokeMedia<MlxInstallStatus>('install_mlx_diffusion_status')}+/** Keychain account for the HuggingFace token (see stores/providerStore). */+export const HF_TOKEN_ACCOUNT = 'huggingface-token'++/**+ * Hand the HuggingFace token to Rust, which attaches it to every model+ * download it spawns. Anonymous hub traffic gets rate-limited into the ground+ * — a download that crawls at kilobytes per second is throttling, not a bad+ * connection — and gated repos need a token outright.+ *+ * Rust keeps it in memory only; the keychain is the store of record, so this+ * has to run again on every app start.+ */+export async function applyHfToken(token: string): Promise<{ present: boolean }> {+ return invokeMedia<{ present: boolean }>('set_hf_token', { token })+}++/** Whether Rust currently holds a token. Never returns the token itself. */+export async function hfTokenPresent(): Promise<boolean> {+ const r = await invokeMedia<{ present: boolean }>('hf_token_present')+ return !!r?.present+}+export type MlxImageDecision = 'use' | 'start' | 'comfyui' | 'unavailable'export function decideMlxImageBackend(opts: {diff --git a/src/components/settings/MlxMediaSettings.tsx b/src/components/settings/MlxMediaSettings.tsxindex afa7ffc2..19e66468 100644--- a/src/components/settings/MlxMediaSettings.tsx+++ b/src/components/settings/MlxMediaSettings.tsx@@ -10,7 +10,7 @@// while something runs instead of holding progress in React.import { useCallback, useEffect, useRef, useState } from 'react'-import { Cpu, Download, Trash2, Loader2, Check, AlertTriangle, Film, Image as ImageIcon } from 'lucide-react'+import { Cpu, Download, Trash2, Loader2, Check, AlertTriangle, Film, Image as ImageIcon, KeyRound } from 'lucide-react'import {mlxStatus,listMlxImageModels,@@ -19,9 +19,12 @@ import {deleteMlxImageModel,installMlxImageEngine,getMlxImageEngineStatus,+ applyHfToken,+ HF_TOKEN_ACCOUNT,type MlxStatus,type MlxImageModel,} from '../../api/mlx-image'+import { secretGet, secretSet } from '../../api/backend'import {getVideoStatus,listVideoModels,@@ -74,6 +77,9 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {const [progress, setProgress] = useState<string | null>(null)const [error, setError] = useState<string | null>(null)const [confirmDelete, setConfirmDelete] = useState<string | null>(null)+ const [hfToken, setHfToken] = useState('')+ const [hfSaving, setHfSaving] = useState(false)+ const [hfSaved, setHfSaved] = useState(false)// Keep the latest busy kind readable from inside the interval callback// without re-arming the timer on every state change.@@ -97,6 +103,33 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {void refresh()}, [refresh])+ // The keychain is the store of record; Rust only holds the token in memory,+ // so every app start has to push it down again. Doing that here means the+ // token is live before the user can start a download from this very panel.+ useEffect(() => {+ void (async () => {+ const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)+ if (!stored) return+ setHfToken(stored)+ await applyHfToken(stored).catch(() => {})+ })()+ }, [])++ const saveHfToken = useCallback(async () => {+ setHfSaving(true)+ setError(null)+ try {+ const value = hfToken.trim()+ await secretSet(HF_TOKEN_ACCOUNT, value)+ await applyHfToken(value)+ setHfSaved(true)+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ } finally {+ setHfSaving(false)+ }+ }, [hfToken])+// Poll the Rust install slot for whichever install is running.useEffect(() => {if (!busy) return@@ -254,6 +287,34 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {</div>)}+ <div className="p-2.5 rounded-lg border border-gray-200 dark:border-white/8">+ <div className="flex items-center gap-1.5">+ <KeyRound size={12} className="text-gray-500" />+ <span className="text-[0.7rem] text-gray-800 dark:text-gray-200">HuggingFace token</span>+ <span className="text-[0.55rem] text-gray-500">optional</span>+ </div>+ <div className="text-[0.6rem] text-gray-500 leading-relaxed mt-1">+ Models download from HuggingFace. Without a token those downloads are anonymous, and the hub throttles them+ heavily — a slow download is almost always this. A free token also unlocks models that require accepting a+ licence. Stored in your Mac keychain, never sent anywhere but HuggingFace.+ </div>+ <div className="flex gap-1.5 mt-2">+ <input+ type="password"+ value={hfToken}+ onChange={(e) => { setHfToken(e.target.value); setHfSaved(false) }}+ placeholder="hf_…"+ spellCheck={false}+ aria-label="HuggingFace token"+ className="flex-1 min-w-0 px-2 py-1 rounded text-[0.65rem] font-mono bg-gray-50 dark:bg-white/[0.04] border border-gray-200 dark:border-white/10 outline-none focus:border-purple-400"+ />+ <button className={primaryCls} onClick={saveHfToken} disabled={hfSaving}>+ {hfSaved ? <Check size={11} /> : null}+ {hfSaved ? 'Saved' : 'Save'}+ </button>+ </div>+ </div>+{/* ── Image ─────────────────────────────────────────── */}{showImage && (<><div className="flex items-center gap-1.5 pt-1">