Skip to content

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.

feat(create): wire MLX image generation into the Create tab (Phase 6.3)

purplef10613e991bc
diff --git a/src/api/bridge-client.ts b/src/api/bridge-client.ts
new file mode 100644
index 00000000..df122dae
--- /dev/null
+++ b/src/api/bridge-client.ts
@@ -0,0 +1,55 @@
+/**
+ * lu-bridge media client (macOS Apple-Silicon MLX local media).
+ *
+ * Hard rule: Mac local image/video is MLX-via-lu-bridge only, never ComfyUI.
+ * The bundled `lu-bridge` sidecar (spawned by `start_media_bridge`, see
+ * src-tauri/src/commands/bridge.rs) serves `/cmd/:name` on 127.0.0.1:47711 with
+ * NO auth (loopback bind IS the boundary). This is the single transport the
+ * MLX image/video API wrappers use — the desktop analogue of the web app's
+ * `backendCall` (which POSTs to the same `/cmd/*` on a paired bridge URL).
+ */
+import { localFetch, backendCall } from './backend'
+
+const BRIDGE_BASE = 'http://127.0.0.1:47711'
+
+// Memoized "ensure the sidecar is up" promise. `start_media_bridge` is
+// idempotent (no-op if already healthy), so we only pay the spawn+health-wait
+// once per session; a failure clears the memo so the next call retries.
+let _bridgeReady: Promise<void> | null = null
+
+export function ensureMediaBridge(): Promise<void> {
+ if (!_bridgeReady) {
+ _bridgeReady = backendCall('start_media_bridge')
+ .then(() => undefined)
+ .catch((e) => {
+ _bridgeReady = null
+ throw e
+ })
+ }
+ return _bridgeReady
+}
+
+/**
+ * POST a bridge command. Ensures the sidecar is running first, then proxies
+ * the call to `127.0.0.1:47711/cmd/<command>` through `localFetch` (Tauri Rust
+ * proxy → bypasses CORS). `timeoutMs` defaults to 30 s for status/catalog
+ * calls; generation calls (a single long-blocking request) pass a large value.
+ */
+export async function bridgeCmd<T = unknown>(
+ command: string,
+ args?: Record<string, unknown>,
+ timeoutMs = 30_000,
+): Promise<T> {
+ await ensureMediaBridge()
+ const res = await localFetch(`${BRIDGE_BASE}/cmd/${command}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(args ?? {}),
+ timeoutMs,
+ })
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as { error?: string }
+ throw new Error(body.error || `HTTP ${res.status}`)
+ }
+ return res.json() as Promise<T>
+}
diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.ts
new file mode 100644
index 00000000..fb577cf5
--- /dev/null
+++ b/src/api/mlx-image.ts
@@ -0,0 +1,216 @@
+/**
+ * MLX-Stable-Diffusion image pipeline (Apple Silicon), via the bundled
+ * lu-bridge sidecar. Ported from uselu/apps/web/api/mlx-image.ts — the only
+ * change is the transport (`bridgeCmd` → 127.0.0.1:47711/cmd/*) plus a
+ * readiness wait: the FastAPI sidecar (:47712) binds a beat after `mlx_start`
+ * returns, so a cold first generate can race and 500 with "mlx unreachable".
+ *
+ * Hard rule: this is the Mac local image backend, NOT ComfyUI.
+ */
+import { bridgeCmd } from './bridge-client'
+import { isMacOS } from './backend'
+import type { ClassifiedModel } from './comfyui'
+
+export interface MlxStatus {
+ installed: boolean
+ running: boolean
+ port: number
+ modelLoaded?: boolean
+ modelRepo?: string | null
+ idleSeconds?: number | null
+}
+
+/** One bridge image-catalog entry (bridge commands/mlx.rs IMAGE_CATALOG). */
+export interface MlxImageModel {
+ id: string
+ name: string
+ repo: string
+ sizeGB: number
+ minRamGB: number
+ steps: number
+ guidance: number
+ defaultSize: number
+ unfiltered: boolean
+ description: string
+ installed: boolean
+}
+
+export interface MlxInstallStatus {
+ status: 'idle' | 'installing' | 'complete' | 'error'
+ logs: string[]
+ error: string | null
+}
+
+export interface MlxGenerateArgs {
+ prompt: string
+ model?: string
+ steps?: number
+ seed?: number
+ width?: number
+ height?: number
+ negativePrompt?: string
+}
+
+export interface MlxGenerateResult {
+ image_base64: string
+ width: number
+ height: number
+}
+
+export async function mlxStatus(): Promise<MlxStatus> {
+ return bridgeCmd<MlxStatus>('mlx_status')
+}
+
+export async function mlxStart(): Promise<{ ok: boolean; port: number }> {
+ return bridgeCmd<{ ok: boolean; port: number }>('mlx_start')
+}
+
+export async function mlxUnload(): Promise<{ ok: boolean; was_loaded: boolean; running: boolean }> {
+ return bridgeCmd('mlx_unload')
+}
+
+export async function mlxGenerate(args: MlxGenerateArgs): Promise<MlxGenerateResult> {
+ const body: Record<string, unknown> = { prompt: args.prompt }
+ if (args.model) body.model = args.model
+ if (args.steps != null) body.steps = args.steps
+ if (args.seed != null && args.seed !== -1) body.seed = args.seed
+ if (args.width != null) body.width = args.width
+ if (args.height != null) body.height = args.height
+ if (args.negativePrompt) body.negative_prompt = args.negativePrompt
+ // A single long-blocking request (model load + diffusion) — allow 5 min.
+ return bridgeCmd<MlxGenerateResult>('mlx_generate', body, 300_000)
+}
+
+export async function listMlxImageModels(): Promise<MlxImageModel[]> {
+ return bridgeCmd<MlxImageModel[]>('mlx_image_models')
+}
+
+export async function installMlxImageModel(
+ id: string,
+): Promise<{ ok: boolean; status: string; id?: string }> {
+ return bridgeCmd('mlx_image_install_model', { id })
+}
+
+export async function getMlxImageInstallStatus(): Promise<MlxInstallStatus> {
+ return bridgeCmd<MlxInstallStatus>('mlx_image_install_status')
+}
+
+export async function deleteMlxImageModel(id: string): Promise<{ ok: boolean; id: string }> {
+ return bridgeCmd('mlx_image_delete_model', { id })
+}
+
+/** Install the MLX image engine itself (venv + torch/diffusers sidecar). */
+export async function installMlxImageEngine(): Promise<{ ok: boolean; status: string }> {
+ return bridgeCmd('install_mlx_diffusion', {}, 1_800_000)
+}
+
+export async function getMlxImageEngineStatus(): Promise<MlxInstallStatus> {
+ return bridgeCmd<MlxInstallStatus>('install_mlx_diffusion_status')
+}
+
+export type MlxImageDecision = 'use' | 'start' | 'comfyui' | 'unavailable'
+
+export function decideMlxImageBackend(opts: {
+ isAppleSilicon: boolean
+ comfyHasModels: boolean
+ mlx: MlxStatus | null
+}): MlxImageDecision {
+ if (opts.comfyHasModels) return 'comfyui'
+ if (!opts.isAppleSilicon) return 'comfyui'
+ if (!opts.mlx || !opts.mlx.installed) return 'unavailable'
+ return opts.mlx.running ? 'use' : 'start'
+}
+
+/** Poll `mlx_status` until the sidecar reports `running`, or time out. */
+async function waitForMlxRunning(timeoutMs = 30_000): Promise<void> {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ if ((await mlxStatus().catch(() => null))?.running) return
+ await new Promise((r) => setTimeout(r, 500))
+ }
+}
+
+/**
+ * Ensure the MLX sidecar is up and warm, then generate and return a
+ * ready-to-render PNG data URL. Throws on any failure so callers surface a
+ * single error string. Retries once on a transient "unreachable" — the cold
+ * sidecar binds its port a moment after `mlx_start` returns.
+ */
+export async function generateMlxImageDataUrl(
+ args: MlxGenerateArgs,
+): Promise<{ dataUrl: string; width: number; height: number }> {
+ const status = await mlxStatus()
+ if (!status.installed) {
+ throw new Error(
+ 'MLX image generation is not installed. Open Models → Discover → Mac Image to install it.',
+ )
+ }
+ if (!status.running) {
+ await mlxStart()
+ await waitForMlxRunning()
+ }
+ let result: MlxGenerateResult
+ try {
+ result = await mlxGenerate(args)
+ } catch (e) {
+ // Cold-start race: the sidecar port bound a beat late. Wait + retry once.
+ if (/unreachable|refused|reset|ECONNREFUSED/i.test(String(e))) {
+ await waitForMlxRunning()
+ result = await mlxGenerate(args)
+ } else {
+ throw e
+ }
+ }
+ return {
+ dataUrl: `data:image/png;base64,${result.image_base64}`,
+ width: result.width,
+ height: result.height,
+ }
+}
+
+/** True when this machine is a Mac (Apple Silicon build → the MLX host). */
+export function isMlxImageHost(): boolean {
+ return isMacOS()
+}
+
+export const MLX_MODEL_PREFIX = 'MLX '
+export const MLX_IMAGE_MODEL_NAME = 'MLX SD-Turbo'
+
+export function mlxDisplayName(m: Pick<MlxImageModel, 'name'>): string {
+ return `${MLX_MODEL_PREFIX}${m.name}`
+}
+
+const mlxIdByDisplayName = new Map<string, string>([[MLX_IMAGE_MODEL_NAME, 'sd-turbo']])
+
+/** Resolve a dropdown selection back to the bridge catalog id. */
+export function mlxModelIdFor(displayName: string | null | undefined): string {
+ return (displayName && mlxIdByDisplayName.get(displayName)) || 'sd-turbo'
+}
+
+export function mlxModelType(m: Pick<MlxImageModel, 'id' | 'defaultSize'>): ClassifiedModel['type'] {
+ if (m.id === 'z-image-turbo') return 'zimage'
+ return m.defaultSize >= 1024 ? 'sdxl' : 'sd15'
+}
+
+export function buildMlxImageModels(catalog: MlxImageModel[]): ClassifiedModel[] {
+ return catalog
+ .filter((m) => m.installed)
+ .map((m) => {
+ mlxIdByDisplayName.set(mlxDisplayName(m), m.id)
+ return { name: mlxDisplayName(m), type: mlxModelType(m), source: 'checkpoint' } satisfies ClassifiedModel
+ })
+}
+
+/** True when the given model name is a synthetic MLX image model. */
+export function isMlxImageModel(name: string | null | undefined): boolean {
+ return !!name && name.startsWith(MLX_MODEL_PREFIX)
+}
+
+/** Merge synthetic MLX models into ComfyUI image models — MLX first, dedup by name. */
+export function mergeImageModels(
+ comfy: ClassifiedModel[],
+ mlx: ClassifiedModel[],
+): ClassifiedModel[] {
+ const names = new Set(mlx.map((m) => m.name))
+ return [...mlx, ...comfy.filter((m) => !names.has(m.name))]
+}
diff --git a/src/api/mlx-video.ts b/src/api/mlx-video.ts
new file mode 100644
index 00000000..56be60d4
--- /dev/null
+++ b/src/api/mlx-video.ts
@@ -0,0 +1,123 @@
+/**
+ * MLX-video pipeline (Apple Silicon), via the bundled lu-bridge sidecar.
+ * Ported from uselu/apps/web/api/video.ts — transport swapped to `bridgeCmd`
+ * (127.0.0.1:47711/cmd/*). The bridge spawns `python -m mlx_video.<family>.
+ * generate` as a subprocess and exposes progress the frontend polls.
+ *
+ * Hard rule: this is the Mac local video backend, NOT ComfyUI. Only Apple
+ * Silicon Macs see a real surface — every call returns `available:false`
+ * elsewhere so the UI can dim/skip it.
+ */
+import { bridgeCmd } from './bridge-client'
+
+export interface VideoStatus {
+ available: boolean
+ appleSilicon: boolean
+ mlxInstalled: boolean
+ mlxVersion: string | null
+ pythonBin: string | null
+ modelsRoot: string
+ outputsRoot: string
+ installedModels: string[]
+ running: boolean
+}
+
+export interface VideoModel {
+ id: string
+ name: string
+ family: 'wan_2' | 'ltx_2' | string
+ repo: string
+ sizeGB: number
+ minRamGB: number
+ defaultFrames: number
+ needsConvert: boolean
+ unfiltered: boolean
+ description: string
+ installed: boolean
+}
+
+export interface VideoProgress {
+ running: boolean
+ status: 'idle' | 'installing' | 'complete' | 'error' | string
+ logs: string[]
+ error: string | null
+}
+
+export interface InstallStatus {
+ status: 'idle' | 'installing' | 'complete' | 'error'
+ logs: string[]
+ download_progress: number
+ download_total: number
+ download_speed: number
+ error: string | null
+}
+
+export interface GenerateParams {
+ id: string
+ prompt: string
+ seconds?: number
+ fps?: number
+ initImage?: string
+ seed?: number
+}
+
+export interface GenerateResult {
+ ok: boolean
+ jobId: string
+ pid: number
+ output: string
+}
+
+export async function getVideoStatus(): Promise<VideoStatus> {
+ return bridgeCmd<VideoStatus>('video_status')
+}
+
+export async function listVideoModels(): Promise<VideoModel[]> {
+ return bridgeCmd<VideoModel[]>('video_list_models')
+}
+
+export async function installMlxVideo(): Promise<{ ok: boolean; status: string }> {
+ return bridgeCmd<{ ok: boolean; status: string }>('video_install_mlx', {}, 1_800_000)
+}
+
+export async function getMlxInstallStatus(): Promise<InstallStatus> {
+ return bridgeCmd<InstallStatus>('video_install_mlx_status')
+}
+
+export async function installVideoModel(
+ id: string,
+): Promise<{ ok: boolean; status: string; id?: string }> {
+ return bridgeCmd('video_install_model', { id })
+}
+
+export async function getModelInstallStatus(): Promise<InstallStatus> {
+ return bridgeCmd<InstallStatus>('video_install_model_status')
+}
+
+export async function deleteVideoModel(id: string): Promise<{ ok: boolean; id: string }> {
+ return bridgeCmd('video_delete_model', { id })
+}
+
+export async function generateVideo(params: GenerateParams): Promise<GenerateResult> {
+ const body = {
+ id: params.id,
+ prompt: params.prompt,
+ seconds: params.seconds,
+ fps: params.fps,
+ init_image: params.initImage,
+ seed: params.seed,
+ }
+ // Kick off the subprocess; generation itself is polled via video_progress.
+ return bridgeCmd<GenerateResult>('video_generate', body, 120_000)
+}
+
+export async function getVideoProgress(): Promise<VideoProgress> {
+ return bridgeCmd<VideoProgress>('video_progress')
+}
+
+export async function cancelVideo(): Promise<{ ok: boolean }> {
+ return bridgeCmd<{ ok: boolean }>('video_cancel')
+}
+
+/** Bridge base for <video src> playback of a finished clip (served at /videos/:file). */
+export const MLX_VIDEO_BASE = 'http://127.0.0.1:47711'
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index fdb73c20..55623949 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -34,6 +34,10 @@ import { useCreateStore } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { injectParameters } from '../api/workflows'
import { preflightCheck } from '../api/preflight'
+import {
+ generateMlxImageDataUrl, isMlxImageHost, isMlxImageModel,
+ mlxStatus, listMlxImageModels, buildMlxImageModels, mergeImageModels, mlxModelIdFor,
+} from '../api/mlx-image'
export function useCreate() {
const [connected, setConnected] = useState<boolean | null>(null)
@@ -88,9 +92,31 @@ export function useCreate() {
setModelLoadError(null)
try {
- // Check connection first — if ComfyUI is down, don't waste time on model queries
+ // Apple Silicon: MLX is a first-class local image backend (hard rule —
+ // Mac local media is MLX-via-lu-bridge, never ComfyUI). Load the installed
+ // MLX catalog first (this also spins up the bundled bridge sidecar) so
+ // images work even when ComfyUI is absent — the normal Mac case.
+ let mlxImageModels: ClassifiedModel[] = []
+ if (isMlxImageHost()) {
+ try {
+ const mlx = await mlxStatus()
+ if (mlx.installed) mlxImageModels = buildMlxImageModels(await listMlxImageModels())
+ } catch { /* bridge/sidecar not up yet — treat as no MLX models */ }
+ }
+
+ // Check connection — if ComfyUI is down, don't waste time on its queries.
const comfyOk = await checkComfyConnection()
if (!comfyOk) {
+ // On Apple Silicon MLX alone is a valid image backend — don't bail.
+ if (mlxImageModels.length > 0) {
+ setImageModels(mlxImageModels)
+ const st = useCreateStore.getState()
+ st.setImageModelList(mlxImageModels)
+ if (!st.imageModel) st.setImageModel(mlxImageModels[0].name, mlxImageModels[0].type)
+ zeroModelRetries.current = 0
+ setModelsLoaded(true)
+ return
+ }
setModelLoadError('ComfyUI is not running. Start it from Settings or wait for auto-start.')
return
}
@@ -108,7 +134,10 @@ export function useCreate() {
detectVideoBackend(),
getAllNodeInfo().catch(() => null),
])
- const imgModels = comfyImgModels
+ // MLX entries go first so one is the default on a fresh Apple-Silicon box.
+ const imgModels = mlxImageModels.length
+ ? mergeImageModels(comfyImgModels, mlxImageModels)
+ : comfyImgModels
setImageModels(imgModels)
setVideoModelsList(vidModels)
setSamplerList(samplers)
@@ -266,8 +295,47 @@ export function useCreate() {
const maskFilename = mask?.filename
const isRemoveBg = mode === 'image' && removebg
- // Desktop port: the MLX video/image pipelines (Apple Silicon) are not
- // part of this build — ComfyUI is the only local backend.
+ // ── MLX image pipeline (Apple Silicon) — hard rule: Mac local image is
+ // MLX-via-lu-bridge, never ComfyUI. Routes on the SELECTED model being the
+ // synthetic MLX entry (a stale videoBackend must not hijack a real ComfyUI
+ // checkpoint). Generation returns a base64 PNG stored as a data URL on the
+ // gallery item, so display + download work with no ComfyUI /view route. ──
+ if (mode === 'image' && isMlxImageHost() && isMlxImageModel(imageModel) && !isRemoveBg) {
+ setError(null)
+ if (!prompt.trim()) { setError('Please enter a prompt.'); return }
+ setIsGenerating(true)
+ state.setProgressPhase('loading-model')
+ setProgress(10, 'Starting MLX image generation...')
+ addToPromptHistory(prompt)
+ const startTime = Date.now()
+ try {
+ state.setProgressPhase('sampling')
+ setProgress(40, 'Generating with MLX...')
+ const { dataUrl, width: outW, height: outH } = await generateMlxImageDataUrl({
+ prompt, steps, seed, width, height,
+ model: mlxModelIdFor(imageModel),
+ negativePrompt: negativePrompt || undefined,
+ })
+ const elapsed = Math.round((Date.now() - startTime) / 1000)
+ state.setProgressPhase('complete')
+ setProgress(100, 'Complete!')
+ state.setLastGenTime(`${elapsed}s`)
+ addToGallery({
+ id: uuid(), type: 'image', filename: `mlx-${Date.now()}.png`, subfolder: '',
+ dataUrl, prompt, negativePrompt, model: imageModel, modelType: 'unknown',
+ seed: seed === -1 ? 0 : seed, steps, cfgScale, sampler, scheduler,
+ width: outW || width, height: outH || height, batchSize: 1,
+ createdAt: Date.now(), builderUsed: 'dynamic', intent,
+ })
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e)
+ useCreateStore.getState().setError(`Generation failed: ${msg}`)
+ } finally {
+ useCreateStore.getState().setIsGenerating(false)
+ useCreateStore.getState().setProgress(0)
+ }
+ return
+ }
setError(null)
const activeModel = mode === 'image' ? imageModel : videoModel