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-3d): Blender entries in the viewer's Download menu

purpleeb05e9b0505c
diff --git a/src/api/__tests__/blender-handoff.test.ts b/src/api/__tests__/blender-handoff.test.ts
new file mode 100644
index 00000000..7ab87e57
--- /dev/null
+++ b/src/api/__tests__/blender-handoff.test.ts
@@ -0,0 +1,120 @@
+// Create, 3D to Blender: what the frontend sends to Rust and what the menu shows.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const invoke = vi.fn()
+vi.mock('@tauri-apps/api/core', () => ({ invoke: (...a: unknown[]) => invoke(...a) }))
+let tauri = true
+let mobile = false
+vi.mock('../in-tauri', () => ({ isTauri: () => tauri }))
+vi.mock('../../lib/device-kind', () => ({ isMobile: () => mobile }))
+
+import {
+ BLENDER_TEXT, blenderHeaders, blenderMenu, blenderMenuHint, blenderModelName, forgetBlenderStatus,
+ getBlenderStatus, makeWithBlender, openInBlender, stopBlender,
+} from '../blender'
+import { MESH_FORMATS } from '../../lib/three/mesh-export'
+
+const GLB = new Uint8Array([0x67, 0x6c, 0x54, 0x46, 2, 0, 0, 0])
+
+beforeEach(() => {
+ invoke.mockReset()
+ forgetBlenderStatus()
+ tauri = true
+ mobile = false
+})
+afterEach(() => vi.useRealTimers())
+
+describe('status', () => {
+ it('is not asked outside the desktop app or on a phone', async () => {
+ tauri = false
+ expect(await getBlenderStatus()).toBeNull()
+ tauri = true
+ mobile = true
+ expect(await getBlenderStatus()).toBeNull()
+ expect(invoke).not.toHaveBeenCalled()
+ })
+
+ it('is asked once per half minute', async () => {
+ vi.useFakeTimers()
+ invoke.mockResolvedValue({ found: true, version: '5.2.1', tooOld: false, source: 'app' })
+ expect((await getBlenderStatus())?.version).toBe('5.2.1')
+ await getBlenderStatus()
+ expect(invoke).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(31_000)
+ await getBlenderStatus()
+ expect(invoke).toHaveBeenCalledTimes(2)
+ })
+
+ it('a failing check means no Blender entries, not an error', async () => {
+ invoke.mockRejectedValue(new Error('boom'))
+ expect(await getBlenderStatus()).toBeNull()
+ expect(blenderMenu(null)).toEqual([])
+ })
+})
+
+describe('calls', () => {
+ it('the GLB goes as the raw body, the name as an encoded header', async () => {
+ invoke.mockResolvedValue(4242)
+ expect(await openInBlender(GLB, 'a red mug, "café"')).toBe(4242)
+ const [cmd, body, opts] = invoke.mock.calls[0]
+ expect(cmd).toBe('blender_open')
+ expect(body).toBe(GLB)
+ expect(opts.headers['x-lu-name']).toBe(encodeURIComponent('a red mug, "café"'))
+ expect(decodeURIComponent(opts.headers['x-lu-name'])).toBe('a red mug, "café"')
+ })
+
+ it('a .blend or FBX comes back as bytes', async () => {
+ invoke.mockResolvedValue(new Uint8Array([1, 2, 3]).buffer)
+ const out = await makeWithBlender(GLB, 'Mug', 'fbx', 'job-1')
+ expect(Array.from(out)).toEqual([1, 2, 3])
+ const [cmd, body, opts] = invoke.mock.calls[0]
+ expect(cmd).toBe('blender_convert')
+ expect(body).toBe(GLB)
+ expect(opts.headers).toEqual({ 'x-lu-name': 'Mug', 'x-lu-format': 'fbx', 'x-lu-job': 'job-1' })
+ })
+
+ it('stop names the job and never throws', async () => {
+ invoke.mockRejectedValue(new Error('gone'))
+ await expect(stopBlender('job-1')).resolves.toBeUndefined()
+ expect(invoke).toHaveBeenCalledWith('blender_cancel', { job: 'job-1' }, undefined)
+ })
+
+ it('headers are plain ASCII whatever the name holds', () => {
+ const h = blenderHeaders('ロボット\nnew line', { 'x-lu-format': 'blend' })
+ for (const v of Object.values(h)) expect(v).toMatch(/^[\x20-\x7e]*$/)
+ })
+})
+
+describe('menu', () => {
+ it('a usable Blender gives three entries', () => {
+ const entries = blenderMenu({ found: true, version: '5.2.1', tooOld: false, source: 'app' })
+ expect(entries.map((e) => e.id)).toEqual(['open', 'blend', 'fbx'])
+ expect(entries[0].label).toBe('Open in Blender')
+ expect(blenderMenuHint({ found: true, version: '5.2.1', tooOld: false, source: 'app' })).toBeNull()
+ })
+
+ it('an old Blender gives no entries and one honest line', () => {
+ const old = { found: true, version: '2.93.1', tooOld: true, source: 'app' }
+ expect(blenderMenu(old)).toEqual([])
+ expect(blenderMenuHint(old)).toBe(BLENDER_TEXT.tooOld('2.93.1'))
+ })
+
+ it('without Blender the GLB entry says it is the one for Blender', () => {
+ expect(blenderMenu({ found: false, version: null, tooOld: false, source: null })).toEqual([])
+ expect(MESH_FORMATS.find((f) => f.id === 'glb')?.note).toMatch(/best for Blender/)
+ })
+
+ it('texts end without a closing pleasantry', () => {
+ const all = [BLENDER_TEXT.open, BLENDER_TEXT.blend, BLENDER_TEXT.fbx, BLENDER_TEXT.fbxNote, BLENDER_TEXT.blendNote, BLENDER_TEXT.tooOld('3.0')]
+ for (const t of all) expect(t).not.toMatch(/should work|hope|enjoy/i)
+ })
+})
+
+describe('name', () => {
+ it('the prompt, cut at a word', () => {
+ expect(blenderModelName({ prompt: 'a small friendly robot, toy style' })).toBe('a small friendly robot, toy style')
+ expect(blenderModelName({ prompt: 'a very old wooden chair with carved legs and a red velvet seat' })).toBe('a very old wooden chair with carved legs')
+ expect(blenderModelName({ prompt: '', label: 'From a picture' })).toBe('From a picture')
+ expect(blenderModelName({ prompt: ' ' })).toBe('LU model')
+ })
+})
diff --git a/src/api/blender.ts b/src/api/blender.ts
new file mode 100644
index 00000000..44cd0c89
--- /dev/null
+++ b/src/api/blender.ts
@@ -0,0 +1,125 @@
+/**
+ * Create, 3D to Blender (desktop app only). Rust: src-tauri/src/commands/blender.rs.
+ *
+ * getBlenderStatus() -> BlenderStatus | null (null: no desktop app)
+ * openInBlender(glb, name) -> starts Blender with the model, does not wait
+ * makeWithBlender(glb, name, format, job) -> bytes of a .blend or .fbx
+ * stopBlender(job) -> stops that run
+ *
+ * The GLB goes to Rust as the raw body of the call, the name and the format
+ * as headers. Rust only ever runs a Blender it found itself.
+ */
+import { isTauri } from './in-tauri'
+import { isMobile } from '../lib/device-kind'
+import type { GalleryItem } from '../stores/createStore'
+
+export interface BlenderStatus {
+ found: boolean
+ version: string | null
+ tooOld: boolean
+ source: string | null
+}
+
+export type BlenderFormat = 'blend' | 'fbx'
+
+/** True where Blender can be asked for at all: the desktop app. */
+export function blenderPossible(): boolean {
+ return isTauri() && !isMobile()
+}
+
+async function invoke<T>(cmd: string, args?: unknown, headers?: Record<string, string>): Promise<T> {
+ const core = await import('@tauri-apps/api/core')
+ return core.invoke<T>(cmd, args as Record<string, unknown> | Uint8Array | undefined, headers ? { headers } : undefined)
+}
+
+let cached: { at: number; status: BlenderStatus } | null = null
+const FRESH_MS = 30_000
+
+/** Asked when the Download menu opens. A Blender installed while LU runs is
+ * seen after half a minute. */
+export async function getBlenderStatus(): Promise<BlenderStatus | null> {
+ if (!blenderPossible()) return null
+ if (cached && Date.now() - cached.at < FRESH_MS) return cached.status
+ try {
+ const status = await invoke<BlenderStatus>('blender_status')
+ cached = { at: Date.now(), status }
+ return status
+ } catch {
+ return null
+ }
+}
+
+/** For tests. */
+export function forgetBlenderStatus(): void {
+ cached = null
+}
+
+export function blenderHeaders(name: string, extra: Record<string, string> = {}): Record<string, string> {
+ return { 'x-lu-name': encodeURIComponent(name), ...extra }
+}
+
+export async function openInBlender(glb: Uint8Array, name: string): Promise<number> {
+ return invoke<number>('blender_open', glb, blenderHeaders(name))
+}
+
+export async function makeWithBlender(glb: Uint8Array, name: string, format: BlenderFormat, job: string): Promise<Uint8Array> {
+ const out = await invoke<ArrayBuffer | Uint8Array | number[]>('blender_convert', glb, blenderHeaders(name, { 'x-lu-format': format, 'x-lu-job': job }))
+ return out instanceof Uint8Array ? out : new Uint8Array(out as ArrayBuffer)
+}
+
+export async function stopBlender(job: string): Promise<void> {
+ try {
+ await invoke<boolean>('blender_cancel', { job })
+ } catch {
+ // Nothing running any more.
+ }
+}
+
+/** What the model is called in Blender: the first words of its prompt, or
+ * the gallery's label for it. */
+export function blenderModelName(item: Pick<GalleryItem, 'prompt' | 'label' | 'sourceName'>): string {
+ const from = (item.prompt || item.label || item.sourceName || '').replace(/\s+/g, ' ').trim()
+ if (!from) return 'LU model'
+ if (from.length <= 40) return from
+ const cut = from.slice(0, 40)
+ // Cut at the last whole word (the cut may already end on one).
+ const space = from[40] === ' ' ? 40 : cut.lastIndexOf(' ')
+ return (space > 20 ? cut.slice(0, space) : cut).replace(/[.,;:\s]+$/, '')
+}
+
+export const BLENDER_TEXT = {
+ open: 'Open in Blender',
+ blend: 'Save as .blend',
+ blendNote: 'textures packed in',
+ fbx: 'FBX',
+ fbxNote: 'made by Blender, for other 3D apps',
+ opening: 'Opening Blender…',
+ making: { blend: 'Blender is making the .blend…', fbx: 'Blender is making the FBX…' } as Record<BlenderFormat, string>,
+ stop: 'Stop',
+ tooOld: (v: string | null) => `Your Blender${v ? ` (${v})` : ''} is too old. Blender 3.3 or newer can open it here.`,
+ failed: 'Blender could not do it.',
+}
+
+export type BlenderAction = 'open' | 'blend' | 'fbx'
+
+export interface BlenderMenuEntry {
+ id: BlenderAction
+ label: string
+ note?: string
+}
+
+/** The Blender part of the Download menu. Empty without a usable Blender. */
+export function blenderMenu(status: BlenderStatus | null): BlenderMenuEntry[] {
+ if (!status?.found || status.tooOld) return []
+ return [
+ { id: 'open', label: BLENDER_TEXT.open },
+ { id: 'blend', label: BLENDER_TEXT.blend, note: BLENDER_TEXT.blendNote },
+ { id: 'fbx', label: BLENDER_TEXT.fbx, note: BLENDER_TEXT.fbxNote },
+ ]
+}
+
+/** A line under the formats for a Blender too old to use. Without Blender
+ * the GLB entry itself says it is the one for Blender. */
+export function blenderMenuHint(status: BlenderStatus | null): string | null {
+ return status?.found && status.tooOld ? BLENDER_TEXT.tooOld(status.version) : null
+}
diff --git a/src/components/create/experimental/galleryDownload.ts b/src/components/create/experimental/galleryDownload.ts
index dc02961c..488a2637 100644
--- a/src/components/create/experimental/galleryDownload.ts
+++ b/src/components/create/experimental/galleryDownload.ts
@@ -48,6 +48,8 @@ const MIME_BY_EXT: Record<string, string> = {
mp4: 'video/mp4', webm: 'video/webm',
mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg',
glb: 'model/gltf-binary', obj: 'model/obj', stl: 'model/stl', usdz: 'model/vnd.usdz+zip',
+ // Made by Blender on the desktop (api/blender.ts).
+ blend: 'application/x-blender', fbx: 'application/octet-stream',
}
/** The extension a phone asks for before it has seen the bytes. */
diff --git a/src/components/three/ModelViewer.tsx b/src/components/three/ModelViewer.tsx
index 9e4716f0..274f17ae 100644
--- a/src/components/three/ModelViewer.tsx
+++ b/src/components/three/ModelViewer.tsx
@@ -13,6 +13,10 @@ import { MeshLoadError } from '../../lib/three/mesh-load'
import { fetchGalleryItemBlob, markGalleryItemAvailable } from '../create/experimental/galleryUrl'
import { saveBytes } from '../create/experimental/galleryDownload'
import { cn } from '../create/ui/cn'
+import {
+ BLENDER_TEXT, blenderMenu, blenderMenuHint, blenderModelName, blenderPossible, getBlenderStatus, makeWithBlender, openInBlender, stopBlender,
+ type BlenderAction, type BlenderStatus,
+} from '../../api/blender'
export const VIEWER_TEXT = {
hint: 'Drag to turn. Scroll to zoom.',
@@ -57,6 +61,17 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
const [turning, setTurning] = useState(true)
const [menu, setMenu] = useState(false)
const [force, setForce] = useState(false)
+ const [blender, setBlender] = useState<BlenderStatus | null>(null)
+ const [busy, setBusy] = useState<{ action: BlenderAction; job: string } | null>(null)
+ const [note, setNote] = useState('')
+
+ // The Blender entries of the menu: asked when the menu opens (desktop app only).
+ useEffect(() => {
+ if (!menu || !blenderPossible()) return
+ let alive = true
+ void getBlenderStatus().then((s) => { if (alive) setBlender(s) })
+ return () => { alive = false }
+ }, [menu])
useEffect(() => {
if (!webgl) return
@@ -122,6 +137,37 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
}
}, [item.id])
+ const toBlender = useCallback(async (action: BlenderAction) => {
+ setMenu(false)
+ const original = bytesRef.current
+ if (!original || busy) return
+ const job = typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : `${Date.now()}`
+ const name = blenderModelName(item)
+ setMessage('')
+ setBusy({ action, job })
+ setNote(action === 'open' ? BLENDER_TEXT.opening : BLENDER_TEXT.making[action])
+ try {
+ if (action === 'open') {
+ await openInBlender(original, name)
+ // Blender takes a few seconds to show its window; the line stays that long.
+ await new Promise((r) => setTimeout(r, 4000))
+ } else {
+ const bytes = await makeWithBlender(original, name, action, job)
+ setNote('')
+ await saveBytes(bytes, `lu-${item.id}.${action}`, action)
+ }
+ } catch (err) {
+ const text = err instanceof Error ? err.message : String(err)
+ if (text !== 'Stopped.') setMessage(text || BLENDER_TEXT.failed)
+ } finally {
+ setBusy(null)
+ setNote('')
+ }
+ }, [busy, item])
+
+ const blenderEntries = blenderMenu(blender)
+ const menuHint = blenderMenuHint(blender)
+
const canExport = phase === 'ready'
return (
<div
@@ -187,6 +233,21 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
{f.label} <span className="text-gray-500">· {f.note}</span>
</button>
))}
+ {blenderEntries.length > 0 && <div className="my-1 border-t border-white/10" role="separator" />}
+ {blenderEntries.map((b) => (
+ <button
+ key={b.id}
+ type="button"
+ role="menuitem"
+ disabled={!!busy}
+ data-testid={`mv-blender-${b.id}`}
+ onClick={() => void toBlender(b.id)}
+ className="lu-on-dark w-full text-left px-3 py-1.5 t-control text-gray-200 hover:bg-white/5 disabled:opacity-50"
+ >
+ {b.label}{b.note && <span className="text-gray-500"> · {b.note}</span>}
+ </button>
+ ))}
+ {menuHint && <p className="px-3 pt-1 pb-1.5 t-mono text-gray-500 max-w-[260px]" data-testid="mv-blender-hint">{menuHint}</p>}
</div>
)}
</div>
@@ -197,7 +258,17 @@ export default function ModelViewer({ item, className, onFullscreen, touch }: Mo
<span className={touch ? undefined : 'hidden sm:inline'}>{touch ? VIEWER_TEXT.hintTouch : VIEWER_TEXT.hint}</span>
</div>
)}
- {phase === 'ready' && message && (
+ {note && (
+ <div className="absolute bottom-8 left-3 flex items-center gap-2 t-mono text-gray-300" data-testid="model-viewer-blender">
+ <span>{note}</span>
+ {busy && busy.action !== 'open' && (
+ <button type="button" className="underline underline-offset-2 text-gray-200" onClick={() => void stopBlender(busy.job)} data-testid="mv-blender-stop">
+ {BLENDER_TEXT.stop}
+ </button>
+ )}
+ </div>
+ )}
+ {phase === 'ready' && message && !note && (
<div className="absolute bottom-8 left-3 t-mono text-red-300" data-testid="model-viewer-note">{message}</div>
)}
</div>
diff --git a/src/lib/three/mesh-export.ts b/src/lib/three/mesh-export.ts
index 6206e06f..9dd97825 100644
--- a/src/lib/three/mesh-export.ts
+++ b/src/lib/three/mesh-export.ts
@@ -15,7 +15,7 @@ export interface MeshFormatInfo {
}
export const MESH_FORMATS: readonly MeshFormatInfo[] = [
- { id: 'glb', label: 'GLB', note: 'the original, with colors', mime: 'model/gltf-binary' },
+ { id: 'glb', label: 'GLB', note: 'the original, with colors, best for Blender', mime: 'model/gltf-binary' },
{ id: 'obj', label: 'OBJ', note: 'shape only', mime: 'model/obj' },
{ id: 'stl', label: 'STL', note: 'for 3D printing, shape only', mime: 'model/stl' },
{ id: 'usdz', label: 'USDZ', note: 'for iPhone and Mac', mime: 'model/vnd.usdz+zip' },