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(models): HuggingFace token rides along on every hub download
purplec9a68cb5fc4c
diff --git a/e2e/mac-create-mlx.spec.ts b/e2e/mac-create-mlx.spec.tsindex ce86606b..9e0b9498 100644--- a/e2e/mac-create-mlx.spec.ts+++ b/e2e/mac-create-mlx.spec.ts@@ -207,3 +207,52 @@ test('windows local is unchanged: ComfyUI lanes still offered', async ({ page })await expect(page.getByRole('radio', { name: 'Animate Image', exact: true })).toBeVisible()await expect(page.getByRole('radio', { name: 'Music', exact: true })).toBeVisible()})++test('mac: saving the HuggingFace token in Settings pushes it to Rust', async ({ page }) => {+ // #160: without a token every hub download is anonymous and throttled.+ // Saving in Settings must arm Rust immediately, and the recorded call may+ // only say that a token is present, never echo the value.+ await page.addInitScript(tauriMockInit, MAC_OPTS)+ await seedOnboardingDone(page)+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })+ await page.goto('/')+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })++ await page.getByRole('button', { name: /^Settings$/ }).click()+ await page.getByRole('button', { name: /AI Backends/i }).click()+ await page.getByRole('button', { name: /Local Media \(Apple MLX\)/i }).click()++ await page.getByLabel('HuggingFace token').fill('hf_e2e_probe')+ await page.getByRole('button', { name: /^Save$/ }).click()+ await expect(page.getByRole('button', { name: /Saved/i })).toBeVisible({ timeout: 10_000 })++ const token = await page.evaluate(() => (window as unknown as { __E2E_HF_TOKEN__?: string }).__E2E_HF_TOKEN__)+ expect(token).toBe('hf_e2e_probe')++ const call = ((await mlxCalls(page)) as any[]).find((c) => c.cmd === 'set_hf_token')+ expect(call).toMatchObject({ present: true })+ expect(JSON.stringify(call)).not.toContain('hf_e2e_probe')+})++test('mac: a stored token reaches Rust at boot, without opening Settings', async ({ page }) => {+ // The keychain is the store of record and Rust holds the token in memory+ // only, so a fresh app start must push it down again on its own. If it did+ // not, a download started straight from Create or the Model Manager would+ // still go out anonymous.+ await page.addInitScript(tauriMockInit, MAC_OPTS)+ await page.addInitScript(() => {+ ;(window as unknown as { __E2E_SECRETS__: Record<string, string> }).__E2E_SECRETS__ = {+ 'huggingface-token': 'hf_boot_probe',+ }+ })+ await seedOnboardingDone(page)+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })+ await page.goto('/')+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })++ await expect+ .poll(async () => page.evaluate(() => (window as unknown as { __E2E_HF_TOKEN__?: string }).__E2E_HF_TOKEN__), {+ timeout: 15_000,+ })+ .toBe('hf_boot_probe')+})diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.tsindex c8a53e70..8613f503 100644--- a/e2e/support/tauri-mock.ts+++ b/e2e/support/tauri-mock.ts@@ -100,8 +100,14 @@ export function tauriMockInit(opts: TauriMockOptions) {images: new Set<string>(opts.mlx?.installedImages ?? ['sd-turbo']),videos: new Set<string>(opts.mlx?.installedVideos ?? ['wan21-t2v-1.3b']),}- // One install slot per kind, exactly like the Rust side.- const slot = { image: 0, imageEngine: 0, video: 0, videoEngine: 0 }+ // One install slot per kind, exactly like the Rust side: null means idle+ // (nothing was ever started), a number counts polls since the install began.+ const slot: Record<'image' | 'imageEngine' | 'video' | 'videoEngine', number | null> = {+ image: null,+ imageEngine: null,+ video: null,+ videoEngine: null,+ }let pendingImageId: string | null = nulllet pendingVideoId: string | null = null// 1x1 transparent PNG — enough for the gallery to render something real.@@ -113,8 +119,24 @@ export function tauriMockInit(opts: TauriMockOptions) {}/** Advance an install slot; report 'complete' once it has been polled enough. */function installStatus(key: keyof typeof slot, extra?: Record<string, unknown>) {- slot[key] += 1- const done = slot[key] >= MLX_INSTALL_POLLS+ const n = slot[key]+ // Rust semantics: a slot nobody started reads 'idle', and polling it does+ // not advance anything. The download tray probes all four slots at boot+ // (adopt), so a mock that advances on read would install engines by+ // merely being looked at.+ if (n === null) {+ return {+ status: 'idle',+ logs: [] as string[],+ error: null,+ download_progress: 0,+ download_total: 0,+ download_speed: 0,+ ...extra,+ }+ }+ slot[key] = n + 1+ const done = n + 1 >= MLX_INSTALL_POLLSreturn {status: done ? 'complete' : 'installing',logs: done ? ['download complete', 'ready'] : ['starting…', 'downloading…'],@@ -245,6 +267,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..3f746a64 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. "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 1aec6a9d..6544afe4 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 rather than 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, because that is+/// how the user removes the token again; 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() {@@ -494,7 +540,7 @@ pub fn mlx_image_models(_state: &AppState, _args: &Value) -> CmdResult {"name": c.name,"repo": c.repo,// f32→JSON goes through f64 and turns 2.6 into- // 2.5999999046325684 — round to the tenth the catalog means.+ // 2.5999999046325684, so round to the tenth the catalog means."sizeGB": (c.size_gb as f64 * 10.0).round() / 10.0,"minRamGB": c.min_ram_gb,"steps": c.steps,@@ -576,6 +622,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) {@@ -661,6 +708,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"))@@ -752,12 +802,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}")))?;@@ -779,6 +834,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 e01b84e8..80c91284 100644--- a/src-tauri/src/commands/video.rs+++ b/src-tauri/src/commands/video.rs@@ -518,6 +518,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/install_state.rs b/src-tauri/src/install_state.rsindex 58ca9238..19721242 100644--- a/src-tauri/src/install_state.rs+++ b/src-tauri/src/install_state.rs@@ -100,7 +100,7 @@ fn dir_size(path: &std::path::Path) -> u64 {/// Feed a slot's byte progress from the size of the directory the download/// writes into, until the slot leaves "installing". The installers shell out/// to `huggingface_hub.snapshot_download`, which reports nothing machine--/// readable on stdout — the growing target directory is the one progress+/// readable on stdout; the growing target directory is the one progress/// signal that exists on every platform.pub fn watch_dir_size(slot: InstallSlot, dir: std::path::PathBuf, total_bytes: u64) {std::thread::spawn(move || {@@ -149,7 +149,7 @@ mod tests {std::fs::write(sub.join("b.bin"), vec![0u8; 50]).unwrap();assert_eq!(dir_size(&root), 150);std::fs::remove_dir_all(&root).unwrap();- // A directory that does not exist yet reads as empty, not an error —+ // A directory that does not exist yet reads as empty, not an error;// the watcher starts before snapshot_download creates the target.assert_eq!(dir_size(&root), 0);}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/App.tsx b/src/App.tsxindex b026b2c2..fae8c083 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -10,6 +10,18 @@ function App() {import('@tauri-apps/api/core').then(({ invoke }) => {invoke('show_window').catch(() => {})})++ // The keychain is the store of record for the HuggingFace token; Rust+ // holds it in memory only, so every boot pushes it down again. Without+ // this, only opening Settings would arm the token, and a model download+ // started from Create or the Model Manager would still go out anonymous+ // and throttled.+ import('./api/mlx-image').then(async ({ isMlxImageHost, applyHfToken, HF_TOKEN_ACCOUNT }) => {+ if (!isMlxImageHost()) return+ const { secretGet } = await import('./api/backend')+ const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)+ if (stored) await applyHfToken(stored).catch(() => {})+ })}// Probe local Whisper (STT) once at boot and push the result into the voicediff --git a/src/api/mlx-image.ts b/src/api/mlx-image.tsindex 8fe3e155..11cc2b34 100644--- a/src/api/mlx-image.ts+++ b/src/api/mlx-image.ts@@ -131,6 +131,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. 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/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex 514350a0..e272d86a 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -40,7 +40,7 @@ export function DownloadBadge() {comfyBundles.get(bundleName)!.push({ id, d })}- // MLX installs (macOS image/video engines + models) — fed by the Rust+ // MLX installs (macOS image/video engines + models), fed by the Rust// install slots via mlxInstallStore.const mlxEntryMap = useMlxInstallStore(s => s.entries)const mlxEntries = Object.values(mlxEntryMap)diff --git a/src/components/settings/MlxMediaSettings.tsx b/src/components/settings/MlxMediaSettings.tsxindex 31921997..31a59ba6 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,@@ -75,6 +78,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.@@ -98,6 +104,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@@ -259,6 +292,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">diff --git a/src/stores/__tests__/mlxInstallStore.test.ts b/src/stores/__tests__/mlxInstallStore.test.tsindex 06f9be81..d443118e 100644--- a/src/stores/__tests__/mlxInstallStore.test.ts+++ b/src/stores/__tests__/mlxInstallStore.test.ts@@ -40,7 +40,7 @@ function slot(over: Record<string, unknown> = {}) {}}-// The immediate tick in watch() is pure microtasks — no timer advance needed.+// The immediate tick in watch() is pure microtasks, no timer advance needed.async function flush() {for (let i = 0; i < 5; i++) await Promise.resolve()}diff --git a/src/stores/mlxInstallStore.ts b/src/stores/mlxInstallStore.tsindex aac60796..70aeea72 100644--- a/src/stores/mlxInstallStore.ts+++ b/src/stores/mlxInstallStore.ts@@ -1,6 +1,6 @@// The MLX install slots live in Rust and were only ever polled by whichever// page started the install (Settings, Model Manager, Create). The download-// tray in the titlebar — the one place the user actually watches — never saw+// tray in the titlebar, the one place the user actually watches, never saw// them, so a 2.6 GB model pull showed nothing but a spinning "Installing…"// button (David, 2026-07-31). This store is the tray's window into those// slots: watch() follows one install to its terminal state, adopt() picks up@@ -64,7 +64,7 @@ export const useMlxInstallStore = create<MlxInstallStoreState>()((set, get) => (try {s = await READERS[kind]()} catch {- return // transient — the slot is being written; next tick retries+ return // transient: the slot is being written; next tick retries}// 'idle' can only mean the app restarted under us; the install is gone.const status = s.status === 'installing' ? 'installing' : s.status === 'complete' ? 'complete' : s.status === 'error' ? 'error' : null@@ -98,7 +98,7 @@ export const useMlxInstallStore = create<MlxInstallStoreState>()((set, get) => (void tick()},- // Pick up installs already running in Rust that nobody is watching — e.g.+ // Pick up installs already running in Rust that nobody is watching, e.g.// the user started one in Settings, the view unmounted, and the tray is the// only surface left. Callers gate this on macOS; the commands 400 elsewhere.adopt: async () => {