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): install progress in the download tray, full width, clean sizes
purpleeebe2cc8cc31
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex 87948f2b..1aec6a9d 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -493,7 +493,9 @@ pub fn mlx_image_models(_state: &AppState, _args: &Value) -> CmdResult {"id": c.id,"name": c.name,"repo": c.repo,- "sizeGB": c.size_gb,+ // f32→JSON goes through f64 and turns 2.6 into+ // 2.5999999046325684 — 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,"guidance": c.guidance,@@ -542,6 +544,11 @@ pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {}slot.start();slot.log(format!("pulling {} ({} GB)", entry.repo, entry.size_gb));+ crate::install_state::watch_dir_size(+ slot.clone(),+ image_model_cache_dir(entry.repo),+ (entry.size_gb as f64 * 1e9) as u64,+ );let slot2 = slot.clone();let entry2 = entry.clone();std::thread::spawn(move || {diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rsindex 4989663a..e01b84e8 100644--- a/src-tauri/src/commands/video.rs+++ b/src-tauri/src/commands/video.rs@@ -368,7 +368,9 @@ pub fn video_list_models(_state: &AppState, _args: &Value) -> CmdResult {"name": c.name,"family": c.family,"repo": c.repo,- "sizeGB": c.size_gb,+ // f32→JSON goes through f64 and turns 2.6 into 2.5999999046325684+ // — round to the tenth the catalog means.+ "sizeGB": (c.size_gb as f64 * 10.0).round() / 10.0,"minRamGB": c.min_ram_gb,"defaultFrames": c.default_frames,"needsConvert": c.needs_convert,@@ -461,6 +463,11 @@ pub fn video_install_model(state: &AppState, args: &Value) -> CmdResult {std::fs::create_dir_all(parent).map_err(|e| internal(e.to_string()))?;}slot.start();+ crate::install_state::watch_dir_size(+ slot.clone(),+ model_dir(entry.id),+ (entry.size_gb as f64 * 1e9) as u64,+ );let slot2 = slot.clone();let entry2 = entry.clone();std::thread::spawn(move || {diff --git a/src-tauri/src/install_state.rs b/src-tauri/src/install_state.rsindex 41c21787..58ca9238 100644--- a/src-tauri/src/install_state.rs+++ b/src-tauri/src/install_state.rs@@ -61,10 +61,11 @@ impl InstallSlot {}}- pub fn set_download(&self, progress: u64, total: u64) {+ pub fn set_download(&self, progress: u64, total: u64, speed: u64) {let mut g = self.inner.lock().unwrap();- g.download_progress = progress;+ g.download_progress = if total > 0 { progress.min(total) } else { progress };g.download_total = total;+ g.download_speed = speed;}pub fn complete(&self, msg: impl Into<String>) {@@ -82,3 +83,74 @@ impl InstallSlot {g.logs.push(format!("ERROR: {m}"));}}++fn dir_size(path: &std::path::Path) -> u64 {+ let Ok(read) = std::fs::read_dir(path) else {+ return 0;+ };+ read.flatten()+ .map(|e| match e.metadata() {+ Ok(m) if m.is_dir() => dir_size(&e.path()),+ Ok(m) => m.len(),+ Err(_) => 0,+ })+ .sum()+}++/// 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+/// signal that exists on every platform.+pub fn watch_dir_size(slot: InstallSlot, dir: std::path::PathBuf, total_bytes: u64) {+ std::thread::spawn(move || {+ let mut last: Option<(std::time::Instant, u64)> = None;+ while slot.is_running() {+ let size = dir_size(&dir);+ let speed = match last {+ Some((t, prev)) if size > prev => {+ ((size - prev) as f64 / t.elapsed().as_secs_f64().max(0.001)) as u64+ }+ _ => 0,+ };+ last = Some((std::time::Instant::now(), size));+ slot.set_download(size, total_bytes, speed);+ std::thread::sleep(std::time::Duration::from_millis(1000));+ }+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn set_download_clamps_to_total_and_keeps_speed() {+ let slot = InstallSlot::default();+ slot.start();+ slot.set_download(500, 1000, 42);+ let s = slot.snapshot();+ assert_eq!((s.download_progress, s.download_total, s.download_speed), (500, 1000, 42));+ // A convert step growing the dir past the download size must not+ // report more than 100%.+ slot.set_download(1500, 1000, 7);+ assert_eq!(slot.snapshot().download_progress, 1000);+ // No known total: pass the raw byte count through.+ slot.set_download(1500, 0, 0);+ assert_eq!(slot.snapshot().download_progress, 1500);+ }++ #[test]+ fn dir_size_sums_nested_files() {+ let root = std::env::temp_dir().join(format!("lu-dirsize-{}", std::process::id()));+ let sub = root.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ std::fs::write(root.join("a.bin"), vec![0u8; 100]).unwrap();+ 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 —+ // the watcher starts before snapshot_download creates the target.+ assert_eq!(dir_size(&root), 0);+ }+}diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.tsindex f60b50a8..8fe3e155 100644--- a/src/api/mlx-image.ts+++ b/src/api/mlx-image.ts@@ -54,6 +54,9 @@ export interface MlxInstallStatus {status: 'idle' | 'installing' | 'complete' | 'error'logs: string[]error: string | null+ download_progress: number+ download_total: number+ download_speed: number}export interface MlxGenerateArgs {diff --git a/src/api/mlx-install.ts b/src/api/mlx-install.tsindex 413a17dd..a00fdb96 100644--- a/src/api/mlx-install.ts+++ b/src/api/mlx-install.ts@@ -14,6 +14,7 @@// downloader really is abortable).import { waitOrAbort } from '../lib/bundle-install'+import { useMlxInstallStore } from '../stores/mlxInstallStore'import {mlxStatus,listMlxImageModels,@@ -96,6 +97,7 @@ export async function installMlxStack(if (!st?.installed) {onProgress?.('Setting up the image engine (about 3 GB, one time)…')await installMlxImageEngine()+ useMlxInstallStore.getState().watch('image-engine', 'MLX image engine')await awaitSlot(getMlxImageEngineStatus, 'Image engine install', onProgress, signal)}const pick = smallest(await listMlxImageModels())@@ -104,6 +106,7 @@ export async function installMlxStack(if (!pick) returnonProgress?.(`Downloading ${pick.name} (${pick.sizeGB} GB)…`)await installMlxImageModel(pick.id)+ useMlxInstallStore.getState().watch('image-model', pick.name)await awaitSlot(getMlxImageInstallStatus, `${pick.name} download`, onProgress, signal)return}@@ -115,11 +118,13 @@ export async function installMlxStack(if (!vs?.mlxInstalled) {onProgress?.('Setting up the video engine (one time)…')await installMlxVideo()+ useMlxInstallStore.getState().watch('video-engine', 'MLX video engine')await awaitSlot(getMlxInstallStatus, 'Video engine install', onProgress, signal)}const pick = smallest(await listVideoModels())if (!pick) returnonProgress?.(`Downloading ${pick.name} (${pick.sizeGB} GB)…`)await installVideoModel(pick.id)+ useMlxInstallStore.getState().watch('video-model', pick.name)await awaitSlot(getModelInstallStatus, `${pick.name} download`, onProgress, signal)}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 51c715b9..51ae6995 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -797,7 +797,7 @@ export function AppShell() {<StorageQuotaToast /><div className="flex-1 flex overflow-hidden gap-2 p-2">{!isComparing && <Sidebar />}- <main className={`overflow-hidden rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] ${currentView === 'models' ? 'flex-none w-[85%] mx-auto' : 'flex-1'}`}>+ <main className="flex-1 overflow-hidden rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05]">{currentView === 'chat' && <ErrorBoundary><ChatView /></ErrorBoundary>}{currentView === 'models' && <ErrorBoundary><ModelManager /></ErrorBoundary>}{currentView === 'benchmark' && <ErrorBoundary><BenchmarkView /></ErrorBoundary>}diff --git a/src/components/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex 4f09593e..514350a0 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -3,6 +3,8 @@ import { motion, AnimatePresence } from 'framer-motion'import { ArrowDownToLine, Pause, Play, X, CheckCircle, RotateCcw } from 'lucide-react'import { useModels } from '../../hooks/useModels'import { useDownloadStore } from '../../stores/downloadStore'+import { useMlxInstallStore } from '../../stores/mlxInstallStore'+import { isMlxImageHost } from '../../api/mlx-image'import { formatBytes } from '../../lib/formatters'function ProgressBar({ progress }: { progress: number }) {@@ -38,8 +40,20 @@ export function DownloadBadge() {comfyBundles.get(bundleName)!.push({ id, d })}- const totalActive = textActiveCount + comfyActiveCount- const hasAny = textEntries.length > 0 || comfyEntries.length > 0+ // 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)+ const mlxActiveCount = mlxEntries.filter(e => e.status === 'installing').length++ // An install can already be running with no page watching it (started in+ // Settings, view unmounted). The badge is always mounted, so it adopts.+ useEffect(() => {+ if (isMlxImageHost()) void useMlxInstallStore.getState().adopt()+ }, [])++ const totalActive = textActiveCount + comfyActiveCount + mlxActiveCount+ const hasAny = textEntries.length > 0 || comfyEntries.length > 0 || mlxEntries.length > 0// Click outside to closeuseEffect(() => {@@ -114,13 +128,14 @@ export function DownloadBadge() {{/* Header */}<div className="flex items-center justify-between px-3 pt-2.5 pb-1"><span className="text-[0.65rem] font-semibold uppercase tracking-widest text-gray-500">- Downloads {hasAny && `(${textEntries.length + comfyEntries.length})`}+ Downloads {hasAny && `(${textEntries.length + comfyEntries.length + mlxEntries.length})`}</span>- {(textEntries.some(([, s]) => s.complete) || comfyEntries.some(([, d]) => d.status === 'complete')) && (+ {(textEntries.some(([, s]) => s.complete) || comfyEntries.some(([, d]) => d.status === 'complete') || mlxEntries.some(e => e.status === 'complete')) && (<buttononClick={() => {textEntries.filter(([, s]) => s.complete).forEach(([n]) => dismissPull(n))comfyEntries.filter(([, d]) => d.status === 'complete').forEach(([id]) => useDownloadStore.getState().dismiss(id))+ mlxEntries.filter(e => e.status === 'complete').forEach(e => useMlxInstallStore.getState().dismiss(e.kind))}}className="text-[0.6rem] text-gray-500 hover:text-gray-300 transition-colors">@@ -256,6 +271,37 @@ export function DownloadBadge() {</div>)})}++ {/* MLX installs (macOS image/video engines + models) */}+ {mlxEntries.map((e) => {+ const prog = e.total > 0 ? (e.progress / e.total) * 100 : 0+ return (+ <div key={e.kind} className="px-3 py-2 border-t border-gray-100 dark:border-white/[0.04] first:border-t-0">+ <div className="flex items-center justify-between gap-2 mb-1">+ <p className="text-[0.7rem] text-gray-700 dark:text-gray-300 truncate">{e.label}</p>+ {e.status !== 'installing' && (+ <button onClick={() => useMlxInstallStore.getState().dismiss(e.kind)} className="p-0.5 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300 transition-colors shrink-0" title="Dismiss"><X size={11} /></button>+ )}+ </div>+ {e.status === 'complete' ? (+ <div className="flex items-center gap-1.5 text-green-400"><CheckCircle size={11} /><span className="text-[0.65rem]">Complete</span></div>+ ) : e.status === 'error' ? (+ <p className="text-[0.6rem] text-red-400 break-words">{e.error || 'Install failed.'}</p>+ ) : e.total > 0 ? (+ <>+ <ProgressBar progress={prog} />+ <p className="text-[0.55rem] text-gray-500 mt-0.5">+ {formatBytes(e.progress)} / {formatBytes(e.total)}+ {prog > 0 && <span className="ml-1.5 text-blue-400">{Math.round(prog)}%</span>}+ {e.speed > 0 && <span className="ml-1.5 text-gray-400">{formatBytes(e.speed)}/s</span>}+ </p>+ </>+ ) : (+ <p className="text-[0.6rem] text-gray-500 truncate">{e.lastLog || 'Preparing…'}</p>+ )}+ </div>+ )+ })}</div></motion.div>)}diff --git a/src/components/settings/MlxMediaSettings.tsx b/src/components/settings/MlxMediaSettings.tsxindex afa7ffc2..31921997 100644--- a/src/components/settings/MlxMediaSettings.tsx+++ b/src/components/settings/MlxMediaSettings.tsx@@ -34,6 +34,7 @@ import {type VideoModel,} from '../../api/mlx-video'import { formatBytes } from '../../lib/formatters'+import { useMlxInstallStore } from '../../stores/mlxInstallStore'const POLL_MS = 1500@@ -149,13 +150,16 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {}}, [busy, refresh])- const start = async (next: NonNullable<Busy>, fn: () => Promise<unknown>) => {+ const start = async (next: NonNullable<Busy>, fn: () => Promise<unknown>, trayLabel: string) => {setError(null)setLog([])setProgress(null)setBusy(next)try {await fn()+ // Mirror the install into the titlebar download tray, which keeps+ // following it after this panel unmounts.+ useMlxInstallStore.getState().watch(next.kind, trayLabel)} catch (e) {setError(e instanceof Error ? e.message : String(e))setBusy(null)@@ -224,6 +228,7 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {start({ kind: kind === 'image' ? 'image-model' : 'video-model', id: m.id },() => (kind === 'image' ? installMlxImageModel(m.id) : installVideoModel(m.id)),+ m.name,)}>@@ -271,7 +276,7 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {</div></div>{!imageEngineReady && (- <button className={primaryCls} disabled={anyBusy} onClick={() => start({ kind: 'image-engine' }, installMlxImageEngine)}>+ <button className={primaryCls} disabled={anyBusy} onClick={() => start({ kind: 'image-engine' }, installMlxImageEngine, 'MLX image engine')}>{busy?.kind === 'image-engine' ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}{busy?.kind === 'image-engine' ? 'Installing…' : 'Install engine'}</button>@@ -307,7 +312,7 @@ export function MlxMediaSettings({ only }: { only?: 'image' | 'video' } = {}) {<buttonclassName={primaryCls}disabled={anyBusy || (video ? !video.appleSilicon : false)}- onClick={() => start({ kind: 'video-engine' }, installMlxVideo)}+ onClick={() => start({ kind: 'video-engine' }, installMlxVideo, 'MLX video engine')}>{busy?.kind === 'video-engine' ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}{busy?.kind === 'video-engine' ? 'Installing…' : 'Install engine'}diff --git a/src/stores/__tests__/mlxInstallStore.test.ts b/src/stores/__tests__/mlxInstallStore.test.tsnew file mode 100644index 00000000..06f9be81--- /dev/null+++ b/src/stores/__tests__/mlxInstallStore.test.ts@@ -0,0 +1,157 @@+/**+ * The download tray's window into the Rust MLX install slots (2026-07-31)+ *+ * David: a 2.6 GB model pull showed only a spinning "Installing…" button; the+ * titlebar download tray never listed it. This store is the tray's view of the+ * four Rust install slots. These tests pin the lifecycle: watch() follows a+ * slot to its terminal state and stops polling, 'idle' means the app restarted+ * under us (entry dismissed), a failed poll is transient and must not kill the+ * watch, and adopt() picks up exactly the installs nobody is watching.+ *+ * Run: npx vitest run src/stores/__tests__/mlxInstallStore.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const getMlxImageEngineStatus = vi.fn()+const getMlxImageInstallStatus = vi.fn()+const getMlxInstallStatus = vi.fn()+const getModelInstallStatus = vi.fn()++vi.mock('../../api/mlx-image', () => ({+ getMlxImageEngineStatus: (...a: any[]) => getMlxImageEngineStatus(...(a as [])),+ getMlxImageInstallStatus: (...a: any[]) => getMlxImageInstallStatus(...(a as [])),+}))+vi.mock('../../api/mlx-video', () => ({+ getMlxInstallStatus: (...a: any[]) => getMlxInstallStatus(...(a as [])),+ getModelInstallStatus: (...a: any[]) => getModelInstallStatus(...(a as [])),+}))++import { useMlxInstallStore } from '../mlxInstallStore'++function slot(over: Record<string, unknown> = {}) {+ return {+ status: 'installing',+ logs: [] as string[],+ error: null,+ download_progress: 0,+ download_total: 0,+ download_speed: 0,+ ...over,+ }+}++// 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()+}++const entries = () => useMlxInstallStore.getState().entries++describe('mlxInstallStore', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+ useMlxInstallStore.setState({ entries: {} })+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('follows an install to complete and stops polling', async () => {+ getMlxImageInstallStatus+ .mockResolvedValueOnce(+ slot({ download_progress: 500, download_total: 1000, download_speed: 42, logs: ['pulling weights'] }),+ )+ .mockResolvedValueOnce(slot({ status: 'complete', download_progress: 1000, download_total: 1000 }))++ useMlxInstallStore.getState().watch('image-model', 'SD Turbo')+ expect(entries()['image-model']).toMatchObject({ status: 'installing', label: 'SD Turbo' })++ await flush()+ expect(entries()['image-model']).toMatchObject({+ progress: 500,+ total: 1000,+ speed: 42,+ lastLog: 'pulling weights',+ })++ await vi.advanceTimersByTimeAsync(1200)+ expect(entries()['image-model']).toMatchObject({ status: 'complete', progress: 1000 })++ const calls = getMlxImageInstallStatus.mock.calls.length+ await vi.advanceTimersByTimeAsync(3600)+ expect(getMlxImageInstallStatus.mock.calls.length).toBe(calls)+ })++ it('keeps an errored install visible with its cause and stops polling', async () => {+ getModelInstallStatus.mockResolvedValueOnce(slot({ status: 'error', error: 'disk full' }))++ useMlxInstallStore.getState().watch('video-model', 'Wan 2.1')+ await flush()++ expect(entries()['video-model']).toMatchObject({ status: 'error', error: 'disk full' })++ const calls = getModelInstallStatus.mock.calls.length+ await vi.advanceTimersByTimeAsync(3600)+ expect(getModelInstallStatus.mock.calls.length).toBe(calls)+ })++ it('dismisses the entry when the slot reads idle (app restarted under us)', async () => {+ getMlxInstallStatus.mockResolvedValueOnce(slot({ status: 'idle' }))++ useMlxInstallStore.getState().watch('video-engine', 'MLX video engine')+ expect(entries()['video-engine']).toBeDefined()++ await flush()+ expect(entries()['video-engine']).toBeUndefined()++ const calls = getMlxInstallStatus.mock.calls.length+ await vi.advanceTimersByTimeAsync(3600)+ expect(getMlxInstallStatus.mock.calls.length).toBe(calls)+ })++ it('treats a failed poll as transient and keeps watching', async () => {+ getMlxImageEngineStatus+ .mockRejectedValueOnce(new Error('slot busy'))+ .mockResolvedValueOnce(slot({ status: 'complete' }))++ useMlxInstallStore.getState().watch('image-engine', 'MLX image engine')+ await flush()++ // The failed read left the seeded entry alone…+ expect(entries()['image-engine']).toMatchObject({ status: 'installing', progress: 0 })++ // …and the next interval tick still ran and saw the terminal state.+ await vi.advanceTimersByTimeAsync(1200)+ expect(entries()['image-engine']).toMatchObject({ status: 'complete' })+ })++ it('adopt() watches only slots that are mid-install', async () => {+ getMlxImageEngineStatus.mockResolvedValue(slot({ status: 'idle' }))+ getMlxImageInstallStatus+ .mockResolvedValueOnce(slot()) // adopt's probe+ .mockResolvedValueOnce(slot({ download_progress: 1, download_total: 2 })) // watch's immediate tick+ .mockResolvedValueOnce(slot({ status: 'complete' }))+ getMlxInstallStatus.mockRejectedValue(new Error('400 not this platform'))+ getModelInstallStatus.mockResolvedValue(slot({ status: 'complete' }))++ await useMlxInstallStore.getState().adopt()+ await flush()++ expect(Object.keys(entries())).toEqual(['image-model'])+ expect(entries()['image-model']).toMatchObject({ label: 'Image model', progress: 1, total: 2 })++ await vi.advanceTimersByTimeAsync(1200)+ expect(entries()['image-model']).toMatchObject({ status: 'complete' })+ })++ it('dismiss() removes an entry', async () => {+ getModelInstallStatus.mockResolvedValueOnce(slot({ status: 'complete' }))+ useMlxInstallStore.getState().watch('video-model', 'Wan 2.1')+ await flush()++ useMlxInstallStore.getState().dismiss('video-model')+ expect(entries()['video-model']).toBeUndefined()+ })+})diff --git a/src/stores/mlxInstallStore.ts b/src/stores/mlxInstallStore.tsnew file mode 100644index 00000000..aac60796--- /dev/null+++ b/src/stores/mlxInstallStore.ts@@ -0,0 +1,121 @@+// 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+// 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+// an install that is already running when the tray mounts.++import { create } from 'zustand'+import { getMlxImageInstallStatus, getMlxImageEngineStatus, type MlxInstallStatus } from '../api/mlx-image'+import { getMlxInstallStatus, getModelInstallStatus, type InstallStatus } from '../api/mlx-video'++const POLL_MS = 1200++export type MlxInstallKind = 'image-engine' | 'image-model' | 'video-engine' | 'video-model'++export interface MlxInstallEntry {+ kind: MlxInstallKind+ label: string+ status: 'installing' | 'complete' | 'error'+ progress: number+ total: number+ speed: number+ lastLog: string+ error: string | null+}++const READERS: Record<MlxInstallKind, () => Promise<MlxInstallStatus | InstallStatus>> = {+ 'image-engine': getMlxImageEngineStatus,+ 'image-model': getMlxImageInstallStatus,+ 'video-engine': getMlxInstallStatus,+ 'video-model': getModelInstallStatus,+}++const ADOPT_LABELS: Record<MlxInstallKind, string> = {+ 'image-engine': 'MLX image engine',+ 'image-model': 'Image model',+ 'video-engine': 'MLX video engine',+ 'video-model': 'Video model',+}++interface MlxInstallStoreState {+ entries: Record<string, MlxInstallEntry>+ watch: (kind: MlxInstallKind, label: string) => void+ adopt: () => Promise<void>+ dismiss: (kind: MlxInstallKind) => void+}++const timers: Partial<Record<MlxInstallKind, ReturnType<typeof setInterval>>> = {}++export const useMlxInstallStore = create<MlxInstallStoreState>()((set, get) => ({+ entries: {},++ watch: (kind, label) => {+ if (timers[kind]) return+ set((s) => ({+ entries: {+ ...s.entries,+ [kind]: { kind, label, status: 'installing', progress: 0, total: 0, speed: 0, lastLog: '', error: null },+ },+ }))+ const tick = async () => {+ let s: MlxInstallStatus | InstallStatus+ try {+ s = await READERS[kind]()+ } catch {+ 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+ if (status === null) {+ clearInterval(timers[kind])+ delete timers[kind]+ get().dismiss(kind)+ return+ }+ set((st) => ({+ entries: {+ ...st.entries,+ [kind]: {+ kind,+ label: st.entries[kind]?.label ?? label,+ status,+ progress: s.download_progress,+ total: s.download_total,+ speed: s.download_speed,+ lastLog: s.logs.length ? String(s.logs[s.logs.length - 1]) : '',+ error: s.error,+ },+ },+ }))+ if (status !== 'installing') {+ clearInterval(timers[kind])+ delete timers[kind]+ }+ }+ timers[kind] = setInterval(tick, POLL_MS)+ void tick()+ },++ // 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 () => {+ await Promise.all(+ (Object.keys(READERS) as MlxInstallKind[]).map(async (kind) => {+ if (timers[kind] || get().entries[kind]) return+ const s = await READERS[kind]().catch(() => null)+ if (s?.status === 'installing') get().watch(kind, ADOPT_LABELS[kind])+ }),+ )+ },++ dismiss: (kind) => {+ set((s) => {+ const entries = { ...s.entries }+ delete entries[kind]+ return { entries }+ })+ },+}))