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(mac): chat image_generate/video_generate tools use MLX on Mac + onboarding skips ComfyUI

purplec278bdee563f
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 92e275d1..d6b575c3 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -8,6 +8,8 @@ import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
+import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'
+import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, readVideoAsBlobUrl, type VideoModel } from '../mlx-video'
/**
* Helper: current chat id as a plain `{ chatId }` fragment to spread into
@@ -1040,6 +1042,13 @@ async function executeImageGenerate(args: Record<string, any>): Promise<string>
const flat: Record<string, any> = {}
for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+
+ // Hard rule: on macOS, local image generation is Apple MLX only — ComfyUI
+ // never runs there (see isMlxImageHost() / useCreate.ts's MLX image
+ // branch, the reference this mirrors). Route around the ComfyUI-only
+ // vram-handoff orchestrator + model-pick gate entirely.
+ if (isMlxImageHost()) return executeImageGenerateMlx(prompt, merged)
+
// Model-Picker gate (v2.5.3): BEFORE the VRAM swap, let the user pick the
// ComfyUI model in the tool call (or silently use the saved preference).
// Returns null when an explicit model arg exists / nothing is installed /
@@ -1067,6 +1076,16 @@ async function executeVideoGenerate(args: Record<string, any>): Promise<string>
const flat: Record<string, any> = {}
for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+
+ // Hard rule: on macOS, local video generation is Apple MLX only — ComfyUI
+ // never runs there. Route around vram-handoff entirely (no VRAM juggling —
+ // there is no local text-model/ComfyUI VRAM contention to manage: MLX runs
+ // its own subprocess).
+ if (isMlxImageHost()) {
+ const prompt = String(args.prompt ?? args.description ?? '').trim() || 'gentle, subtle natural motion'
+ return executeVideoGenerateMlx(prompt, merged)
+ }
+
// Model-Picker gate (v2.5.3) — see executeImageGenerate. T2V and I2V keep
// separate saved preferences (disjoint capability sets).
const { pickModelForGeneration } = await import('../model-pick')
@@ -1076,6 +1095,182 @@ async function executeVideoGenerate(args: Record<string, any>): Promise<string>
return vramHandoffGenerate('video', merged)
}
+// ── macOS MLX generation (hard rule: local image/video on Mac is MLX only,
+// never ComfyUI — see api/mlx-image.ts / api/mlx-video.ts module docs) ────
+
+/** Fuzzy-resolve a chat-typed model name against an installed MLX catalog by
+ * id or display name. Same tolerant-matching shape as resolveModelName in
+ * vram-handoff.ts, kept as a separate small helper so this Mac-only path
+ * doesn't pull in the ComfyUI-flavoured module. */
+function resolveMlxModel<T extends { id: string; name: string }>(
+ requested: string | undefined,
+ installed: T[],
+): T | null {
+ if (installed.length === 0 || !requested) return null
+ const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '')
+ const r = norm(requested)
+ if (!r) return null
+ return (
+ installed.find((m) => norm(m.id) === r || norm(m.name) === r) ??
+ installed.find((m) => norm(m.id).includes(r) || norm(m.name).includes(r)) ??
+ installed.find((m) => r.includes(norm(m.id)) || r.includes(norm(m.name))) ??
+ null
+ )
+}
+
+/** Decode a `data:image/png;base64,...` result into a compact `blob:` URL —
+ * same b64 → Blob → createObjectURL pattern as readVideoAsBlobUrl
+ * (mlx-video.ts). Keeps the multi-hundred-KB PNG OUT of the tool-result
+ * string that gets fed back into the model's context; only the short
+ * blob: URL (which the CSP's img-src already allows) goes there. */
+function pngDataUrlToObjectUrl(dataUrl: string): string {
+ const comma = dataUrl.indexOf(',')
+ const b64 = comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl
+ const bin = atob(b64)
+ const bytes = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
+ return URL.createObjectURL(new Blob([bytes], { type: 'image/png' }))
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms))
+}
+
+/**
+ * macOS image_generate — hard rule: local image on Mac is MLX only, never
+ * ComfyUI (ComfyUI is never even started on this platform). Mirrors the MLX
+ * image branch in useCreate.ts (generateMlxImageDataUrl → base64 PNG), then
+ * returns the SAME result shape pollAndExtract uses for the ComfyUI path —
+ * `${kind} generated: <file> (prompt: "...")\n<url>` — so ToolCallBlock
+ * renders it inline; only the url is a local blob: URL instead of a ComfyUI
+ * /view URL.
+ */
+async function executeImageGenerateMlx(prompt: string, merged: Record<string, any>): Promise<string> {
+ let installed: MlxImageModel[]
+ try {
+ installed = (await listMlxImageModels()).filter((m) => m.installed)
+ } catch (e) {
+ return `Error: Could not query MLX image models — ${e instanceof Error ? e.message : String(e)}.`
+ }
+ if (installed.length === 0) {
+ return 'Error: No MLX image model installed. Download one from Models → Discover → Mac Image (e.g. "MLX SD-Turbo") and try again.'
+ }
+ const requested = typeof merged.model === 'string' && merged.model ? merged.model : undefined
+ let model: MlxImageModel
+ if (requested) {
+ const resolved = resolveMlxModel(requested, installed)
+ if (!resolved) {
+ return `Error: No installed MLX image model matches "${requested}". Installed: ${installed.map((m) => m.name).join(', ')}.`
+ }
+ model = resolved
+ } else {
+ model = installed.find((m) => m.id === 'sd-turbo') ?? installed[0]
+ }
+
+ try {
+ const { dataUrl } = await generateMlxImageDataUrl({
+ prompt,
+ model: model.id,
+ steps: typeof merged.steps === 'number' ? merged.steps : undefined,
+ seed: typeof merged.seed === 'number' ? merged.seed : undefined,
+ width: typeof merged.width === 'number' ? merged.width : undefined,
+ height: typeof merged.height === 'number' ? merged.height : undefined,
+ negativePrompt: typeof merged.negativePrompt === 'string' ? merged.negativePrompt : undefined,
+ })
+ const filename = `mlx-${Date.now()}.png`
+ const url = pngDataUrlToObjectUrl(dataUrl)
+ return `Image generated: ${filename} (prompt: "${prompt}")\n${url}`
+ } catch (e) {
+ return `Image generation failed: ${e instanceof Error ? e.message : String(e)}`
+ }
+}
+
+/**
+ * macOS video_generate — hard rule: local video on Mac is MLX only, never
+ * ComfyUI. Text-to-video is the primary path. `inputImage` (image-to-video)
+ * passes through to mlx-video's `initImage`, which the Rust side validates
+ * as an absolute file path on disk — a chat-generated MLX image (data-URL
+ * only, never written to disk, per media_cmds.rs) cleanly fails there with
+ * "init_image not found: ...", the same honest-rejection shape this codebase
+ * uses for every other unsupported value, rather than silently ignoring it.
+ */
+async function executeVideoGenerateMlx(prompt: string, merged: Record<string, any>): Promise<string> {
+ let status: Awaited<ReturnType<typeof getVideoStatus>>
+ try {
+ status = await getVideoStatus()
+ } catch (e) {
+ return `Error: Could not query MLX video status — ${e instanceof Error ? e.message : String(e)}.`
+ }
+ if (!status.available) return 'Error: MLX video is Apple Silicon only.'
+ if (!status.mlxInstalled) return 'Error: mlx-video is not installed. Open Models → Discover → Mac Video to install it, then try again.'
+
+ let catalog: VideoModel[]
+ try {
+ catalog = (await listVideoModels()).filter((m) => m.installed)
+ } catch (e) {
+ return `Error: Could not query MLX video models — ${e instanceof Error ? e.message : String(e)}.`
+ }
+ if (catalog.length === 0) {
+ return 'Error: No MLX video model installed. Download one from Models → Discover → Mac Video (e.g. "Wan 2.1 — 1.3B") and try again.'
+ }
+ const requested = typeof merged.model === 'string' && merged.model ? merged.model : undefined
+ let model: VideoModel
+ if (requested) {
+ const resolved = resolveMlxModel(requested, catalog)
+ if (!resolved) {
+ return `Error: No installed MLX video model matches "${requested}". Installed: ${catalog.map((m) => m.name).join(', ')}.`
+ }
+ model = resolved
+ } else {
+ model = catalog[0]
+ }
+
+ const fps = typeof merged.fps === 'number' ? merged.fps : undefined
+ let seconds: number | undefined = typeof merged.seconds === 'number' ? merged.seconds : undefined
+ if (seconds == null && typeof merged.frames === 'number' && merged.frames > 0) {
+ seconds = merged.frames / (fps ?? 24)
+ }
+ const inputImage = typeof merged.inputImage === 'string' && merged.inputImage ? merged.inputImage : undefined
+
+ let job: Awaited<ReturnType<typeof generateMlxVideo>>
+ try {
+ job = await generateMlxVideo({
+ id: model.id,
+ prompt,
+ seconds,
+ fps,
+ seed: typeof merged.seed === 'number' ? merged.seed : undefined,
+ initImage: inputImage,
+ })
+ } catch (e) {
+ return `Video generation failed: ${e instanceof Error ? e.message : String(e)}`
+ }
+
+ const deadline = Date.now() + 10 * 60 * 1000
+ while (Date.now() < deadline) {
+ await sleep(2000)
+ let prog: Awaited<ReturnType<typeof getVideoProgress>>
+ try {
+ prog = await getVideoProgress()
+ } catch (e) {
+ return `Video generation failed: ${e instanceof Error ? e.message : String(e)}`
+ }
+ if (prog.status === 'complete') {
+ try {
+ const blobUrl = await readVideoAsBlobUrl(job.output)
+ const filename = job.output.split(/[\\/]/).pop() || `mlx-${Date.now()}.mp4`
+ return `Video generated: ${filename} (prompt: "${prompt}")\n${blobUrl}`
+ } catch (e) {
+ return `Video generation failed: could not read output — ${e instanceof Error ? e.message : String(e)}`
+ }
+ }
+ if (prog.status === 'error') {
+ return `Video generation failed: ${prog.error || 'mlx-video failed'}`
+ }
+ }
+ return 'Video generation timed out after 10 minutes.'
+}
+
async function executeGetCurrentTime(_args: Record<string, any>): Promise<string> {
try {
const data = await backendCall<{ unix: number; iso_local: string; iso_utc: string; timezone: string; timezone_offset: number }>(
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index 239a7577..e808ccee 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -71,6 +71,29 @@ export function comfyViewParams(url: string | null | undefined): { filename: str
}
}
+// Mac MLX media (hard rule: local image/video on Mac is MLX, never ComfyUI —
+// see api/mcp/builtin-tools.ts's executeImageGenerateMlx / executeVideoGenerateMlx).
+// There is no ComfyUI /view route for these, so the result carries a local
+// `blob:` (or, defensively, `data:`) URL created in THIS webview session
+// instead. Same F1 result shape as the ComfyUI path — `<kind> generated:
+// <file> (prompt: "...")\n<url>` — just a different url scheme. Exported for
+// unit testing.
+export function localMediaUrlFromResult(result: string | null | undefined): string | null {
+ if (!result) return null
+ const m = result.match(/(blob:[^\s)\]]+|data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[^\s)\]]+)/i)
+ return m ? m[1] : null
+}
+
+// Pull the "<file>" back out of the "<kind> generated: <file> (prompt: …"
+// prefix so the local-media Download button can suggest a real filename
+// (blob:/data: URLs carry no filename of their own, unlike a ComfyUI /view
+// URL's `filename=` query param). Exported for unit testing.
+export function localMediaFilenameFromResult(result: string | null | undefined): string | null {
+ if (!result) return null
+ const m = result.match(/^(?:Image|Video) generated:\s*(\S+)/)
+ return m ? m[1] : null
+}
+
interface Props {
toolCall: AgentToolCall
onApprove?: () => void
@@ -123,7 +146,13 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
// Computed once; rendered ALWAYS-visible below the header (even while the
// tool block is collapsed) so an auto-approved generation shows its picture
// without the user having to expand the block — konata's "and no image".
- const previewUrl = comfyViewUrlFromResult(toolCall.result)
+ // Two possible sources: a ComfyUI /view URL (Windows/Linux), or a local
+ // blob:/data: URL from the Mac MLX path (executeImageGenerateMlx /
+ // executeVideoGenerateMlx in api/mcp/builtin-tools.ts — no ComfyUI /view
+ // route exists for those).
+ const comfyPreviewUrl = comfyViewUrlFromResult(toolCall.result)
+ const localPreviewUrl = comfyPreviewUrl ? null : localMediaUrlFromResult(toolCall.result)
+ const previewUrl = comfyPreviewUrl ?? localPreviewUrl
// Model-Picker (v2.5.3): while a generation tool call is RUNNING and the
// executor's pre-VRAM-swap gate is waiting, render the picker inside this
@@ -144,12 +173,20 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
const [imgFailed, setImgFailed] = useState(false)
const effectivePreviewUrl = (() => {
if (!previewUrl) return null
+ // blob:/data: URLs (Mac MLX) are self-contained in this session — the
+ // ComfyUI-host retry below only ever applies to a relative /view path.
if (imgFailed && previewUrl.startsWith('/')) {
const path = previewUrl.startsWith('/comfyui/') ? previewUrl.slice('/comfyui'.length) : previewUrl
return `http://${getComfyHost()}:${getComfyPort()}${path}`
}
return previewUrl
})()
+ // A blob:/data: URL carries no `filename=` query param for isInlineVideoUrl
+ // to key off, so fall back to the tool name — accurate since the MLX video
+ // executor never produces an image result and vice versa.
+ const isVideoResult = !!localPreviewUrl
+ ? toolCall.toolName === 'video_generate'
+ : !!effectivePreviewUrl && isInlineVideoUrl(effectivePreviewUrl)
return (
<div className="mb-0.5">
@@ -214,7 +251,7 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
ComfyUI by comfyViewUrlFromResult (never auto-loads arbitrary URLs). */}
{previewUrl && effectivePreviewUrl && (
<div className="pl-5 pt-0.5 space-y-1">
- {isInlineVideoUrl(effectivePreviewUrl) ? (
+ {isVideoResult ? (
<video
src={effectivePreviewUrl}
controls
@@ -235,18 +272,33 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
)}
{/* Download (David 2026-06-12): generated media shows in the chat with
a Download button, ChatGPT-style — downloadComfyFile pulls the real
- bytes and saves via the native dialog. */}
+ bytes and saves via the native dialog. Mac MLX results have no
+ ComfyUI /view route to re-fetch from, so a plain anchor download
+ off the blob:/data: URL already in hand does the same job. */}
{(() => {
const p = comfyViewParams(effectivePreviewUrl)
- if (!p) return null
+ if (p) {
+ return (
+ <button
+ onClick={() => { void downloadComfyFile(p.filename, p.subfolder, p.type) }}
+ title="Download"
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-500 hover:bg-blue-500/25 border border-blue-500/30 transition-colors"
+ >
+ <Download size={11} /> Download
+ </button>
+ )
+ }
+ if (!localPreviewUrl) return null
+ const filename = localMediaFilenameFromResult(toolCall.result) || (isVideoResult ? 'video.mp4' : 'image.png')
return (
- <button
- onClick={() => { void downloadComfyFile(p.filename, p.subfolder, p.type) }}
+ <a
+ href={effectivePreviewUrl}
+ download={filename}
title="Download"
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-500 hover:bg-blue-500/25 border border-blue-500/30 transition-colors"
>
<Download size={11} /> Download
- </button>
+ </a>
)
})()}
</div>
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsx
index 614e3e92..342148f5 100644
--- a/src/components/onboarding/Onboarding.tsx
+++ b/src/components/onboarding/Onboarding.tsx
@@ -9,7 +9,7 @@ import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-det
import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'
import { useDownloadStore } from '../../stores/downloadStore'
import { ProgressBar } from '../ui/ProgressBar'
-import { openExternal } from '../../api/backend'
+import { openExternal, isMacOS } from '../../api/backend'
import { formatBytes } from '../../lib/formatters'
import { backendCall } from '../../api/backend'
import { getSystemVRAM } from '../../api/comfyui'
@@ -344,7 +344,17 @@ export function Onboarding() {
if (isTauri) backendCall('set_onboarding_done').catch(() => {})
}
- // Commit the chosen backend to the provider store and advance to ComfyUI.
+ // Hard rule: on macOS, local image/video generation is Apple MLX only —
+ // ComfyUI never runs there (see isMlxImageHost() / the image_generate +
+ // video_generate MLX routing in api/mcp/builtin-tools.ts). The ComfyUI
+ // wizard step would just auto-detect/install a backend that can't start on
+ // this platform, so skip straight to the model picker. MLX models are
+ // managed from Models → Discover after onboarding, same as any other
+ // model — no dedicated onboarding step for them.
+ const nextStepAfterBackends = (): Step => (isMacOS() ? 'models' : 'comfyui')
+
+ // Commit the chosen backend to the provider store and advance to ComfyUI
+ // (or straight to the model picker on macOS — see nextStepAfterBackends).
// Built-in (default) reasserts the managed OpenAI-slot config; a detected
// Ollama takes over the primary slot (managed built-in disabled) so there
// aren't two defaults; other OpenAI-compat backends fill the openai slot.
@@ -367,7 +377,7 @@ export function Onboarding() {
})
}
}
- setStep('comfyui')
+ setStep(nextStepAfterBackends())
}
/* ── Scan for backends ──────────────────────────────────── */
@@ -600,7 +610,11 @@ export function Onboarding() {
// are true. A `found && !complete` carcass (P14) keeps the install option
// visible so the user can re-trigger and let LU rebuild torch/deps.
useEffect(() => {
- if (step === 'comfyui' && !comfyFound && !comfyDetecting) {
+ // Belt-and-suspenders: nextStepAfterBackends() already routes macOS
+ // straight past this step, so `step` should never actually be 'comfyui'
+ // there — but never auto-detect/install ComfyUI on Mac regardless (hard
+ // rule: Mac local image/video is MLX only).
+ if (step === 'comfyui' && !isMacOS() && !comfyFound && !comfyDetecting) {
setComfyDetecting(true)
// First: enumerate ALL installs (Bug #3). When >1 we show a picker
// BEFORE auto-picking — preventing the ninjastic2008 trap where LU
@@ -727,7 +741,10 @@ export function Onboarding() {
const handleClose = async () => { const { getCurrentWindow } = await import('@tauri-apps/api/window'); getCurrentWindow().close() }
const winBtn = 'inline-flex items-center justify-center w-[46px] h-8 transition-colors text-gray-400 hover:text-gray-200'
- const stepIndex = STEP_ORDER.indexOf(step)
+ // Mac never visits 'comfyui' (see nextStepAfterBackends) — drop it from the
+ // dots too so the indicator doesn't show a step the user will never see.
+ const visibleStepOrder = isMacOS() ? STEP_ORDER.filter((s) => s !== 'comfyui') : STEP_ORDER
+ const stepIndex = visibleStepOrder.indexOf(step)
return (
<div className={`h-screen w-screen flex items-center justify-center p-4 ${bgClass}`}>
@@ -742,7 +759,7 @@ export function Onboarding() {
{/* Step indicator dots */}
<div className="fixed top-10 left-1/2 -translate-x-1/2 z-40 flex gap-1.5">
- {STEP_ORDER.map((s, i) => (
+ {visibleStepOrder.map((s, i) => (
<div key={s} className={`w-1.5 h-1.5 rounded-full transition-colors ${i <= stepIndex ? (isDark ? 'bg-white' : 'bg-gray-900') : (isDark ? 'bg-white/15' : 'bg-gray-300')}`} />
))}
</div>
@@ -1173,7 +1190,7 @@ export function Onboarding() {
)}
{(ollamaReady || lmstudioReady || (!ollamaInstalling && !lmstudioInstalling)) && (
<button
- onClick={() => setStep('comfyui')}
+ onClick={() => setStep(nextStepAfterBackends())}
className={(ollamaReady || lmstudioReady) ? primaryBtn : `${secondaryBtn} opacity-60`}
>
{(ollamaReady || lmstudioReady) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}