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(create-3d): 3D tab in Create, local and cloud runs, Windows/Linux TRELLIS.2 lane
purple3177ab3a242f
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex 465c7c63..cb8ed143 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -652,6 +652,10 @@ const MODEL_SUBDIRS: &[&str] = &["controlnet", "upscale_models", "embeddings", "style_models",// LTX 2.5's x2 latent upscaler (LatentUpscaleModelLoader reads this folder)."latent_upscale_models",+ // Local 3D (3.1.0): BiRefNet, the cutout model in front of TRELLIS.2.+ // LoadBackgroundRemovalModel reads it (ComfyUI v0.42.4, folder_paths.py+ // key "background_removal").+ "background_removal",];/// Why a file ComfyUI listed is not in the ComfyUI models tree.@@ -3363,6 +3367,17 @@ mod tests {assert_eq!(sorted.len(), MODEL_SUBDIRS.len(), "duplicate entry");}+ #[test]+ fn the_3d_folders_are_model_subdirs_and_safe_targets() {+ // The TRELLIS.2 bundle (src/api/model-bundles.ts getThreeDBundles)+ // writes into these four folders. Each has to be a target the+ // downloader accepts and a folder delete searches, or the 3D files+ // could be fetched but never removed from the Installed list.+ for d in ["diffusion_models", "vae", "clip_vision", "background_removal"] {+ assert!(super::MODEL_SUBDIRS.contains(&d), "{d} missing from MODEL_SUBDIRS");+ assert!(super::safe_subfolder(d).is_ok(), "{d} refused as a download target");+ }+ }/// GH #113: a partial as long as the file is answered 416 on every/// resume. That and only that sends the partial to the Trash and startsdiff --git a/src/api/__tests__/get-target-is-a-folder-we-read.test.ts b/src/api/__tests__/get-target-is-a-folder-we-read.test.tsindex 230b75cc..ec621751 100644--- a/src/api/__tests__/get-target-is-a-folder-we-read.test.ts+++ b/src/api/__tests__/get-target-is-a-folder-we-read.test.ts@@ -47,8 +47,9 @@ vi.mock('../backend', async (importOriginal) => ({import {COMFY_MODEL_FOLDERS, getVideoModels, getImageModels, getAudioModels,- getLipsyncModels, getMotionModels, getUpscaleModels, type ClassifiedModel,+ getLipsyncModels, getMotionModels, getUpscaleModels, getDiffusionModels, type ClassifiedModel,} from '../comfyui'+import { getThreeDBundles } from '../model-bundles'import {getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles,modelsNotVisibleInComfy, type ModelBundle, type DiscoverModel,@@ -74,6 +75,8 @@ const SCANS: Record<string, string[]> = {upscale_models: ['models/upscale_models'],latent_upscale_models: ['models/latent_upscale_models'],style_models: ['models/style_models'],+ // Local 3D (3.1.0): BiRefNet, read by LoadBackgroundRemovalModel.+ background_removal: ['models/background_removal'],}function filesIn(root: string, rel: string): string[] {@@ -121,6 +124,7 @@ function serve(root: string) {if (url.includes('LatentUpscaleModelLoader')) return combo('LatentUpscaleModelLoader', 'model_name', listFor(root, 'latent_upscale_models', false))if (url.includes('UpscaleModelLoader')) return combo('UpscaleModelLoader', 'model_name', listFor(root, 'upscale_models', false))if (url.includes('StyleModelLoader')) return combo('StyleModelLoader', 'style_model_name', listFor(root, 'style_models', false))+ if (url.includes('LoadBackgroundRemovalModel')) return combo('LoadBackgroundRemovalModel', 'bg_removal_name', listFor(root, 'background_removal', false))if (url.includes('ADE_LoadAnimateDiffModel')) {return combo('ADE_LoadAnimateDiffModel', 'model_name', filesIn(root, 'custom_nodes/ComfyUI-AnimateDiff-Evolved/models'))}@@ -189,6 +193,12 @@ const LANES: Array<{ lane: string; bundles: () => ModelBundle[]; picker: () => Plane: 'upscale', bundles: getUpscaleBundles,picker: async () => (await getUpscaleModels()).map((name) => ({ name }) as ClassifiedModel),},+ // Local 3D (3.1.0): TRELLIS.2 has no picker, the graph loads it by name+ // from UNETLoader's list (lib/local-3d-comfy comfyThreeDReady).+ {+ lane: '3d', bundles: getThreeDBundles,+ picker: async () => (await getDiffusionModels()).map((name) => ({ name }) as ClassifiedModel),+ },]const allBundles = () => LANES.flatMap((l) => l.bundles())@@ -243,6 +253,13 @@ describe('what the Get wrote, the picker offers', () => {}})+ it('the 3D model is not offered as an image model after its Get', async () => {+ const [bundle] = getThreeDBundles()+ serve(runTheGet(bundle.files))+ const offered = (await getImageModels()).map((m) => m.name)+ for (const f of mainFiles(bundle)) expect(offered).not.toContain(f.filename)+ })+// ...and the same question for every other Get target in the catalog, which// is the only way to know the two above were not the only two.it('and so is the main model of every other bundle', async () => {diff --git a/src/api/__tests__/three-d-bundle.test.ts b/src/api/__tests__/three-d-bundle.test.tsnew file mode 100644index 00000000..0c3eaa58--- /dev/null+++ b/src/api/__tests__/three-d-bundle.test.ts@@ -0,0 +1,131 @@+// Local 3D on Windows and Linux (3.1.0): the TRELLIS.2 bundle, where its files+// go, how ComfyUI reads them back, and how a finished model is named in the+// gallery.+import { describe, it, expect } from 'vitest'+import { getThreeDBundles, TRELLIS2_FILES } from '../model-bundles'+import {+ COMFY_MODEL_FOLDERS, extractComfyOutputFiles, galleryTypeForFile, isThreeDModelFile, classifyModel,+} from '../comfyui'+import { starterBundleFor } from '../../lib/starter-bundle'+import { localTier } from '../../lib/render/local-model-tier'++const GIB = 1_073_741_824++describe('the TRELLIS.2 bundle', () => {+ const bundles = getThreeDBundles()+ const [bundle] = bundles++ it('is one bundle of five files, about 8.95 GB', () => {+ expect(bundles).toHaveLength(1)+ expect(bundle.files).toHaveLength(5)+ const bytes = bundle.files.reduce((s, f) => s + (f.sizeBytes ?? 0), 0)+ expect(bytes).toBe(8954386952)+ // sizeGB is GiB, the unit the download tray turns back into bytes.+ for (const f of bundle.files) {+ expect(Math.abs(f.sizeGB! * GIB - f.sizeBytes!)).toBeLessThan(0.0001 * GIB)+ }+ const sum = bundle.files.reduce((s, f) => s + f.sizeGB!, 0)+ expect(bundle.totalSizeGB).toBeCloseTo(sum, 2)+ })++ it('names the files the graph loads, each in its ComfyUI folder', () => {+ const where = Object.fromEntries(bundle.files.map((f) => [f.filename, f.subfolder]))+ expect(where).toEqual({+ [TRELLIS2_FILES.model]: 'diffusion_models',+ [TRELLIS2_FILES.shapeVae]: 'vae',+ [TRELLIS2_FILES.textureVae]: 'vae',+ [TRELLIS2_FILES.imageEncoder]: 'clip_vision',+ [TRELLIS2_FILES.cutout]: 'background_removal',+ })+ const bytes = Object.fromEntries(bundle.files.map((f) => [f.filename, f.sizeBytes]))+ expect(bytes).toEqual({+ 'trellis_2_int8_convrot.safetensors': 5253048192,+ 'trellis_2_shape_vae_bf16.safetensors': 1095844024,+ 'trellis_2_texture_vae_bf16.safetensors': 948461364,+ 'dino_v3_vit_l.safetensors': 1212559776,+ 'birefnet.safetensors': 444473596,+ })+ })++ it('downloads only from Comfy-Org on Hugging Face, pinned to a commit, with a digest', () => {+ for (const f of bundle.files) {+ expect(f.downloadUrl).toMatch(+ /^https:\/\/huggingface\.co\/Comfy-Org\/(TRELLIS\.2|BiRefNet)\/resolve\/[0-9a-f]{40}\/[a-z_]+\/[a-z0-9_.]+\.safetensors$/,+ )+ expect(f.downloadUrl!.endsWith(`/${f.subfolder}/${f.filename}`)).toBe(true)+ expect(f.sha256).toMatch(/^[0-9a-f]{64}$/)+ }+ const cutout = bundle.files.find((f) => f.subfolder === 'background_removal')!+ expect(cutout.downloadUrl).toContain('/Comfy-Org/BiRefNet/')+ expect(bundle.files.filter((f) => f.downloadUrl!.includes('/Comfy-Org/TRELLIS.2/'))).toHaveLength(4)+ expect(bundle.files.every((f) => f.filename!.endsWith('.safetensors'))).toBe(true)+ })++ it('every folder it writes is one the app reads back', () => {+ const read = new Set(COMFY_MODEL_FOLDERS.map((f) => f.subfolder))+ for (const f of bundle.files) expect(read.has(f.subfolder!), f.subfolder).toBe(true)+ })++ it('is unfiltered, unverified until a box run, and needs no node pack', () => {+ expect(bundle.uncensored).toBe(true)+ expect(bundle.verified).toBe(false)+ expect(bundle.customNodes ?? []).toEqual([])+ expect(bundle.tags).toContain('MIT')+ expect(bundle.vramMinGB).toBe(16)+ })++ it('is what the 3D setup card installs', () => {+ expect(starterBundleFor('3d', '3d')?.name).toBe(bundle.name)+ })++ it('carries the tier the local picker gives its family', () => {+ expect(localTier({ name: TRELLIS2_FILES.model, type: bundle.workflow })).toBe(bundle.tier)+ expect(bundle.tier).toBe('best')+ })+})++describe('the 3D model file stays out of the image picker', () => {+ it('is recognised by name', () => {+ expect(isThreeDModelFile('trellis_2_int8_convrot.safetensors')).toBe(true)+ expect(isThreeDModelFile('sub/trellis_2_bf16.safetensors')).toBe(true)+ expect(isThreeDModelFile('TRELLIS2.safetensors')).toBe(true)+ expect(isThreeDModelFile('pixal3d_int8_convrot.safetensors')).toBe(false)+ expect(isThreeDModelFile('flux1-dev-fp8.safetensors')).toBe(false)+ expect(isThreeDModelFile('trellis_20b.safetensors')).toBe(false)+ })++ it('would otherwise come back as an unknown, which the image picker lets through', () => {+ expect(classifyModel('trellis_2_int8_convrot.safetensors')).toBe('unknown')+ })+})++describe('galleryTypeForFile', () => {+ it('names every mesh format a 3D model, whatever the mode', () => {+ for (const name of ['m_00001_.glb', 'm.gltf', 'm.obj', 'm.ply', 'm.stl', 'M.GLB']) {+ expect(galleryTypeForFile(name, 'image'), name).toBe('3d')+ expect(galleryTypeForFile(name, 'video'), name).toBe('3d')+ }+ })++ it('leaves pictures, videos and sound as they were', () => {+ expect(galleryTypeForFile('a.png', 'image')).toBe('image')+ expect(galleryTypeForFile('a.mp4', 'video')).toBe('video')+ expect(galleryTypeForFile('a.mp3', 'image')).toBe('audio')+ expect(galleryTypeForFile('a.objx', 'image')).toBe('image')+ })+})++describe('extractComfyOutputFiles and SaveGLB', () => {+ // UI.Saved3DModels.as_dict (comfy_api/latest/_ui.py, v0.42.4): the files+ // under "3d", next to a camera_info of [None] and an empty model_3d_info.+ it('finds the model under the "3d" key and skips the rest', () => {+ const output = {+ '3d': [{ filename: 'locally_uncensored_3d_abc123_00001_.glb', subfolder: '3d', type: 'output' }],+ camera_info: [null],+ model_3d_info: [],+ }+ expect(extractComfyOutputFiles(output)).toEqual([+ { filename: 'locally_uncensored_3d_abc123_00001_.glb', subfolder: '3d', type: 'output' },+ ])+ })+})diff --git a/src/api/__tests__/three-d-workflow.test.ts b/src/api/__tests__/three-d-workflow.test.tsnew file mode 100644index 00000000..eb4029ef--- /dev/null+++ b/src/api/__tests__/three-d-workflow.test.ts@@ -0,0 +1,177 @@+// The local 3D graph (TRELLIS.2, 3.1.0) against the node sequence of ComfyUI's+// template 3d_pixal3d_trellis2_image_to_model.json (wheel+// comfyui_workflow_templates_json 0.1.120, the one ComfyUI v0.42.4 pins),+// TRELLIS.2 branch, with the preview nodes taken out. The class and input+// names below were read from the node code at v0.42.4.+import { describe, it, expect } from 'vitest'+import {+ buildThreeDWorkflow, THREE_D_DETAIL, THREE_D_NODES, THREE_D_CUTOUT_NODES, THREE_D_SAVE_NODE,+ WorkflowUnavailableError, type ThreeDParams,+} from '../dynamic-workflow'+import { TRELLIS2_FILES } from '../model-bundles'+import type { ComfyApiGraph } from '../../types/comfy-graph'++const ALL = Object.fromEntries([...THREE_D_NODES, ...THREE_D_CUTOUT_NODES].map((n) => [n, {}]))+const base: ThreeDParams = { image: 'chair.png', detail: 'fine', cutout: true, seed: 42 }+const build = (p: Partial<ThreeDParams> = {}, nodes: Record<string, unknown> = ALL) =>+ buildThreeDWorkflow({ ...base, ...p }, nodes)++/** Every link as "target.input <- source:slot", for a readable diff. */+function links(g: ComfyApiGraph): string[] {+ const out: string[] = []+ for (const [id, node] of Object.entries(g)) {+ for (const [k, v] of Object.entries(node.inputs ?? {})) {+ if (Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number') {+ out.push(`${id}.${k} <- ${v[0]}:${v[1]}`)+ }+ }+ }+ return out.sort()+}++// The template's TRELLIS.2 branch (switch "Switch to Trellis2" true, "Remove+// background" true), node ids as in the template, previews bridged over.+const TEMPLATE_CLASSES: Record<string, string> = {+ '122': 'LoadImage', '193': 'LoadBackgroundRemovalModel', '192': 'RemoveBackground', '312': 'ImageCropToMask',+ '15': 'CLIPVisionLoader', '40': 'UNETLoader', '117': 'VAELoader', '118': 'VAELoader',+ '199': 'CFGOverride', '125': 'RescaleCFG', '108': 'ModelSamplingSD3', '279': 'CFGOverride', '126': 'RescaleCFG',+ '299': 'Trellis2Conditioning', '87': 'EmptyTrellis2LatentStructure',+ '3': 'KSampler', '119': 'VaeDecodeStructureTrellis2', '91': 'Trellis2ShapeStage', '18': 'KSampler',+ '94': 'Trellis2UpsampleStage', '23': 'KSampler', '92': 'VaeDecodeShapeTrellis',+ '98': 'Trellis2TextureStage', '12': 'KSampler', '93': 'VaeDecodeTextureTrellis',+ '241': 'RemeshMesh', '186': 'DecimateMesh', '238': 'MeshSmoothNormals', '196': 'UnwrapMesh',+ '147': 'BakeTextureFromVoxel', '224': 'BakeNormalMapFromMesh', '233': 'BakeAmbientOcclusion',+ '210': 'ApplyTextureToMesh', '260': 'MeshSmoothNormals', [THREE_D_SAVE_NODE]: 'SaveGLB',+}+const TEMPLATE_LINKS = [+ '192.bg_removal_model <- 193:0', '192.image <- 122:0',+ '312.images <- 122:0', '312.masks <- 192:0',+ '199.model <- 40:0', '125.model <- 199:0', '108.model <- 125:0', '279.model <- 40:0', '126.model <- 279:0',+ '299.clip_vision_model <- 15:0', '299.image <- 312:0',+ '3.model <- 108:0', '3.positive <- 299:0', '3.negative <- 299:1', '3.latent_image <- 87:0',+ '119.samples <- 3:0', '119.vae <- 117:0',+ '91.positive <- 299:0', '91.negative <- 299:1', '91.voxel <- 119:0',+ '18.model <- 126:0', '18.positive <- 91:0', '18.negative <- 91:1', '18.latent_image <- 91:2',+ '94.positive <- 91:0', '94.negative <- 91:1', '94.shape_latent <- 18:0', '94.vae <- 117:0',+ '23.model <- 126:0', '23.positive <- 94:0', '23.negative <- 94:1', '23.latent_image <- 94:2',+ '92.samples <- 23:0', '92.vae <- 117:0',+ '98.positive <- 94:0', '98.negative <- 94:1', '98.shape_latent <- 23:0',+ '12.model <- 40:0', '12.positive <- 98:0', '12.negative <- 98:1', '12.latent_image <- 98:2',+ '93.samples <- 12:0', '93.vae <- 118:0', '93.shape_subdivides <- 92:1',+ '241.mesh <- 92:0', '186.mesh <- 241:0', '238.mesh <- 186:0', '196.mesh <- 238:0',+ '147.mesh <- 196:0', '147.voxel_colors <- 93:0', '147.reference_mesh <- 92:0',+ '224.low_poly <- 196:0', '224.high_poly <- 241:0', '233.low_poly <- 196:0', '233.high_poly <- 241:0',+ '210.mesh <- 196:0', '210.base_color <- 147:0', '210.metallic <- 147:1', '210.roughness <- 147:2',+ '210.occlusion <- 233:0', '210.normal_map <- 224:0',+ '260.mesh <- 210:0', `${THREE_D_SAVE_NODE}.mesh <- 260:0`,+].sort()++describe('buildThreeDWorkflow', () => {+ it('is the template node for node, link for link', () => {+ const g = build()+ expect(Object.fromEntries(Object.entries(g).map(([id, n]) => [id, n.class_type]))).toEqual(TEMPLATE_CLASSES)+ expect(links(g)).toEqual(TEMPLATE_LINKS)+ })++ it('loads the five bundle files by name', () => {+ const g = build()+ expect(g['40'].inputs).toMatchObject({ unet_name: TRELLIS2_FILES.model, weight_dtype: 'default' })+ expect(g['117'].inputs).toEqual({ vae_name: TRELLIS2_FILES.shapeVae })+ expect(g['118'].inputs).toEqual({ vae_name: TRELLIS2_FILES.textureVae })+ expect(g['15'].inputs).toEqual({ clip_name: TRELLIS2_FILES.imageEncoder })+ expect(g['193'].inputs).toEqual({ bg_removal_name: TRELLIS2_FILES.cutout })+ expect(g['122'].inputs).toEqual({ image: 'chair.png' })+ })++ it('keeps the template sampler and guidance settings', () => {+ const g = build()+ expect(g['199'].inputs).toMatchObject({ cfg: 1, start_percent: 0.667, end_percent: 1 })+ expect(g['279'].inputs).toMatchObject({ cfg: 1, start_percent: 0.769, end_percent: 1 })+ expect(g['125'].inputs).toMatchObject({ multiplier: 0.7 })+ expect(g['126'].inputs).toMatchObject({ multiplier: 0.5 })+ expect(g['108'].inputs).toMatchObject({ shift: 5 })+ const ks = (id: string) => {+ const i = g[id].inputs!+ return [i.steps, i.cfg, i.sampler_name, i.scheduler, i.denoise]+ }+ expect(ks('3')).toEqual([12, 7.5, 'euler', 'normal', 1])+ expect(ks('18')).toEqual([20, 7.5, 'euler', 'normal', 1])+ expect(ks('23')).toEqual([12, 7.5, 'euler', 'simple', 1])+ expect(ks('12')).toEqual([12, 1, 'euler', 'normal', 1])+ expect(g['3'].inputs!.seed).toBe(42)+ expect(g['12'].inputs!.seed).toBe(43)+ expect(g['119'].inputs).toMatchObject({ resolution: '32' })+ expect(g['87'].inputs).toEqual({ batch_size: 1 })+ })++ it('writes the remesh choice the way a DynamicCombo is sent', () => {+ expect(build()['241'].inputs).toMatchObject({+ sign_mode: 'solid', 'sign_mode.fill': 20, 'sign_mode.qef': false,+ band: 1, project_back: 0, fix_poles: false, smooth_iters: 20,+ drop_small_components: 0.01, precluster_max_verts: 20_000_000,+ })+ expect(build()['186'].inputs).toMatchObject({ placement_mode: 'midpoint' })+ })++ it('fine is the template; draft and standard are lighter', () => {+ const at = (detail: ThreeDParams['detail']) => {+ const g = build({ detail })+ return {+ shape: g['94'].inputs!.target_resolution, remesh: g['241'].inputs!.resolution,+ faces: g['186'].inputs!.target_face_count, unwrap: g['196'].inputs!.resolution,+ texture: g['147'].inputs!.texture_size, normal: g['224'].inputs!.resolution,+ ao: g['233'].inputs!.resolution,+ }+ }+ expect(at('fine')).toEqual({ shape: 1536, remesh: 768, faces: 700_000, unwrap: 4096, texture: 4096, normal: 2048, ao: 1024 })+ expect(at('standard').shape).toBe(1024)+ expect(at('draft').faces).toBeLessThan(at('standard').faces as number)+ // Inside the node ranges of v0.42.4.+ for (const d of Object.values(THREE_D_DETAIL)) {+ expect(d.shapeResolution).toBeGreaterThanOrEqual(1024)+ expect(d.shapeResolution).toBeLessThanOrEqual(2048)+ expect(d.shapeResolution % 128).toBe(0)+ expect(d.texture % 256).toBe(0)+ expect(d.normalMap % 64).toBe(0)+ expect(d.occlusion % 64).toBe(0)+ expect(d.occlusionSamples % 4).toBe(0)+ expect(d.remeshResolution).toBeGreaterThanOrEqual(32)+ expect(d.remeshResolution).toBeLessThanOrEqual(2048)+ }+ })++ it('without a cutout uses the picture\'s own mask and needs no cutout model', () => {+ const noCut = Object.fromEntries(THREE_D_NODES.map((n) => [n, {}]))+ const g = build({ cutout: false }, noCut)+ expect(g['192']).toBeUndefined()+ expect(g['193']).toBeUndefined()+ expect(g['312'].inputs!.masks).toEqual(['122', 1])+ })++ it('crops to a 1024 square on black', () => {+ expect(build()['312'].inputs).toEqual({+ images: ['122', 0], masks: ['192', 0], width: 1024, height: 1024, pad_factor: 1.0, grow_mask: 0, background: '#000000',+ })+ })++ it('saves a GLB under output/3d', () => {+ const save = build()[THREE_D_SAVE_NODE]+ expect(save.class_type).toBe('SaveGLB')+ expect(String(save.inputs!.filename_prefix)).toMatch(/^3d\//)+ })++ it('asks for an update on a ComfyUI without the TRELLIS.2 nodes', () => {+ const old = { ...ALL }+ delete old.Trellis2UpsampleStage+ expect(() => build({}, old)).toThrow(WorkflowUnavailableError)+ expect(() => build({}, old)).toThrow(/ComfyUI 0\.42\.4 or newer/)+ const noSave = { ...ALL }+ delete noSave.SaveGLB+ expect(() => build({}, noSave)).toThrow(/newer/)+ })++ it('refuses a cutout when the cutout nodes are missing', () => {+ const noCut = Object.fromEntries(THREE_D_NODES.map((n) => [n, {}]))+ expect(() => build({ cutout: true }, noCut)).toThrow(/RemoveBackground/)+ })+})diff --git a/src/api/__tests__/wrapper-node-names.test.ts b/src/api/__tests__/wrapper-node-names.test.tsindex b330f5d2..0a32a5a8 100644--- a/src/api/__tests__/wrapper-node-names.test.ts+++ b/src/api/__tests__/wrapper-node-names.test.ts@@ -57,6 +57,18 @@ const CORE_NODES = new Set(['CLIPTextEncode', 'TextEncodeQwenImage21', 'CLIPSetLastLayer', 'CLIPVisionEncode', 'ConditioningZeroOut','InpaintModelConditioning', 'AudioEncoderEncode', 'ModelSamplingSD3', 'ModelSamplingAuraFlow','SVD_img2vid_Conditioning', 'VideoLinearCFGGuidance',+ // Local 3D (3.1.0, buildThreeDWorkflow), schema node_id of each read in+ // ComfyUI at tag v0.42.4 on 2026-11-13: nodes_trellis2.py (the eight+ // Trellis2 nodes), nodes_bg_removal.py (LoadBackgroundRemovalModel,+ // RemoveBackground), nodes_images.py (ImageCropToMask),+ // nodes_custom_sampler.py (CFGOverride), nodes_model_advanced.py+ // (RescaleCFG), nodes_mesh_postprocess.py (the mesh and bake nodes),+ // nodes_save_3d.py (SaveGLB).+ 'EmptyTrellis2LatentStructure', 'Trellis2Conditioning', 'Trellis2ShapeStage', 'Trellis2UpsampleStage',+ 'Trellis2TextureStage', 'VaeDecodeStructureTrellis2', 'VaeDecodeShapeTrellis', 'VaeDecodeTextureTrellis',+ 'LoadBackgroundRemovalModel', 'RemoveBackground', 'ImageCropToMask', 'CFGOverride', 'RescaleCFG',+ 'RemeshMesh', 'DecimateMesh', 'MeshSmoothNormals', 'UnwrapMesh', 'BakeTextureFromVoxel',+ 'BakeNormalMapFromMesh', 'BakeAmbientOcclusion', 'ApplyTextureToMesh', 'SaveGLB',// latents'EmptyLatentImage', 'EmptyLTXVLatentVideo', 'Wan22ImageToVideoLatent', 'TrimVideoLatent','WanSoundImageToVideo', 'WanAnimateToVideo', 'WanVaceToVideo',diff --git a/src/api/cloud/__tests__/catalog-desktop-names.test.ts b/src/api/cloud/__tests__/catalog-desktop-names.test.tsindex fc415a8b..0afeab46 100644--- a/src/api/cloud/__tests__/catalog-desktop-names.test.ts+++ b/src/api/cloud/__tests__/catalog-desktop-names.test.ts@@ -76,7 +76,7 @@ describe('the live catalog reaches every reader under the app name', () => {it('getCatalog asks the same route as before and returns the app names', async () => {cloudFetch.mockResolvedValue(answer(WIRE))const c = await getCatalog()- expect(cloudFetch).toHaveBeenCalledWith('/api/jobs/catalog?v=2')+ expect(cloudFetch).toHaveBeenCalledWith('/api/jobs/catalog?v=2&with=3d')expect(c.models.find((m) => m.id === 'chroma')?.label).toBe('Chroma Uncensored')})diff --git a/src/api/cloud/catalog.ts b/src/api/cloud/catalog.tsindex 97993c2f..84cca424 100644--- a/src/api/cloud/catalog.ts+++ b/src/api/cloud/catalog.ts@@ -57,6 +57,9 @@ export async function getCatalog(): Promise<CloudCatalog> {// `api_schema`/`pricing`/`quote_required` to the entries this same v=2// response already carries, and cloudCatalogStore/runCredits key off the// PRESENCE of those fields, never a version number (portplan Abschnitt 4/7).- const res = await cloudFetch('/api/jobs/catalog?v=2')+ // 3.1.0: `with=3d` asks for the 3D models too. A server hands them only to+ // an app that asks, so an app before 3.1.0 never draws a GLB as a broken+ // picture.+ const res = await cloudFetch('/api/jobs/catalog?v=2&with=3d')return desktopCatalog(await jsonOrError<Parameters<typeof desktopCatalog>[0]>(res))}diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.tsindex df1c6d21..f5802584 100644--- a/src/api/cloud/jobs.ts+++ b/src/api/cloud/jobs.ts@@ -17,6 +17,10 @@ export interface CloudJobParams {/** Idempotency key (a UUID minted client-side): a retried submit after a* dropped response replays the same job instead of booking twice. */client_request_id?: string+ /** 3D (3.1.0): where the pictures of the run came from (a file name, the+ * prompt of a gallery picture). The server's content gate reads it like+ * every other text parameter. */+ source_prompt?: string/** Bilder in diesem Lauf, 1 bis 4 (nur Bild und Bearbeiten). Fehlt das Feld,* bucht der Server genau einen Auftrag, wie vor dem 02.10.2026. Ein Server* ohne die Anzahl bucht ebenfalls einen, deshalb schickt der Start sie nur,diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex a9cb965c..069b8c36 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -181,11 +181,16 @@ export function extractComfyOutputFiles(nodeOutput: unknown): ComfyUIOutput[] {* the long-standing image/video tagging (incl. the animated-webp fallback)* is untouched. */const AUDIO_OUTPUT_EXTS = new Set(['mp3', 'wav', 'flac', 'ogg', 'opus', 'm4a'])+/** 3.1.0: the mesh formats a 3D save node writes. SaveGLB (nodes_save_3d.py,+ * ComfyUI v0.42.4) always writes .glb for a mesh and keeps the format of a+ * File3D it is handed, so the other four can come out of it too. */+const MESH_OUTPUT_EXTS = new Set(['glb', 'gltf', 'obj', 'ply', 'stl'])export function galleryTypeForFile(filename: string,mode: 'image' | 'video',-): 'image' | 'video' | 'audio' {+): 'image' | 'video' | 'audio' | '3d' {const ext = (filename.split('.').pop() || '').toLowerCase()+ if (MESH_OUTPUT_EXTS.has(ext)) return '3d'return AUDIO_OUTPUT_EXTS.has(ext) ? 'audio' : mode}@@ -1228,6 +1233,13 @@ export async function filterPartialFiles(filenames: string[]): Promise<Set<strin* The catalogue card keeps its own verdict (discover.ts filters there) and goes* on saying honestly that the package is not fully downloaded.*/+/** A main model file of the local 3D lane (TRELLIS.2). It runs only in the+ * 3D graph (buildThreeDWorkflow), never as an image or video model. */+export function isThreeDModelFile(name: string): boolean {+ const base = name.split(/[\\/]/).pop()!.toLowerCase()+ return /(^|[^a-z0-9])trellis[._-]?2([^0-9]|$)/.test(base)+}+/** A VAE that landed in a main model folder (Discord 2026-09-26: a CivitAI* download of minimax_h3_video_vae_fp16 showed up as an IMAGE model). It can* never run as one, so the picker leaves it out. Deliberately narrow: only a@@ -1340,6 +1352,11 @@ async function mainModelLane(if (complete && !complete.has(name)) continueif (isStrayAddonFile(name)) continueif (listed.has(name)) continue+ // The 3D model sits in diffusion_models and its name places it in no+ // family, so it would come back 'unknown' and be offered as an image+ // model. The pickers leave it out; the inventory (hidePartialDownloads+ // false) keeps it, so it can still be seen and deleted.+ if (hidePartialDownloads && isThreeDModelFile(name)) continuecandidates.push({ name, type: classifyModel(name), source: 'diffusion_model' })}await applyHeaderSniff(candidates)@@ -1665,6 +1682,10 @@ export const COMFY_MODEL_FOLDERS: Array<{// and a different loader from the image upscalers above).{ subfolder: 'latent_upscale_models', read: () => nodeOptionsOrNull('LatentUpscaleModelLoader', 'model_name') },{ subfolder: 'style_models', read: () => nodeOptionsOrNull('StyleModelLoader', 'style_model_name') },+ // The cutout model of local 3D (BiRefNet). LoadBackgroundRemovalModel is a+ // core node of ComfyUI v0.42.4 (comfy_extras/nodes_bg_removal.py) and lists+ // models/background_removal under `bg_removal_name`.+ { subfolder: 'background_removal', read: () => nodeOptionsOrNull('LoadBackgroundRemovalModel', 'bg_removal_name') },{ subfolder: ANIMATEDIFF_SUBFOLDER, read: () => nodeOptionsOrNull('ADE_LoadAnimateDiffModel', 'model_name') },]diff --git a/src/api/discover.ts b/src/api/discover.tsindex b293d765..61ce85c4 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -22,7 +22,7 @@ import { imagePartFileName, isUpstreamImagePart, pickUpstreamImagePart } from '.import { shardSetGap, type ShardGap } from '../lib/gguf-shards'import {CUSTOM_NODE_REGISTRY,- getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles,+ getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles, getThreeDBundles,} from "./model-bundles"// Katalog + Formen liegen in model-bundles.ts (siehe dort). Re-Export, damit@@ -2193,7 +2193,7 @@ export interface FileMeta {* and text models alike. One walk, so the lookups below cannot drift apart. */function catalogEntries(): DiscoverModel[] {const out: DiscoverModel[] = []- for (const bundle of [...getImageBundles(), ...getVideoBundles(), ...getAudioBundles(), ...getLipsyncBundles(), ...getMotionBundles(), ...getUpscaleBundles()]) {+ for (const bundle of [...getImageBundles(), ...getVideoBundles(), ...getAudioBundles(), ...getLipsyncBundles(), ...getMotionBundles(), ...getUpscaleBundles(), ...getThreeDBundles()]) {out.push(...bundle.files)}out.push(...getUncensoredTextModels(), ...getMainstreamTextModels())diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.tsindex bec5750b..821dd769 100644--- a/src/api/dynamic-workflow.ts+++ b/src/api/dynamic-workflow.ts@@ -65,6 +65,7 @@ import { extraReferenceSlots, isQwenImageEditModel, referenceSide } from '../libimport { canonicalImageRefs } from '../lib/image-ref-names'import { KREA2_STYLE_LORA, LOCAL_END_FRAME_MODELS, createReferenceSupport, localAnimateReferenceSlots, localEndFrame, CREATE_REFERENCE_MODELS } from '../lib/frame-refs'import { nativeUpscaleScale, upscaleTarget, type UpscaleFactor } from '../lib/local-upscale'+import { TRELLIS2_FILES } from './model-bundles'import { WAN_FAST, findWanSpeedLora, isFastSampling, isWanSpeedLoraName, wanSamplingFor, wanSpeedKind, wanSpeedLoraNames } from '../lib/wan-speed'import { addAudioStitch, addContextWindows, addContinueSource, addStitch, CONTINUE_NEEDS_UPDATE, type ContinueSource } from './video-continue'@@ -2127,6 +2128,206 @@ export async function buildLocalUpscaleWorkflow(params: UpscaleParams): Promise<return buildUpscaleWorkflow(params, await getAllNodeInfo())}+// ─── 3D from one picture (TRELLIS.2, Windows and Linux, 3.1.0) ───+//+// The graph is the TRELLIS.2 branch of ComfyUI's own template+// `3d_pixal3d_trellis2_image_to_model.json`, read as data out of the PyPI+// wheel comfyui_workflow_templates_json 0.1.120 (sha256+// f4f8e94d2c8a94ea894a9d9a18235ea6306268112f9dc267611a04b20d2740be). That is+// the version ComfyUI v0.42.4 pins through comfyui-workflow-templates==0.11.94+// in its requirements.txt. Class names, input names, types and ranges were+// checked against the node code at the tag v0.42.4: comfy_extras/+// nodes_trellis2.py, nodes_bg_removal.py, nodes_images.py (ImageCropToMask),+// nodes_custom_sampler.py (CFGOverride), nodes_model_advanced.py (RescaleCFG,+// ModelSamplingSD3), nodes_mesh_postprocess.py and nodes_save_3d.py.+//+// The node ids are the template's, so a diff against it stays readable. What+// differs from the template, on purpose:+// * The Pixal3D branch is gone (its model, MoGe, the FOV node and the three+// ComfySwitchNode that choose between the two). The template's switch+// "Switch to Trellis2" set to true is exactly this graph.+// * The preview nodes are gone (PreviewImage, MaskPreview, Preview3DAdvanced,+// VoxelToMesh, PaintMesh, RenderUVAtlas, GetMeshInfo, the MeshToFile3D in+// front of each preview). In v0.42.4 PreviewImage and MaskPreview pass+// their input through, so the links run straight from the node before.+// * SaveGLB (mesh in, writes output/3d/*.glb, reports under the key "3d")+// stands in for MeshToFile3D plus Save3DAdvanced, which needs the+// viewport state of the canvas.+// * cutout false skips RemoveBackground and feeds the picture's own mask+// (LoadImage output 1) into ImageCropToMask, the template's "Switch:+// Remove background" set to false. An opaque picture then has an empty+// mask, and ImageCropToMask takes the whole picture (_crop_image_with_mask).+// * pad_factor 1.0 instead of the template's 1.1: the Trellis2Conditioning+// input says "pad_factor=1.0 for TRELLIS.2"; the template shares the crop+// with Pixal3D. Unconfirmed until a run on the box.+// * `detail` sets the cascade resolution, the remesh grid, the face count+// and the texture sizes. 'fine' is the template's values.++export type ThreeDDetail = 'draft' | 'standard' | 'fine'++export interface ThreeDDetailSettings {+ /** Trellis2UpsampleStage target_resolution (1024 to 2048, step 128). */+ shapeResolution: number+ /** RemeshMesh resolution (32 to 2048). */+ remeshResolution: number+ /** DecimateMesh target_face_count. */+ faces: number+ /** UnwrapMesh resolution and BakeTextureFromVoxel texture_size (step 256). */+ texture: number+ /** BakeNormalMapFromMesh resolution (step 64). */+ normalMap: number+ /** BakeAmbientOcclusion resolution (step 64) and its ray count (step 4). */+ occlusion: number+ occlusionSamples: number+}++export const THREE_D_DETAIL: Record<ThreeDDetail, ThreeDDetailSettings> = {+ draft: { shapeResolution: 1024, remeshResolution: 384, faces: 100_000, texture: 1024, normalMap: 1024, occlusion: 512, occlusionSamples: 32 },+ standard: { shapeResolution: 1024, remeshResolution: 512, faces: 300_000, texture: 2048, normalMap: 2048, occlusion: 1024, occlusionSamples: 64 },+ fine: { shapeResolution: 1536, remeshResolution: 768, faces: 700_000, texture: 4096, normalMap: 2048, occlusion: 1024, occlusionSamples: 64 },+}++export interface ThreeDParams {+ /** The picture, as ComfyUI's /upload/image named it. */+ image: string+ detail: ThreeDDetail+ /** Cut the object out of its background first (BiRefNet). */+ cutout: boolean+ seed: number+ /** Other file names than the catalogue's, for a ComfyUI that lists them so. */+ files?: Partial<Record<keyof typeof TRELLIS2_FILES, string>>+}++export const THREE_D_NEEDS_UPDATE = 'Local 3D needs ComfyUI 0.42.4 or newer. Update ComfyUI in Settings.'++/** The core nodes the graph is built from. The TRELLIS.2 ones are the release+ * marker: without them the install is older than the lane. */+export const THREE_D_TRELLIS_NODES = [+ 'EmptyTrellis2LatentStructure', 'Trellis2Conditioning', 'Trellis2ShapeStage', 'Trellis2UpsampleStage',+ 'Trellis2TextureStage', 'VaeDecodeStructureTrellis2', 'VaeDecodeShapeTrellis', 'VaeDecodeTextureTrellis',+]+export const THREE_D_NODES = [+ ...THREE_D_TRELLIS_NODES,+ 'LoadImage', 'ImageCropToMask', 'CLIPVisionLoader', 'UNETLoader', 'VAELoader',+ 'CFGOverride', 'RescaleCFG', 'ModelSamplingSD3', 'KSampler',+ 'RemeshMesh', 'DecimateMesh', 'MeshSmoothNormals', 'UnwrapMesh',+ 'BakeTextureFromVoxel', 'BakeNormalMapFromMesh', 'BakeAmbientOcclusion', 'ApplyTextureToMesh', 'SaveGLB',+]+export const THREE_D_CUTOUT_NODES = ['LoadBackgroundRemovalModel', 'RemoveBackground']++/** The id of the save node, whose history entry carries the model. */+export const THREE_D_SAVE_NODE = '900'++function sampler(+ model: [string, number], cond: string, latent: [string, number], seed: number,+ steps: number, cfg: number, scheduler: string,+): ComfyNodeInputs {+ return {+ model, positive: [cond, 0], negative: [cond, 1], latent_image: latent,+ seed, steps, cfg, sampler_name: 'euler', scheduler, denoise: 1,+ }+}++export function buildThreeDWorkflow(params: ThreeDParams, allNodes: NodePresence): ComfyApiGraph {+ requireRelease(allNodes, THREE_D_TRELLIS_NODES, THREE_D_NEEDS_UPDATE, 'unavailable')+ requireRelease(allNodes, ['SaveGLB', 'RemeshMesh', 'BakeTextureFromVoxel'], THREE_D_NEEDS_UPDATE, 'unavailable')+ requireNodes(allNodes, THREE_D_NODES, 'Local 3D')+ if (params.cutout) requireNodes(allNodes, THREE_D_CUTOUT_NODES, 'Local 3D')+ const files = { ...TRELLIS2_FILES, ...params.files }+ const d = THREE_D_DETAIL[params.detail] ?? THREE_D_DETAIL.standard+ // KSampler takes 0 to 2^64-1; the texture pass gets its own seed as in the+ // template (42 for the shape passes, 43 for the texture).+ const seed = Math.max(0, Math.floor(params.seed))+ const textureSeed = seed + 1 > Number.MAX_SAFE_INTEGER ? 0 : seed + 1+ const w: ComfyApiGraph = {}++ // The picture, cut out and cropped to 1024 square.+ w['122'] = { class_type: 'LoadImage', inputs: { image: params.image } }+ let mask: [string, number] = ['122', 1]+ if (params.cutout) {+ w['193'] = { class_type: 'LoadBackgroundRemovalModel', inputs: { bg_removal_name: files.cutout } }+ w['192'] = { class_type: 'RemoveBackground', inputs: { bg_removal_model: ['193', 0], image: ['122', 0] } }+ mask = ['192', 0]+ }+ w['312'] = {+ class_type: 'ImageCropToMask',+ inputs: { images: ['122', 0], masks: mask, width: 1024, height: 1024, pad_factor: 1.0, grow_mask: 0, background: '#000000' },+ }++ // Loaders and the two guided model chains of the template.+ w['15'] = { class_type: 'CLIPVisionLoader', inputs: { clip_name: files.imageEncoder } }+ w['40'] = { class_type: 'UNETLoader', inputs: { unet_name: files.model, weight_dtype: 'default' } }+ w['117'] = { class_type: 'VAELoader', inputs: { vae_name: files.shapeVae } }+ w['118'] = { class_type: 'VAELoader', inputs: { vae_name: files.textureVae } }+ w['199'] = { class_type: 'CFGOverride', inputs: { model: ['40', 0], cfg: 1, start_percent: 0.667, end_percent: 1 } }+ w['125'] = { class_type: 'RescaleCFG', inputs: { model: ['199', 0], multiplier: 0.7 } }+ w['108'] = { class_type: 'ModelSamplingSD3', inputs: { model: ['125', 0], shift: 5 } }+ w['279'] = { class_type: 'CFGOverride', inputs: { model: ['40', 0], cfg: 1, start_percent: 0.769, end_percent: 1 } }+ w['126'] = { class_type: 'RescaleCFG', inputs: { model: ['279', 0], multiplier: 0.5 } }+ w['299'] = { class_type: 'Trellis2Conditioning', inputs: { clip_vision_model: ['15', 0], image: ['312', 0] } }++ // Structure, then shape at 512, then the cascade up to the detail's resolution.+ w['87'] = { class_type: 'EmptyTrellis2LatentStructure', inputs: { batch_size: 1 } }+ w['3'] = { class_type: 'KSampler', inputs: sampler(['108', 0], '299', ['87', 0], seed, 12, 7.5, 'normal') }+ w['119'] = { class_type: 'VaeDecodeStructureTrellis2', inputs: { samples: ['3', 0], vae: ['117', 0], resolution: '32' } }+ w['91'] = { class_type: 'Trellis2ShapeStage', inputs: { positive: ['299', 0], negative: ['299', 1], voxel: ['119', 0] } }+ w['18'] = { class_type: 'KSampler', inputs: sampler(['126', 0], '91', ['91', 2], seed, 20, 7.5, 'normal') }+ w['94'] = {+ class_type: 'Trellis2UpsampleStage',+ inputs: { positive: ['91', 0], negative: ['91', 1], shape_latent: ['18', 0], vae: ['117', 0], target_resolution: d.shapeResolution },+ }+ w['23'] = { class_type: 'KSampler', inputs: sampler(['126', 0], '94', ['94', 2], seed, 12, 7.5, 'simple') }+ w['92'] = { class_type: 'VaeDecodeShapeTrellis', inputs: { samples: ['23', 0], vae: ['117', 0] } }++ // The surface, as voxel colours.+ w['98'] = { class_type: 'Trellis2TextureStage', inputs: { positive: ['94', 0], negative: ['94', 1], shape_latent: ['23', 0] } }+ w['12'] = { class_type: 'KSampler', inputs: sampler(['40', 0], '98', ['98', 2], textureSeed, 12, 1, 'normal') }+ w['93'] = { class_type: 'VaeDecodeTextureTrellis', inputs: { samples: ['12', 0], vae: ['118', 0], shape_subdivides: ['92', 1] } }++ // A clean mesh, unwrapped, with the colours baked into textures.+ w['241'] = {+ class_type: 'RemeshMesh',+ inputs: {+ mesh: ['92', 0], resolution: d.remeshResolution,+ // A DynamicCombo: the choice under its own name, its options as+ // "sign_mode.<name>" (comfy_api/latest/_io.py, finalize_prefix).+ sign_mode: 'solid', 'sign_mode.fill': 20, 'sign_mode.qef': false,+ band: 1, project_back: 0, fix_poles: false, smooth_iters: 20,+ drop_small_components: 0.01, precluster_max_verts: 20_000_000,+ },+ }+ w['186'] = { class_type: 'DecimateMesh', inputs: { mesh: ['241', 0], target_face_count: d.faces, placement_mode: 'midpoint' } }+ w['238'] = { class_type: 'MeshSmoothNormals', inputs: { mesh: ['186', 0], crease_angle: 180 } }+ w['196'] = { class_type: 'UnwrapMesh', inputs: { mesh: ['238', 0], segmenter: 'pec', resolution: d.texture, padding: 1, weld_distance: 0.0002 } }+ w['147'] = {+ class_type: 'BakeTextureFromVoxel',+ inputs: { mesh: ['196', 0], voxel_colors: ['93', 0], texture_size: d.texture, reference_mesh: ['92', 0] },+ }+ w['224'] = {+ class_type: 'BakeNormalMapFromMesh',+ inputs: { low_poly: ['196', 0], high_poly: ['241', 0], resolution: d.normalMap, cage_distance: 0.05, ignore_backfaces: true },+ }+ w['233'] = {+ class_type: 'BakeAmbientOcclusion',+ inputs: { low_poly: ['196', 0], high_poly: ['241', 0], resolution: d.occlusion, samples: d.occlusionSamples, max_distance: 0.71, strength: 1, bias: 0.01 },+ }+ w['210'] = {+ class_type: 'ApplyTextureToMesh',+ inputs: { mesh: ['196', 0], base_color: ['147', 0], metallic: ['147', 1], roughness: ['147', 2], occlusion: ['233', 0], normal_map: ['224', 0] },+ }+ w['260'] = { class_type: 'MeshSmoothNormals', inputs: { mesh: ['210', 0], crease_angle: 180 } }+ w[THREE_D_SAVE_NODE] = {+ class_type: 'SaveGLB',+ inputs: { mesh: ['260', 0], filename_prefix: `3d/${promptFilenamePrefix('', false)}_3d` },+ }+ return w+}++/** The graph against the running ComfyUI's node list. */+export async function buildLocalThreeDWorkflow(params: ThreeDParams): Promise<ComfyApiGraph> {+ return buildThreeDWorkflow(params, await getAllNodeInfo())+}+// Resolve a default value for one RMBG widget input from its object_info spec.// Combo → prefer a transparent option for the background widget, else the// declared default / first entry. Primitives → their declared default. Adiff --git a/src/api/model-bundles.ts b/src/api/model-bundles.tsindex 294fd256..9c777b85 100644--- a/src/api/model-bundles.ts+++ b/src/api/model-bundles.ts@@ -2086,3 +2086,105 @@ export function getUpscaleBundles(): ModelBundle[] {},])}++// ─── 3D on Windows and Linux (3.1.0) ───+//+// TRELLIS.2 (microsoft/TRELLIS.2-4B, MIT) in the ComfyUI repack, plus BiRefNet+// (MIT) for the cutout. Both run on ComfyUI core nodes of the pinned release+// v0.42.4 (comfy_extras/nodes_trellis2.py, nodes_bg_removal.py,+// nodes_mesh_postprocess.py, nodes_save_3d.py); no custom node pack.+//+// Files, folders, byte counts and SHA-256 are the Hugging Face LFS values of+// the two repositories, read from the tree API on 2026-11-13 and pinned to+// these commits:+// Comfy-Org/TRELLIS.2 430a9d09b2416687018c8fe8edced2ad4858a439+// Comfy-Org/BiRefNet 884af709e9b795d89dafbf97f29c8d6a2386f5c6+// The official template (3d_pixal3d_trellis2_image_to_model.json, see+// buildThreeDWorkflow) loads the two VAEs from Comfy-Org/Pixal3D; they are+// byte for byte the files in Comfy-Org/TRELLIS.2 (same SHA-256). Its image+// encoder there is dino_v3_L_naf_fp32, which carries the NAF upsampler only the+// Pixal3D branch uses (comfy/clip_vision.py). TRELLIS.2 needs the plain+// DINOv3 ViT-L, the file its own repository ships.+//+// The int8 model is the one the template loads. The bf16 file (10.3 GB) is+// left out on purpose. `verified` stays false until a run on the box.++/** The five file names the 3D graph loads. One place, so the bundle, the+ * graph and the readiness check can never name different files. */+export const TRELLIS2_FILES = {+ model: 'trellis_2_int8_convrot.safetensors',+ shapeVae: 'trellis_2_shape_vae_bf16.safetensors',+ textureVae: 'trellis_2_texture_vae_bf16.safetensors',+ imageEncoder: 'dino_v3_vit_l.safetensors',+ cutout: 'birefnet.safetensors',+} as const++const GIB = 1_073_741_824+const gib = (bytes: number) => Math.round((bytes / GIB) * 10000) / 10000++export function getThreeDBundles(): ModelBundle[] {+ const files: DiscoverModel[] = [+ {+ name: 'TRELLIS.2 4B (INT8)',+ description: 'The model that builds the shape and the surface from one picture.',+ pulls: '', tags: ['Diffusion Model', '5.25 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/430a9d09b2416687018c8fe8edced2ad4858a439/diffusion_models/trellis_2_int8_convrot.safetensors',+ filename: TRELLIS2_FILES.model, subfolder: 'diffusion_models', sizeGB: gib(5253048192),+ sizeBytes: 5253048192,+ sha256: 'd01952ad137213f6a868f86b6b877026276f84af5eec23069217475a0bad3a31',+ },+ {+ name: 'TRELLIS.2 Shape VAE',+ description: 'Required, turns the shape into a mesh.',+ pulls: '', tags: ['VAE', '1.10 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/430a9d09b2416687018c8fe8edced2ad4858a439/vae/trellis_2_shape_vae_bf16.safetensors',+ filename: TRELLIS2_FILES.shapeVae, subfolder: 'vae', sizeGB: gib(1095844024),+ sizeBytes: 1095844024,+ sha256: 'de0cb4949a76c59ee5c091a995a69bcc8c51d5aeda939f0c641a50d2a72341f4',+ },+ {+ name: 'TRELLIS.2 Texture VAE',+ description: 'Required, paints the surface.',+ pulls: '', tags: ['VAE', '948 MB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/430a9d09b2416687018c8fe8edced2ad4858a439/vae/trellis_2_texture_vae_bf16.safetensors',+ filename: TRELLIS2_FILES.textureVae, subfolder: 'vae', sizeGB: gib(948461364),+ sizeBytes: 948461364,+ sha256: '714e5ebf094a610e12a8e3b5175c18a62f37f6ea4218acb6073644456b73ab0e',+ },+ {+ name: 'DINOv3 ViT-L Image Encoder',+ description: 'Required, reads the picture for TRELLIS.2.',+ pulls: '', tags: ['CLIP Vision', '1.21 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/430a9d09b2416687018c8fe8edced2ad4858a439/clip_vision/dino_v3_vit_l.safetensors',+ filename: TRELLIS2_FILES.imageEncoder, subfolder: 'clip_vision', sizeGB: gib(1212559776),+ sizeBytes: 1212559776,+ sha256: '5cb785e458de7c460579082418af81f5c62380c181599344bdc60898c63468ee',+ },+ {+ name: 'BiRefNet',+ description: 'Cuts the object out of its background before the model sees it.',+ pulls: '', tags: ['Background Removal', '444 MB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/Comfy-Org/BiRefNet/resolve/884af709e9b795d89dafbf97f29c8d6a2386f5c6/background_removal/birefnet.safetensors',+ filename: TRELLIS2_FILES.cutout, subfolder: 'background_removal', sizeGB: gib(444473596),+ sizeBytes: 444473596,+ sha256: '9ab37426bf4de0567af6b5d21b16151357149139362e6e8992021b8ce356a154',+ },+ ]+ return withVramNeed([+ {+ name: 'TRELLIS.2 (Image to 3D)',+ description: 'Turns one picture of an object into a textured 3D model. MIT licensed, runs on ComfyUI.',+ tags: ['3D', 'Image to 3D', 'MIT'],+ totalSizeGB: Math.round(files.reduce((s, f) => s + (f.sizeGB ?? 0), 0) * 100) / 100,+ // Microsoft names 24 GB for the original bf16 model. What the int8+ // repack needs on a smaller card is not measured yet.+ vramRequired: '16-24 GB',+ workflow: 'trellis2',+ tier: 'best',+ uncensored: true,+ verified: false,+ url: 'https://huggingface.co/Comfy-Org/TRELLIS.2',+ files,+ },+ ])+}diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsxindex 2458c720..6c6b8cd9 100644--- a/src/components/create/experimental/Composer.tsx+++ b/src/components/create/experimental/Composer.tsx@@ -14,12 +14,12 @@ import { intentToJob, quotaCostKind } from '../../../lib/render/cloud-jobs'import { meterState } from '../../../lib/render/credits-meter'import { runImageCount } from '../../../lib/render/image-count'import { useCloudCatalogStore, cloudModelById, defaultCloudModel, editNeedsMask, modelForOp, runCredits, lengthCredits, lengthPrice } from '../../../stores/cloudCatalogStore'-import { createRunModel, intentRequiredInputs, isStudioModel } from '../../../lib/render/create-studio'+import { createRunModel, intentRequiredInputs, isStudioModel, studioIntentOf } from '../../../lib/render/create-studio'import { STUDIO_MODELS } from '../../../lib/render/studio-contract'import { effectiveVideoDurations, snapToVideoDuration } from '../../../lib/render/video-duration'import { mediaSeconds, useStudioPrice } from './useStudioPrice'import { getJob } from '../../../api/cloud/jobs'-import { INTENT_MAP, intentTakesOptionalPrompt, intentTakesPrompt } from './intents'+import { INTENT_MAP, intentNeedsSource, intentTakesOptionalPrompt, intentTakesPrompt } from './intents'import { MUSIC_PLACEHOLDER, musicText } from '../../../lib/render/music-ui'import { subscribeInstallRuns, getInstallRun } from '../../../lib/model-install-runs'import { useWorkflowStore, shouldShowManagerNotice } from '../../../stores/workflowStore'@@ -36,6 +36,8 @@ import { CharacterChip, CharacterNote, characterMakesStart } from './CharacterChimport { PromptHistory } from './PromptHistory'import { PromptAssistant } from './PromptAssistant'import { SpecialControls } from './SpecialIntentControls'+import { ThreeDControls } from './ThreeDControls'+import { threeDControlFacts } from '../../../lib/three/three-d-models'import { CreditsMeter } from './CreditsMeter'import { Button } from '../ui/Button'import { PromptField } from '../ui/PromptField'@@ -138,6 +140,8 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {intent === 'character' || intent === 'lipsync' || intent === 'music' ||intent === 'extend' || intent === 'motion'const characterUse = intent === 'character' && characterTab === 'use'+ const threeDWay = useCreateStore((s) => s.threeDWay)+ const needsSource = intentNeedsSource(intent, threeDWay)let { kind: intentKind, op: intentOp } = intentToJob(intent)if (characterUse) {// The use-surface is a plain image generate with the character attached.@@ -148,7 +152,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {// flag, plus Character-Studio's use-surface (train has no prompt), plus// Motion Control on the local lanes, whose prompt may stay empty.const optionalPrompt = intentTakesOptionalPrompt(intent, backend)- const needPrompt = intentTakesPrompt(intent, characterUse) || optionalPrompt+ const needPrompt = intentTakesPrompt(intent, characterUse, threeDWay) || optionalPrompt// Gate on the exact run's cost (model + op + clip length), the same figure// the CreditsMeter shows — quota.costs[kind] is only the tier's// representative per-kind number and would mis-gate utility ops / pricier@@ -165,7 +169,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {// Wahl, die die Unterkategorie nicht fahren kann, rechnet hier als das Modell,// das wirklich laeuft. Rollen-Absichten behalten ihre Wahl.const runModel = createRunModel(- intent,+ studioIntentOf(intent, threeDWay),{ image: cloudImageModel, video: cloudVideoModel, op: cloudOpModel },characterUse ? selectedCharacter?.family ?? '' : undefined,)@@ -361,7 +365,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {const canGenerate =!macSetupFirst &&(!needPrompt || optionalPrompt || prompt.trim().length > 0) &&- (!meta.needsSource || hasStart) &&+ (!needsSource || hasStart) &&(!needsMask || !!mask) &&specialReady &&upscaleReady &&@@ -373,7 +377,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {const inputNote = showNoPromptHint && !needsMask && isInputHint(intent)const laneCaption = noPromptHint(meta.id, backend, backend === 'local' && isMlxImageHost(), trainKind)// The disabled button says which input it waits for (laneHint.ts).- const missingSource = missingSourceHint({ intent, needsSource: meta.needsSource, hasSource: hasStart })+ const missingSource = missingSourceHint({ intent, needsSource, hasSource: hasStart })return (// A stable min-height (bottom-anchored) so the prompt window occupies the@@ -390,6 +394,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {Befund und hier nicht behoben. */}<div className="mx-auto w-full max-w-[660px] space-y-2.5">{special && <SpecialControls intent={intent} />}+ {intent === '3d' && <ThreeDControls {...threeDControlFacts(backend, studioPick)} studioId={studioPick} />}{!isUtility && <LaneControls />}<CharacterNote />{inputNote && (@@ -753,6 +758,8 @@ function LaneControls() {if (backend === 'cloud' && !characterUse && !specialOp && isStudioModel(modelForOp(laneKind, cloudVideoOp, lanePicked))) return nullif (characterTrain) return null+ // 3D has its own row (ThreeDControls): no size, steps or aspect.+ if (intent === '3d') return null// ── Image lanes: quality + aspect (+ edit strength) ──if (kind === 'image') {diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxindex 3b58e92f..30845fe9 100644--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@ -106,7 +106,7 @@ interface CreateExpValue {* 2.5.8 lanes → ACE / S2V / VACE starters incl. their node packs)* with streamed progress, refresh ComfyUI's model enums and re-fetch the* model lists. Throws on failure. */- installModelBundle: (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale', onProgress?: (msg: string) => void, signal?: AbortSignal) => Promise<void>+ installModelBundle: (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale' | '3d', onProgress?: (msg: string) => void, signal?: AbortSignal) => Promise<void>/** Runtime backend axis: hosted rendering offered for this session? */cloudAvailable: booleanquota: CloudQuota | null@@ -459,7 +459,7 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {// then refresh ComfyUI's model enums so the new files are pickable without// a restart. Bundles that need a custom node pack (GGUF loader, pose// extractor) install + register it first — one click really means one click.- const installModelBundle = useCallback(async (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale', onProgress?: (msg: string) => void, signal?: AbortSignal) => {+ const installModelBundle = useCallback(async (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale' | '3d', onProgress?: (msg: string) => void, signal?: AbortSignal) => {// macOS takes the MLX path — engine plus the smallest model of that kind.// Everything below this line is the ComfyUI bundle flow, which would start// by installing ComfyUI itself; on a Mac that is the one thing that must@@ -467,6 +467,9 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {// Only image and video exist locally there; the other lanes are cloud// teasers on a Mac and never render this card.if (isMacOS()) {+ // 3D on a Mac is its own engine with its own download (api/mlx-3d.ts),+ // never this ComfyUI bundle.+ if (kind === '3d') throw new Error('3D on this Mac sets up from its own card, not through ComfyUI.')if (kind !== 'image' && kind !== 'video' && kind !== 'motion') {throw new Error('This one runs in LU Cloud on a Mac — local generation covers images and video.')}diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsxindex 08adf48b..9c5dac5b 100644--- a/src/components/create/experimental/CreateExperimental.tsx+++ b/src/components/create/experimental/CreateExperimental.tsx@@ -43,7 +43,7 @@ const PresetWorkshop = lazy(() =>import('./PresetWorkshop').then((m) => ({ default: m.PresetWorkshop })),)import { INTENT_MAP, isIntentAvailable } from './intents'-import { studioPickFor } from '../../../lib/render/create-studio'+import { studioIntentOf, studioPickFor } from '../../../lib/render/create-studio'import { modelForOp, useCloudCatalogStore } from '../../../stores/cloudCatalogStore'import { stageShowsSetupCard, laneModelCount } from './stageGate'import { isMlxImageHost } from '../../../api/mlx-image'@@ -93,6 +93,7 @@ function CreateExperimentalInner() {// Composer.tsx, kept in sync by hand (both read the same store getters and// pure functions, no new state).const intent = useCreateStore((s) => s.intent())+ const threeDWay = useCreateStore((s) => s.threeDWay)const cloudOpModel = useCreateStore((s) => s.cloudOpModel)const cloudImageModel = useCreateStore((s) => s.cloudImageModel)const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)@@ -104,7 +105,7 @@ function CreateExperimentalInner() {// traegt die Regel fuer Composer, Zaehler, Start und diese Schublade; der// Character-Weg bleibt davon ausgenommen. Auf der lokalen Spur gibt es nie// eine Studio-Wahl.- const studioPick = backend === 'cloud' ? studioPickFor(intent, { cloudImageModel, cloudVideoModel, cloudOpModel }) : undefined+ const studioPick = backend === 'cloud' ? studioPickFor(studioIntentOf(intent, threeDWay), { cloudImageModel, cloudVideoModel, cloudOpModel }) : undefinedconst [shownId, setShownId] = useState<string | null>(null)const [advancedOpen, setAdvancedOpen] = useState(false)diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsxindex 2cab70ec..e60cac09 100644--- a/src/components/create/experimental/CreatePanel.tsx+++ b/src/components/create/experimental/CreatePanel.tsx@@ -10,6 +10,7 @@ import { isMlxImageHost } from '../../../api/mlx-image'import { downloadGalleryItem } from './galleryDownload'import { useComfyMedia } from './useComfyMedia'import { cn } from '../ui/cn'+import { ModelThumb } from '../../three/ModelThumb'import { HINWEIS_TEXT, HINWEIS_ZEILE } from '../../../lib/hinweis'import { hiddenCount, itemsInView } from '../../../lib/gallery-tags'import { FolderFilter, MoveToFolderModal, OnBody } from './GalleryFolders'@@ -378,6 +379,7 @@ function BarBtn({ children, title, onClick, danger }: { children: React.ReactNod// direct /view load, #75) — hooks can't run inside the gallery .map().function GalleryThumb({ g }: { g: GalleryItem }) {const { src, onError, onLoad } = useComfyMedia(g)+ if (g.type === '3d') return <ModelThumb item={g} />if (g.type === 'audio') {// No visual to thumbnail — a labeled tile; the Stage viewer holds the// actual <audio> player.diff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsxindex 124ba598..e4f4a00f 100644--- a/src/components/create/experimental/Lightbox.tsx+++ b/src/components/create/experimental/Lightbox.tsx@@ -8,6 +8,7 @@ import { useCreateExp } from './CreateContext'import { useComfyMedia } from './useComfyMedia'import { PromptDetails } from './PromptDetails'import { cn } from '../ui/cn'+import { LazyModelViewer } from '../../three/LazyModelViewer'import { MoveToFolderModal, OnBody } from './GalleryFolders'import { playsAsVideo } from './galleryUrl'import { itemsInView } from '../../../lib/gallery-tags'@@ -277,7 +278,15 @@ export function Lightbox({ item, onClose, onSaveCharacter, onNavigate, promptOpe</OnBody></div>)}- {item.type === 'audio' ? (+ {item.type === '3d' ? (+ // The model takes the whole room; its own bar carries the+ // download menu and the looks.+ <div className="min-h-0 flex-1 w-full flex items-center justify-center overflow-hidden" onClick={(e) => e.stopPropagation()} data-testid="lightbox-3d">+ <div className="w-full h-full max-w-[1400px]">+ <LazyModelViewer key={item.id} item={item} />+ </div>+ </div>+ ) : item.type === 'audio' ? (<motion.divinitial={{ scale: 0.95 }}animate={{ scale: 1 }}diff --git a/src/components/create/experimental/ModelChip.tsx b/src/components/create/experimental/ModelChip.tsxindex d8317fcd..d636deca 100644--- a/src/components/create/experimental/ModelChip.tsx+++ b/src/components/create/experimental/ModelChip.tsx@@ -7,7 +7,7 @@ import {import { DEFAULT_MODEL_IDS } from '../../../lib/render/cloud-models'import { groupForPicker, sortByTier, tierGroup, tierMarks } from '../../../lib/render/model-tier'import { localTier } from '../../../lib/render/local-model-tier'-import { intentPickerModels, intentRoles, createStudioCost, isStudioModel } from '../../../lib/render/create-studio'+import { intentPickerModels, intentRoles, createStudioCost, isStudioModel, studioIntentOf } from '../../../lib/render/create-studio'import type { RenderOp } from '../../../lib/render/cloud-jobs'import type { PresetModel } from '../../../lib/render/preset-models'import { useSettingsStore } from '../../../stores/settingsStore'@@ -106,8 +106,10 @@ function CloudModelChip() {// Portplan P7: lipsync/music/extend/motion reach the Studio track through// the SAME picker as their classic op-specialized twins.// intentPickerModels() (create-studio.ts, P2) already merges both worlds.- const roleIntent = !characterUse && intentRoles(intent).length > 0- const roleModels: PresetModel[] = roleIntent ? intentPickerModels(intent) : []+ const threeDWay = useCreateStore((s) => s.threeDWay)+ const pickIntent = studioIntentOf(intent, threeDWay)+ const roleIntent = !characterUse && intentRoles(pickIntent).length > 0+ const roleModels: PresetModel[] = roleIntent ? intentPickerModels(pickIntent) : []const characterModels = characterUse ? characterGenerationModels(selectedCharacter?.family ?? '') : []// List only the models that can run the current op — otherwise the picker// offers checkpoints that useCloudCreate silently swaps out at submit, so thediff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsxindex 71b0ad3d..acead822 100644--- a/src/components/create/experimental/OutputView.tsx+++ b/src/components/create/experimental/OutputView.tsx@@ -21,6 +21,7 @@ import { useComfyMedia } from './useComfyMedia'import { BatchQueue } from './BatchStrip'import { FitStage } from './FitStage'import { cn } from '../ui/cn'+import { LazyModelViewer } from '../../three/LazyModelViewer'// The icon in the waiting circle says which PHASE the render is in, never// which device it runs on. The chip is the loading phase, the spark is@@ -199,6 +200,25 @@ export function ResultView({ item, onFullscreen, onShowPrompt, onSendToEditor, o// An old animated .webp clip shows as a picture, which still moves (A19).const inPlayer = playsAsVideo(item)const isAudio = item.type === 'audio'+ // A 3D model has its own view with its own bar (download menu, looks), so+ // it skips the hover buttons of a picture.+ if (item.type === '3d') {+ const model = (maxHeight?: string) => (+ <div className="w-[760px] max-w-full" style={{ height: maxHeight ?? '62vh' }} data-testid="result-3d">+ <LazyModelViewer key={item.id} item={item} onFullscreen={onFullscreen} />+ </div>+ )+ const under = (+ <div className="flex items-center gap-3 mt-3 t-mono text-gray-600" data-testid="result-facts">+ <span className="truncate max-w-[420px]">{galleryLabel(item)}</span>+ <span>·</span>+ <button type="button" className="underline underline-offset-2 hover:text-gray-300" onClick={() => useCreateStore.getState().removeFromGallery(item.id)}>+ {deleteTitle(isMlxImageHost())}+ </button>+ </div>+ )+ return <FitStage picture={model} under={under} side={side} capVh={62} />+ }// `maxHeight` is the height the stage has left for the result (FitStage).// Until the stage is measured it keeps the share of the window it always had.const media = (maxHeight?: string) => (diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex 7ffe3021..42b68bc2 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -6,7 +6,8 @@ import { useModelStore } from '../../../stores/modelStore'import { createRunModel } from '../../../lib/render/create-studio'import { musicText } from '../../../lib/render/music-ui'import { useCreateExp } from './CreateContext'-import { INTENT_MAP } from './intents'+import { INTENT_MAP, intentNeedsSource } from './intents'+import { ThreeDSetupCard, ThreeDVideoHint, useThreeDLocal } from './ThreeDStage'import { editNeedsMask, defaultCloudModel, modelForOp } from '../../../stores/cloudCatalogStore'import { stageShowsSetupCard, laneModelCount } from './stageGate'import { needsMaskFor } from './maskGate'@@ -74,6 +75,8 @@ interface Props {export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResult, onFullscreen, onShowPrompt, onSaveCharacter, comfyStarting }: Props) {const intent = useCreateStore((s) => s.intent())const meta = INTENT_MAP[intent]+ const threeDWay = useCreateStore((s) => s.threeDWay)+ const needsSource = intentNeedsSource(intent, threeDWay)// The width of the stage, for the how-to line at its foot (footLine below).const stageRef = useRef<HTMLDivElement>(null)const [stageWidth, setStageWidth] = useState<number | null>(null)@@ -95,6 +98,8 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResuconst setPrompt = useCreateStore((s) => s.setPrompt)const caps = useCreateStore((s) => s.caps)const backend = useCreateStore((s) => s.backend)+ // 3D brings its own setup card (TripoSR on a Mac, TRELLIS.2 in ComfyUI).+ const threeDSetup = useThreeDLocal(intent === '3d' && backend === 'local')const imageModelList = useCreateStore((s) => s.imageModelList)const videoModelList = useCreateStore((s) => s.videoModelList)const audioModelList = useCreateStore((s) => s.audioModelList)@@ -153,7 +158,7 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResu// model shows none. Local music keeps them: its prompt is always the style.const musicIsLyrics = useCreateStore((s) =>s.backend === 'cloud' && musicText(createRunModel('music', { image: '', video: '', op: s.cloudOpModel })).main === 'lyrics')- const examples = intent === 'music' && musicIsLyrics ? [] : meta.examples+ const examples = (intent === 'music' && musicIsLyrics) || (intent === '3d' && threeDWay !== 'text') ? [] : meta.examples// A bundle is not usable until ALL of its files are down, and the lane list// refills the moment the diffusion model alone lands. Measured on the box@@ -180,6 +185,8 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResuconst howtoTopic = stageHowtoTopic(intent, backend, isMlxImageHost())if (isGenerating) {body = <GeneratingView />+ } else if (intent === '3d' && threeDSetup.needsSetup) {+ body = <ThreeDSetupCard setup={threeDSetup} />} else if (modelsMissing || installRun) {body = <ModelInstallCard kind={meta.requiresModels!} />} else if (meta.capability && !capReady) {@@ -189,10 +196,10 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResu// trigger word + train button sit in the composer below.body = <TrainSetBoard />howtoAtFoot = true- } else if (meta.needsSource && !source) {- body = <InputSlot />+ } else if (needsSource && !source) {+ body = intent === '3d' && threeDWay === 'video' ? <ThreeDVideoHint /> : <InputSlot />howtoAtFoot = true- } else if (meta.needsSource && source && !freshResult) {+ } else if (needsSource && source && !freshResult) {body = <SourcePreview onOpenMaskEditor={onOpenMaskEditor} />howtoAtFoot = truehowtoOnlyWide = true@@ -207,7 +214,7 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResuonSaveCharacter={displayed.type === 'video' && onSaveCharacter ? () => onSaveCharacter(displayed) : undefined}// The source and its references stay on screen beside the result// (FitStage), so the next run shows what it starts from.- side={meta.needsSource && source ? <ResultInputs /> : imageRefSide ? <ImageReferenceStrip /> : undefined}+ side={needsSource && source ? <ResultInputs /> : imageRefSide ? <ImageReferenceStrip /> : undefined}/>)} else {diff --git a/src/components/create/experimental/ThreeDControls.tsx b/src/components/create/experimental/ThreeDControls.tsxnew file mode 100644index 00000000..6e1d57ba--- /dev/null+++ b/src/components/create/experimental/ThreeDControls.tsx@@ -0,0 +1,235 @@+// The 3D tab's own row in the Composer (C3D-PLAN 1.2): the way (text, image,+// video), the cutout switch, the detail step, the further sides of a model+// that takes several views, and the still frames of a video.+//+// The video never leaves the device. LU reads still frames of it here, the+// first one becomes the picture on the Stage (the "Front"), the others the+// further sides. From there "From video" runs exactly like "From image".+import { useEffect, useRef, useState } from 'react'+import { Film, Plus, X } from 'lucide-react'+import { useCreateStore, type ImageRef, type ThreeDDetail, type ThreeDWay } from '../../../stores/createStore'+import { framesAcrossVideo } from '../../../lib/video-frames'+import { THREE_D_TEXT as T } from '../../../lib/three/three-d-text'+import { loadImageRef } from './loadImage'+import { Segmented } from '../ui/Segmented'+import { cn } from '../ui/cn'+import { cloudDetailOf, threeDDetailField } from '../../../lib/three/three-d-models'++const WAYS: ThreeDWay[] = ['text', 'image', 'video']+const DETAILS: ThreeDDetail[] = ['draft', 'standard', 'fine']+/** How many moments of a video are offered to pick from. */+const FRAME_CHOICES = 8++export interface ThreeDControlsProps {+ /** How many pictures the picked model takes: 1, or up to 4 sides. */+ maxViews: number+ /** Whether the picked model has a detail step at all. */+ hasDetail: boolean+ /** Whether the cutout switch applies (it does wherever LU cuts out itself). */+ hasCutout: boolean+ /** The cloud model that will run, when there is one. */+ studioId?: string+}++export function ThreeDControls({ maxViews, hasDetail, hasCutout, studioId }: ThreeDControlsProps) {+ const way = useCreateStore((s) => s.threeDWay)+ const setWay = useCreateStore((s) => s.setThreeDWay)+ const cutout = useCreateStore((s) => s.threeDCutout)+ const setCutout = useCreateStore((s) => s.setThreeDCutout)+ const detail = useCreateStore((s) => s.threeDDetail)+ const setDetail = useCreateStore((s) => s.setThreeDDetail)+ const backend = useCreateStore((s) => s.backend)+ const studioOptions = useCreateStore((s) => s.cloudStudioOptions)+ const setStudioOptions = useCreateStore((s) => s.setCloudStudioOptions)+ // In the cloud the step IS the model's own field (its resolution or its+ // texture quality), written where the price and the booking read it.+ const cloudField = backend === 'cloud' ? threeDDetailField(studioId) : null+ const shownDetail = cloudField ? cloudDetailOf(cloudField, studioOptions[cloudField.field], studioId) : detail+ const pickDetail = (d: ThreeDDetail) => {+ setDetail(d)+ if (cloudField) setStudioOptions({ ...studioOptions, [cloudField.field]: cloudField.values[d] })+ }+ return (+ <div className="flex flex-col gap-3" data-testid="three-d-controls">+ <Segmented+ ariaLabel="How to make the model"+ layoutId="three-d-way"+ value={way}+ onChange={setWay}+ options={WAYS.map((w) => ({ value: w, label: T.ways[w] }))}+ />+ {way === 'text' && backend === 'local' && <p className="t-meta text-gray-400" data-testid="three-d-picture-first">{T.pictureFirst}</p>}+ {way === 'image' && maxViews > 1 && <SideStrip maxViews={maxViews} />}+ {way === 'video' && <VideoFrames maxViews={maxViews} />}+ <div className="flex flex-wrap items-center gap-4">+ {hasCutout && way !== 'text' && (+ <label className="flex items-center gap-2 t-control text-gray-300 cursor-pointer">+ <input type="checkbox" checked={cutout} onChange={(e) => setCutout(e.target.checked)} data-testid="three-d-cutout" />+ {T.cutout}+ </label>+ )}+ {hasDetail && (+ <div className="flex items-center gap-2">+ <span className="t-control text-gray-400">{T.detail}</span>+ <Segmented+ size="sm"+ ariaLabel={T.detail}+ layoutId="three-d-detail"+ value={shownDetail}+ onChange={pickDetail}+ options={DETAILS.map((d) => ({ value: d, label: T.details[d] }))}+ />+ </div>+ )}+ </div>+ </div>+ )+}++/** Left, Back, Right for a model that takes several views. Front is the+ * picture on the Stage. */+function SideStrip({ maxViews }: { maxViews: number }) {+ const views = useCreateStore((s) => s.threeDViews)+ const setViews = useCreateStore((s) => s.setThreeDViews)+ const setError = useCreateStore((s) => s.setError)+ const inputRef = useRef<HTMLInputElement>(null)+ const [slot, setSlot] = useState(0)+ const sides = T.sides.slice(1, maxViews)+ const pick = (i: number) => {+ setSlot(i)+ inputRef.current?.click()+ }+ const onFile = async (f: File | undefined) => {+ if (!f) return+ try {+ const ref = await loadImageRef(f)+ const next = [...views]+ next[slot] = ref+ setViews(next.filter(Boolean))+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ }+ }+ return (+ <div className="flex flex-col gap-1.5" data-testid="three-d-sides">+ <span className="t-control text-gray-300">{T.moreSides}</span>+ <div className="flex gap-2">+ {sides.map((name, i) => (+ <Slot key={name} name={name} image={views[i]} onPick={() => pick(i)} onClear={() => setViews(views.filter((_, k) => k !== i))} />+ ))}+ </div>+ <span className="t-meta text-gray-500">{T.moreSidesSub}</span>+ <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { void onFile(e.target.files?.[0]); e.target.value = '' }} />+ </div>+ )+}++function Slot({ name, image, onPick, onClear, active }: { name: string; image?: ImageRef; onPick: () => void; onClear?: () => void; active?: boolean }) {+ return (+ <div className="relative">+ <button+ type="button"+ onClick={onPick}+ title={name}+ className={cn(+ 'w-16 h-16 rounded-lg border overflow-hidden flex flex-col items-center justify-center gap-0.5 t-label text-gray-400',+ active ? 'border-lu-accent' : 'border-white/10 hover:border-white/25',+ )}+ >+ {image ? <img src={image.url} alt={name} className="w-full h-full object-cover" /> : <><Plus size={14} />{name}</>}+ </button>+ {image && onClear && (+ <button type="button" aria-label={`Remove ${name}`} onClick={onClear} className="absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-black/70 text-gray-200 flex items-center justify-center">+ <X size={11} />+ </button>+ )}+ </div>+ )+}++/** A video in, still frames out. The user picks which moments become the+ * sides: one for a model that takes one picture, up to four otherwise. */+function VideoFrames({ maxViews }: { maxViews: number }) {+ const setSource = useCreateStore((s) => s.setSource)+ const setViews = useCreateStore((s) => s.setThreeDViews)+ const setError = useCreateStore((s) => s.setError)+ const inputRef = useRef<HTMLInputElement>(null)+ const [frames, setFrames] = useState<ImageRef[]>([])+ const [picked, setPicked] = useState<number[]>([])+ const [reading, setReading] = useState(false)+ const [name, setName] = useState<string | null>(null)+ const want = Math.max(1, Math.min(4, maxViews))++ // The picked moments, in order, become the Stage source and the sides.+ useEffect(() => {+ if (!frames.length) return+ const chosen = picked.map((i) => frames[i]).filter(Boolean)+ setSource(chosen[0] ?? null)+ setViews(chosen.slice(1))+ }, [frames, picked, setSource, setViews])++ const onFile = async (f: File | undefined) => {+ if (!f) return+ setReading(true)+ setName(f.name)+ const url = URL.createObjectURL(f)+ try {+ const blobs = await framesAcrossVideo(url, FRAME_CHOICES)+ const refs: ImageRef[] = []+ for (const [i, b] of blobs.entries()) {+ refs.push(await loadImageRef(new File([b], `${f.name.replace(/\.[^.]+$/, '')}-frame-${i + 1}.jpg`, { type: b.type || 'image/jpeg' })))+ }+ setFrames(refs)+ setPicked(evenPick(refs.length, want))+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ } finally {+ URL.revokeObjectURL(url)+ setReading(false)+ }+ }++ const toggle = (i: number) => {+ setPicked((p) => {+ if (want === 1) return [i]+ if (p.includes(i)) return p.length > 1 ? p.filter((k) => k !== i) : p+ return p.length >= want ? [...p.slice(1), i] : [...p, i].sort((a, b) => a - b)+ })+ }++ return (+ <div className="flex flex-col gap-1.5" data-testid="three-d-video">+ <button+ type="button"+ onClick={() => inputRef.current?.click()}+ className="self-start flex items-center gap-2 h-[var(--control-h-md)] px-3 rounded-lg border border-white/10 hover:border-white/25 t-control text-gray-200"+ data-testid="three-d-video-pick"+ >+ <Film size={14} />+ {name ?? T.dropVideo}+ </button>+ {!frames.length && !reading && <span className="t-meta text-gray-500">{T.dropVideoSub}</span>}+ {reading && <span className="t-meta text-gray-400">{T.framesReading}</span>}+ {frames.length > 0 && (+ <>+ <span className="t-meta text-gray-400">{want > 1 ? T.framesMany : T.framesOne}</span>+ <div className="flex flex-wrap gap-2" data-testid="three-d-frames">+ {frames.map((fr, i) => (+ <Slot key={fr.url} name={`${i + 1}`} image={fr} active={picked.includes(i)} onPick={() => toggle(i)} />+ ))}+ </div>+ <span className="t-meta text-gray-500">{T.videoHonest}</span>+ </>+ )}+ <input ref={inputRef} type="file" accept="video/mp4,video/webm,video/quicktime" className="hidden" onChange={(e) => { void onFile(e.target.files?.[0]); e.target.value = '' }} />+ </div>+ )+}++/** `want` indices spread evenly over `n` frames: 0, 2, 4, 6 of eight. */+export function evenPick(n: number, want: number): number[] {+ if (n <= 0) return []+ const k = Math.min(want, n)+ if (k === 1) return [Math.floor((n - 1) / 2)]+ return Array.from({ length: k }, (_, i) => Math.round((i * (n - 1)) / k))+}diff --git a/src/components/create/experimental/ThreeDStage.tsx b/src/components/create/experimental/ThreeDStage.tsxnew file mode 100644index 00000000..9f8b4ddf--- /dev/null+++ b/src/components/create/experimental/ThreeDStage.tsx@@ -0,0 +1,147 @@+// What the Stage of the 3D tab shows before there is anything to show: the+// one-time setup of the local engine, and the hint for a video.+//+// Local 3D has its own setup, not the starter-bundle gate of requiresModels:+// on a Mac it is an engine of its own (TripoSR, commands/mesh3d.rs, through+// api/mlx-3d.ts), on Windows and Linux a ComfyUI bundle (TRELLIS.2,+// lib/local-3d-comfy.ts).+import { useCallback, useEffect, useRef, useState } from 'react'+import { Box, Film } from 'lucide-react'+import { isMlxImageHost } from '../../../api/mlx-image'+import { THREE_D_TEXT as T } from '../../../lib/three/three-d-text'+import { useCreateExp } from './CreateContext'+import { Button } from '../ui/Button'++export const SETUP_TEXT = {+ macTitle: '3D on this Mac needs a one-time download',+ macBody: 'This sets up the 3D engine and the TripoSR model, about 1.7 GB. It turns one picture into a 3D model on this Mac. Local 3D is never filtered.',+ pcTitle: 'Local 3D needs a one-time download',+ pcBody: 'This sets up ComfyUI itself if it is missing, plus the TRELLIS.2 model files, about 9 GB. Local 3D is never filtered.',+ install: 'Download & install',+ cancel: 'Cancel',+ checking: 'Checking for the 3D engine…',+}++export interface ThreeDSetup {+ /** null while the check runs. */+ ready: boolean | null+ needsSetup: boolean+ installing: boolean+ line: string | null+ error: string | null+ install: () => void+ cancel: () => void+}++/** Whether the local 3D engine of this machine is there, and the means to+ * set it up. Asks nothing while `active` is false. */+export function useThreeDLocal(active: boolean): ThreeDSetup {+ const mac = isMlxImageHost()+ const { installModelBundle } = useCreateExp()+ const [ready, setReady] = useState<boolean | null>(null)+ const [installing, setInstalling] = useState(false)+ const [line, setLine] = useState<string | null>(null)+ const [error, setError] = useState<string | null>(null)+ const abort = useRef<AbortController | null>(null)++ const check = useCallback(async () => {+ try {+ if (mac) {+ const { getMesh3dStatus } = await import('../../../api/mlx-3d')+ const st = await getMesh3dStatus()+ return !!st.installed+ }+ const { comfyThreeDReady } = await import('../../../lib/local-3d-comfy')+ return await comfyThreeDReady()+ } catch {+ return false+ }+ }, [mac])++ useEffect(() => {+ if (!active) return+ let alive = true+ void check().then((ok) => { if (alive) setReady(ok) })+ return () => { alive = false }+ }, [active, check])++ const install = useCallback(() => {+ if (installing) return+ const controller = new AbortController()+ abort.current = controller+ setInstalling(true)+ setError(null)+ void (async () => {+ try {+ if (mac) {+ const api = await import('../../../api/mlx-3d')+ await api.installMesh3d()+ for (;;) {+ if (controller.signal.aborted) {+ await api.cancelMesh3dInstall().catch(() => undefined)+ break+ }+ const st = await api.getMesh3dInstallStatus()+ setLine(installLine(st))+ if (st.status === 'complete') break+ if (st.status === 'error') throw new Error(st.error ?? 'The 3D setup stopped.')+ await new Promise((r) => setTimeout(r, 1000))+ }+ } else {+ await installModelBundle('3d', (msg) => setLine(msg), controller.signal)+ }+ setReady(await check())+ } catch (err) {+ if (!controller.signal.aborted) setError(err instanceof Error ? err.message : String(err))+ } finally {+ setInstalling(false)+ setLine(null)+ abort.current = null+ }+ })()+ }, [installing, mac, check, installModelBundle])++ const cancel = useCallback(() => abort.current?.abort(), [])++ return { ready, needsSetup: active && ready === false, installing, line, error, install, cancel }+}++function installLine(st: { status: string; download_progress?: number; download_total?: number; logs?: string[] }): string | null {+ if (st.download_total && st.download_total > 0) {+ const pct = Math.min(100, Math.floor(((st.download_progress ?? 0) / st.download_total) * 100))+ return `Downloading… ${pct}%`+ }+ return st.logs?.length ? st.logs[st.logs.length - 1] : null+}++export function ThreeDSetupCard({ setup }: { setup: ThreeDSetup }) {+ const mac = isMlxImageHost()+ return (+ <div className="flex flex-col items-center gap-3 max-w-[440px] text-center p-6" data-testid="three-d-setup">+ <Box size={30} className="text-gray-400" />+ <h3 className="t-title text-gray-100">{mac ? SETUP_TEXT.macTitle : SETUP_TEXT.pcTitle}</h3>+ <p className="t-body text-gray-400">{mac ? SETUP_TEXT.macBody : SETUP_TEXT.pcBody}</p>+ {setup.installing ? (+ <>+ <p className="t-meta text-gray-300" data-testid="three-d-setup-line">{setup.line ?? T.phases.ready}</p>+ <Button variant="secondary" onClick={setup.cancel}>{SETUP_TEXT.cancel}</Button>+ </>+ ) : (+ <Button onClick={setup.install} data-testid="three-d-setup-install">{SETUP_TEXT.install}</Button>+ )}+ {setup.error && <p className="t-meta text-red-300" role="alert">{setup.error}</p>}+ </div>+ )+}++/** The empty Stage of "From video": the video goes in the Composer, and the+ * first still frame will stand here. */+export function ThreeDVideoHint() {+ return (+ <div className="flex flex-col items-center gap-2 max-w-[420px] text-center p-6" data-testid="three-d-video-hint">+ <Film size={28} className="text-gray-400" />+ <p className="t-body text-gray-300">{T.dropVideo}</p>+ <p className="t-meta text-gray-500">{T.dropVideoSub}</p>+ </div>+ )+}diff --git a/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx b/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsxindex e18df2a7..80fe71d9 100644--- a/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx+++ b/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx@@ -54,7 +54,7 @@ describe('the rule', () => {})it('off on a Mac: only what the Mac runs itself', () => {- expect(visibleIntents('local', true, false).map((m) => m.id)).toEqual(['image', 'removebg', 'video', 'character'])+ expect(visibleIntents('local', true, false).map((m) => m.id)).toEqual(['image', 'removebg', 'video', 'character', '3d'])})it('cloud mode shows everything, whatever the switch says', () => {diff --git a/src/components/create/experimental/__tests__/fit-stage-height.test.ts b/src/components/create/experimental/__tests__/fit-stage-height.test.tsindex 1a5f0b0d..81d799ac 100644--- a/src/components/create/experimental/__tests__/fit-stage-height.test.ts+++ b/src/components/create/experimental/__tests__/fit-stage-height.test.ts@@ -41,7 +41,7 @@ describe('who uses it', () => {const stage = source('Stage.tsx')expect(stage).toContain('return <FitStage picture={picture} side={controls} capVh={52} onDragOver={onDragOver} onDrop={onDrop} />')// B45: the Image tab hands the result its reference images as the side.- expect(stage).toContain('side={meta.needsSource && source ? <ResultInputs /> : imageRefSide ? <ImageReferenceStrip /> : undefined}')+ expect(stage).toContain('side={needsSource && source ? <ResultInputs /> : imageRefSide ? <ImageReferenceStrip /> : undefined}')// No host is asked, and the column that scrolled is gone.expect(stage).not.toMatch(/isMlxImageHost\(\)[^\n]*FitStage|FitStage[^\n]*isMlxImageHost\(\)/)expect(stage).not.toContain('ResultSourceActions')diff --git a/src/components/create/experimental/__tests__/intents.test.ts b/src/components/create/experimental/__tests__/intents.test.tsindex 98167e3f..e70aed86 100644--- a/src/components/create/experimental/__tests__/intents.test.ts+++ b/src/components/create/experimental/__tests__/intents.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { INTENTS, INTENT_MAP, isIntentAvailable, isIntentLocked, visibleIntents } from '../intents'+import { INTENTS, INTENT_MAP, intentNeedsSource, intentTakesPrompt, isIntentAvailable, isIntentLocked, visibleIntents } from '../intents'import { LOCAL_LANE_OPS, LOCAL_UTILITY_OPS } from '../../../../stores/createStore'// 2026-07-10 made the advanced ops cloud-only; 2026-07-12 brought@@ -52,9 +52,9 @@ describe('intent cloud gating', () => {expect(fromMeta).toEqual([...LOCAL_LANE_OPS, ...LOCAL_UTILITY_OPS].sort())})- it('the local IntentBar filter keeps the 5 classic tabs, Enhance and the 5 lanes selectable', () => {+ it('the local IntentBar filter keeps the 5 classic tabs, Enhance, the 5 lanes and 3D selectable', () => {const selectable = INTENTS.filter((m) => !m.cloudOnly || m.hasLocalLane).map((m) => m.id)- expect(selectable).toEqual(['image', 'edit', 'removebg', 'upscale', 'video', 'animate', 'character', 'lipsync', 'music', 'extend', 'motion'])+ expect(selectable).toEqual(['image', 'edit', 'removebg', 'upscale', 'video', 'animate', 'character', 'lipsync', 'music', 'extend', 'motion', '3d'])// …and that IS what the pure filter reports for a ComfyUI local host.expect(unlocked('local', false)).toEqual(selectable)})@@ -96,11 +96,12 @@ describe('intent cloud gating', () => {// /upload/image, which does not exist there either. So on a local MLX Mac an// intent must never render as an active local tab unless MLX really runs it.describe('intent gating on a local MLX Mac (no ComfyUI)', () => {- it('only image, video, the cutout and Character Studio stay real local tabs', () => {+ it('only image, video, the cutout, Character Studio and 3D stay real local tabs', () => {// Remove Background runs on Vision in macOS (commands/mlx_cutout.rs).// Character Studio runs "Use character" through mflux with the LoRA from- // the Mac's LoRA folder; its Train tab says where to train.- expect(unlocked('local', true)).toEqual(['image', 'removebg', 'video', 'character'])+ // the Mac's LoRA folder; its Train tab says where to train. 3D (3.1.0) is+ // TripoSR's own engine; without it the Stage offers the setup.+ expect(unlocked('local', true)).toEqual(['image', 'removebg', 'video', 'character', '3d'])})it('the hosted-only tools AND the 2.5.8 lanes become cloud teasers', () => {@@ -189,3 +190,26 @@ describe('intent gating on a local MLX Mac (no ComfyUI)', () => {}})})++describe('3D (3.1.0)', () => {+ it('is the last pill, so no tool moves', () => {+ expect(INTENTS[INTENTS.length - 1].id).toBe('3d')+ expect(INTENT_MAP['3d'].short).toBe('3D')+ })+ it('takes a prompt from text only, and a source from a picture or a video', () => {+ expect(intentTakesPrompt('3d', false, 'text')).toBe(true)+ expect(intentTakesPrompt('3d', false, 'image')).toBe(false)+ expect(intentTakesPrompt('3d', false, 'video')).toBe(false)+ expect(intentNeedsSource('3d', 'text')).toBe(false)+ expect(intentNeedsSource('3d', 'image')).toBe(true)+ expect(intentNeedsSource('3d', 'video')).toBe(true)+ // Every other tab keeps its own flags.+ expect(intentNeedsSource('animate')).toBe(true)+ expect(intentTakesPrompt('image')).toBe(true)+ })+ it('is a working tab in the cloud, on ComfyUI and on a Mac', () => {+ expect(unlocked('cloud', false)).toContain('3d')+ expect(unlocked('local', false)).toContain('3d')+ expect(unlocked('local', true)).toContain('3d')+ })+})diff --git a/src/components/create/experimental/__tests__/mac-animate-lane.test.ts b/src/components/create/experimental/__tests__/mac-animate-lane.test.tsindex 78c0c228..5a2ddebf 100644--- a/src/components/create/experimental/__tests__/mac-animate-lane.test.ts+++ b/src/components/create/experimental/__tests__/mac-animate-lane.test.ts@@ -79,7 +79,7 @@ describe('the Animate tab on the Mac', () => {// cutout is there on every Mac (Vision, commands/mlx_cutout.rs), and so// is Character Studio. Extend Video runs on the same models as Animate// since 14.10.2026 (M1), so it comes with it.- expect(visibleIntents('local', true, false, true).map((m) => m.id)).toEqual(['image', 'removebg', 'video', 'animate', 'character', 'extend'])+ expect(visibleIntents('local', true, false, true).map((m) => m.id)).toEqual(['image', 'removebg', 'video', 'animate', 'character', 'extend', '3d'])})it('changes nothing on a ComfyUI host, with or without the flag', () => {diff --git a/src/components/create/experimental/__tests__/mac-upscale-lane.test.ts b/src/components/create/experimental/__tests__/mac-upscale-lane.test.tsindex 7259e1bd..e0ad22b9 100644--- a/src/components/create/experimental/__tests__/mac-upscale-lane.test.ts+++ b/src/components/create/experimental/__tests__/mac-upscale-lane.test.ts@@ -25,7 +25,7 @@ describe('the Enhance tab on the Mac', () => {expect(isIntentLocked(INTENT_MAP.upscale, 'local', true, false, false, true)).toBe(false)expect(isIntentAvailable('upscale', 'local', true, false, false, true)).toBe(true)// With the teasers off it is still there: it is no teaser.- expect(ids(true, false)).toEqual(['image', 'removebg', 'upscale', 'video', 'character'])+ expect(ids(true, false)).toEqual(['image', 'removebg', 'upscale', 'video', 'character', '3d'])})it('opens no other tab: Edit, Erase and Animate keep their own rules', () => {diff --git a/src/components/create/experimental/intents.ts b/src/components/create/experimental/intents.tsindex de9b7d10..0079a8b0 100644--- a/src/components/create/experimental/intents.ts+++ b/src/components/create/experimental/intents.ts@@ -1,9 +1,10 @@import {Image as ImageIcon, Wand2, Scissors, Video, Film, Maximize2, Eraser,- UserRound, Mic, Music, FastForward, PersonStanding,+ UserRound, Mic, Music, FastForward, PersonStanding, Box,} from 'lucide-react'import type { LucideIcon } from 'lucide-react'-import type { CreateBackend, CreateIntent } from '../../../stores/createStore'+import type { CreateBackend, CreateIntent, ThreeDWay } from '../../../stores/createStore'+import { THREE_D_TEXT } from '../../../lib/three/three-d-text'import { MUSIC_PLACEHOLDER } from '../../../lib/render/music-ui'export interface IntentMeta {@@ -178,6 +179,20 @@ export const INTENTS: IntentMeta[] = [cloudOnly: true, hasLocalLane: true, requiresModels: 'motion',examples: [],},+ {+ // 3.1.0 (C3D-PLAN): a 3D model from words, a picture or a video. The+ // thirteenth pill, at the far right, so no tool moves. Which inputs it+ // takes depends on the way (intentNeedsSource / intentTakesPrompt), so+ // the two flags here stay false. Local: TripoSR on a Mac (its own+ // engine, commands/mesh3d.rs), TRELLIS.2 in ComfyUI on Windows and Linux.+ // The Stage gates the local tab on its own setup card, not on+ // requiresModels.+ id: '3d', label: '3D Model', short: '3D', icon: Box,+ placeholder: THREE_D_TEXT.prompt,+ needsSource: false, needsPrompt: false, allowsMask: false, isVideo: false,+ cloudOnly: true, hasLocalLane: true,+ examples: THREE_D_TEXT.examples,+ },]export const INTENT_MAP: Record<CreateIntent, IntentMeta> =@@ -188,10 +203,18 @@ export const INTENT_MAP: Record<CreateIntent, IntentMeta> =* one: a view without the field must never send the text left over from* another tab. Character Studio's use surface is a plain image generate and* has one. */-export function intentTakesPrompt(intent: CreateIntent, characterUse = false): boolean {+export function intentTakesPrompt(intent: CreateIntent, characterUse = false, threeDWay: ThreeDWay = 'image'): boolean {+ if (intent === '3d') return threeDWay === 'text'return INTENT_MAP[intent].needsPrompt || characterUse}+/** Does the view need a picture on the Stage before it can start? 3D needs+ * one from a picture and from a video (the first still frame stands there). */+export function intentNeedsSource(intent: CreateIntent, threeDWay: ThreeDWay = 'image'): boolean {+ if (intent === '3d') return threeDWay !== 'text'+ return INTENT_MAP[intent].needsSource+}+/** Does the view on `backend` show a prompt field that may stay empty?* Motion Control on the local lanes. The start sends what is typed there,* and Create does not wait for it. */@@ -232,7 +255,9 @@ export function intentTakesOptionalPrompt(intent: CreateIntent, backend: CreateB// LoRA folder on the second image engine (mflux `--lora`), the way Windows// runs it in ComfyUI. Training stays off on the Mac (LocalTrainControls is a// ComfyUI/CUDA trainer); the tab says where to train instead.-const MLX_LOCAL_INTENTS: ReadonlySet<CreateIntent> = new Set<CreateIntent>(['image', 'video', 'removebg', 'character'])+// 3D (3.1.0) is a local tab on every Mac: without the engine the Stage shows+// its one-time setup card (commands/mesh3d.rs, TripoSR).+const MLX_LOCAL_INTENTS: ReadonlySet<CreateIntent> = new Set<CreateIntent>(['image', 'video', 'removebg', 'character', '3d'])/*** Edit is the second lane with a source that the Mac serves: Qwen-Image 2.1diff --git a/src/components/create/experimental/useRunCredits.ts b/src/components/create/experimental/useRunCredits.tsindex fab9714d..83b072f7 100644--- a/src/components/create/experimental/useRunCredits.ts+++ b/src/components/create/experimental/useRunCredits.ts@@ -2,7 +2,7 @@ import { useCreateStore } from '../../../stores/createStore'import { useCreateExp } from './CreateContext'import { intentToJob, quotaCostKind, type RenderKind, type RenderOp } from '../../../lib/render/cloud-jobs'import { lengthCredits, lengthPrice, runCredits } from '../../../stores/cloudCatalogStore'-import { createRunModel, createStudioCost, isStudioModel, startImageCount } from '../../../lib/render/create-studio'+import { createRunModel, createStudioCost, isStudioModel, startImageCount, studioIntentOf } from '../../../lib/render/create-studio'import { STUDIO_MODELS } from '../../../lib/render/studio-contract'import { runImageCount } from '../../../lib/render/image-count'@@ -25,6 +25,7 @@ export function useRunCredits(): RunCredits | null {const intent = useCreateStore((s) => s.intent())const cloudImageModel = useCreateStore((s) => s.cloudImageModel)const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)+ const threeDWay = useCreateStore((s) => s.threeDWay)const cloudOpModel = useCreateStore((s) => s.cloudOpModel)const characterTab = useCreateStore((s) => s.characterTab)const selectedCharacter = useCreateStore((s) => s.selectedCharacter)@@ -63,7 +64,7 @@ export function useRunCredits(): RunCredits | null {// Wahl, die die Unterkategorie nicht fahren kann, rechnet hier als das Modell,// das wirklich laeuft.const model = createRunModel(- intent,+ studioIntentOf(intent, threeDWay),{ image: cloudImageModel, video: cloudVideoModel, op: cloudOpModel },characterUse ? selectedCharacter?.family ?? '' : undefined,)diff --git a/src/components/three/LazyModelViewer.tsx b/src/components/three/LazyModelViewer.tsxnew file mode 100644index 00000000..1f77378a--- /dev/null+++ b/src/components/three/LazyModelViewer.tsx@@ -0,0 +1,21 @@+// The 3D view, fetched on first use: three and its loaders stay out of the+// bundle the app starts with.+import { Suspense, lazy } from 'react'+import { Box } from 'lucide-react'+import type { ModelViewerProps } from './ModelViewer'++const ModelViewer = lazy(() => import('./ModelViewer'))++export function LazyModelViewer(props: ModelViewerProps) {+ return (+ <Suspense+ fallback={+ <div className="flex w-full h-full min-h-[280px] items-center justify-center rounded-[var(--radius-panel)] border border-white/[0.06]">+ <Box size={28} className="text-gray-500 animate-pulse" />+ </div>+ }+ >+ <ModelViewer {...props} />+ </Suspense>+ )+}diff --git a/src/components/three/ModelThumb.tsx b/src/components/three/ModelThumb.tsxnew file mode 100644index 00000000..b64be263--- /dev/null+++ b/src/components/three/ModelThumb.tsx@@ -0,0 +1,38 @@+// The gallery tile of a 3D model: the still the 3D view drew of it, with a+// small cube in the corner. Before a still exists the tile shows the cube and+// the entry's name, like the audio tile.+import { useEffect, useState } from 'react'+import { Box } from 'lucide-react'+import type { GalleryItem } from '../../stores/createStore'+import { galleryLabel } from '../../lib/render/gallery-label'+import { onPoster, readPoster } from '../../lib/three/mesh-poster'++export function usePoster(id: string): string | null {+ const [poster, setPoster] = useState<string | null>(null)+ useEffect(() => {+ let alive = true+ const read = () => void readPoster(id).then((p) => { if (alive) setPoster(p) })+ read()+ const off = onPoster((changed) => { if (changed === id) read() })+ return () => { alive = false; off() }+ }, [id])+ return poster+}++export function ModelThumb({ item, small }: { item: GalleryItem; small?: boolean }) {+ const poster = usePoster(item.id)+ if (!poster) {+ return (+ <span className="w-full h-full flex flex-col items-center justify-center gap-1 bg-white/[0.03] text-gray-400 p-1" data-testid="thumb-3d">+ <Box size={16} />+ {!small && <span className="t-label truncate max-w-full px-1">{galleryLabel(item)}</span>}+ </span>+ )+ }+ return (+ <>+ <img src={poster} alt="" loading="lazy" decoding="async" className="w-full h-full object-cover" data-testid="thumb-3d" />+ <span className="absolute bottom-1 right-1 rounded bg-black/55 p-0.5"><Box size={12} className="text-white/90" /></span>+ </>+ )+}diff --git a/src/components/three/ModelViewer.tsx b/src/components/three/ModelViewer.tsxnew file mode 100644index 00000000..6594f69f--- /dev/null+++ b/src/components/three/ModelViewer.tsx@@ -0,0 +1,224 @@+// The 3D view on the Stage, in the large view and on the phone (C3D-PLAN 1.3).+// A thin React shell around lib/three/mesh-viewer.ts. Loaded on demand+// (LazyModelViewer.tsx), so three never weighs on the start of the app.+import { useCallback, useEffect, useRef, useState } from 'react'+import { Box, Download, Maximize2, Moon, RefreshCw, RotateCcw, Sun } from 'lucide-react'+import type { GalleryItem } from '../../stores/createStore'+import { createMeshViewer, webglAvailable, type MeshBackdrop, type MeshLook, type MeshViewer } from '../../lib/three/mesh-viewer'+import { factsLine, isHeavyFile } from '../../lib/three/mesh-facts'+import { exportMesh, MESH_FORMATS, type MeshFormat } from '../../lib/three/mesh-export'+import { readPoster, writePoster } from '../../lib/three/mesh-poster'+import { HEAVY_TRIANGLES } from '../../lib/three/mesh-facts'+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'++export const VIEWER_TEXT = {+ hint: 'Drag to turn. Scroll to zoom.',+ hintTouch: 'Drag to turn. Pinch to zoom.',+ turn: 'Turn by itself',+ looks: { color: 'Color', clay: 'Clay', wireframe: 'Wireframe' } as Record<MeshLook, string>,+ backdrop: 'Light or dark background',+ reset: 'Reset view',+ fullscreen: 'Full screen',+ download: 'Download',+ loading: 'Opening your model…',+ heavy: 'This model is too heavy to show here. You can still download it.',+ showAnyway: 'Show it anyway',+ noWebgl: 'The 3D view needs graphics acceleration, and it is off on this device. You can still download the model.',+ saveFailed: 'This format could not be made from this model. The GLB download still works.',+}++const LOOKS: MeshLook[] = ['color', 'clay', 'wireframe']++type Phase = 'loading' | 'heavy' | 'ready' | 'error' | 'no-webgl'++export interface ModelViewerProps {+ item: GalleryItem+ className?: string+ /** Opens the large view. Left out where the viewer already is that view. */+ onFullscreen?: () => void+ /** Touch wording (the phone). */+ touch?: boolean+}++export default function ModelViewer({ item, className, onFullscreen, touch }: ModelViewerProps) {+ const canvasRef = useRef<HTMLCanvasElement>(null)+ const viewerRef = useRef<MeshViewer | null>(null)+ const bytesRef = useRef<Uint8Array | null>(null)+ // Asked once: a device does not gain or lose WebGL while the view is open.+ const [webgl] = useState(webglAvailable)+ const [phase, setPhase] = useState<Phase>(webgl ? 'loading' : 'no-webgl')+ const [message, setMessage] = useState('')+ const [facts, setFacts] = useState('')+ const [look, setLook] = useState<MeshLook>('color')+ const [backdrop, setBackdrop] = useState<MeshBackdrop>('dark')+ const [turning, setTurning] = useState(true)+ const [menu, setMenu] = useState(false)+ const [force, setForce] = useState(false)++ useEffect(() => {+ if (!webgl) return+ const canvas = canvasRef.current+ if (!canvas) return+ let alive = true+ const viewer = createMeshViewer(canvas, { onUserTouch: () => setTurning(false) })+ viewerRef.current = viewer+ void (async () => {+ try {+ const blob = await fetchGalleryItemBlob(item)+ const bytes = new Uint8Array(await blob.arrayBuffer())+ if (!alive) return+ bytesRef.current = bytes+ if (isHeavyFile(bytes.byteLength) && !force) {+ setPhase('heavy')+ return+ }+ const loaded = await viewer.load(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer)+ if (!alive) return+ if (loaded.triangles > HEAVY_TRIANGLES && !force) {+ setPhase('heavy')+ return+ }+ markGalleryItemAvailable(item)+ setFacts(factsLine(loaded.triangles, bytes.byteLength))+ setTurning(true)+ setPhase('ready')+ // The gallery tile gets its still from the first good view.+ if (!(await readPoster(item.id))) {+ requestAnimationFrame(() => {+ const still = viewer.poster()+ if (still) void writePoster(item.id, still)+ })+ }+ } catch (err) {+ if (!alive) return+ setMessage(err instanceof MeshLoadError || err instanceof Error ? err.message : String(err))+ setPhase('error')+ }+ })()+ return () => {+ alive = false+ viewer.dispose()+ viewerRef.current = null+ }+ }, [item, force, webgl])++ useEffect(() => viewerRef.current?.setLook(look), [look])+ useEffect(() => viewerRef.current?.setBackdrop(backdrop), [backdrop])+ useEffect(() => viewerRef.current?.setAutoTurn(turning), [turning])++ const save = useCallback(async (format: MeshFormat) => {+ setMenu(false)+ const original = bytesRef.current+ const root = viewerRef.current?.model()+ if (!original) return+ try {+ const bytes = format === 'glb' || !root ? original : await exportMesh(format, root, original)+ await saveBytes(bytes, `lu-${item.id}.${format}`, format)+ } catch {+ setMessage(VIEWER_TEXT.saveFailed)+ }+ }, [item.id])++ const canExport = phase === 'ready'+ return (+ <div+ className={cn('relative flex flex-col w-full h-full min-h-[280px] rounded-[var(--radius-panel)] overflow-hidden border border-white/[0.06]', className)}+ data-testid="model-viewer"+ data-phase={phase}+ >+ <canvas ref={canvasRef} className={cn('w-full flex-1 min-h-0 block touch-none', phase !== 'ready' && 'opacity-0')} data-testid="model-viewer-canvas" />+ {phase !== 'ready' && (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center bg-black/40">+ <Box size={28} className={cn('text-gray-400', phase === 'loading' && 'animate-pulse')} />+ <p className="t-body text-gray-300 max-w-[360px]" data-testid="model-viewer-state">+ {phase === 'loading' ? VIEWER_TEXT.loading+ : phase === 'heavy' ? VIEWER_TEXT.heavy+ : phase === 'no-webgl' ? VIEWER_TEXT.noWebgl+ : message}+ </p>+ {phase === 'heavy' && (+ <button type="button" className="t-control underline underline-offset-2 text-gray-200" onClick={() => { setPhase('loading'); setForce(true) }}>+ {VIEWER_TEXT.showAnyway}+ </button>+ )}+ </div>+ )}+ <div className="absolute top-2 right-2 flex gap-1" data-testid="model-viewer-bar">+ {phase === 'ready' && (+ <>+ <Btn title={VIEWER_TEXT.turn} pressed={turning} onClick={() => setTurning((t) => !t)} testid="mv-turn"><RefreshCw size={14} /></Btn>+ <div className="flex rounded-lg bg-black/50 backdrop-blur overflow-hidden" role="group" aria-label="Look">+ {LOOKS.map((l) => (+ <button+ key={l}+ type="button"+ aria-pressed={look === l}+ data-testid={`mv-look-${l}`}+ onClick={() => setLook(l)}+ className={cn('lu-on-dark px-2 h-7 t-control', look === l ? 'text-white bg-white/10' : 'text-gray-300 hover:text-white')}+ >+ {VIEWER_TEXT.looks[l]}+ </button>+ ))}+ </div>+ <Btn title={VIEWER_TEXT.backdrop} onClick={() => setBackdrop((b) => (b === 'dark' ? 'light' : 'dark'))} testid="mv-backdrop">+ {backdrop === 'dark' ? <Sun size={14} /> : <Moon size={14} />}+ </Btn>+ <Btn title={VIEWER_TEXT.reset} onClick={() => viewerRef.current?.reset()} testid="mv-reset"><RotateCcw size={14} /></Btn>+ </>+ )}+ {onFullscreen && <Btn title={VIEWER_TEXT.fullscreen} onClick={onFullscreen} testid="mv-fullscreen"><Maximize2 size={14} /></Btn>}+ <div className="relative">+ <Btn title={VIEWER_TEXT.download} onClick={() => (canExport ? setMenu((m) => !m) : void save('glb'))} testid="mv-download"><Download size={14} /></Btn>+ {menu && (+ <div className="absolute right-0 top-8 z-10 min-w-[230px] rounded-lg bg-[var(--lu-surface,#1c1d22)] border border-white/10 shadow-xl py-1" role="menu">+ {MESH_FORMATS.map((f) => (+ <button+ key={f.id}+ type="button"+ role="menuitem"+ data-testid={`mv-save-${f.id}`}+ onClick={() => void save(f.id)}+ className="lu-on-dark w-full text-left px-3 py-1.5 t-control text-gray-200 hover:bg-white/5"+ >+ {f.label} <span className="text-gray-500">· {f.note}</span>+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ {phase === 'ready' && (+ <div className="absolute bottom-2 left-3 right-3 flex justify-between gap-3 t-mono text-gray-400 pointer-events-none">+ <span data-testid="model-viewer-facts">{facts}</span>+ <span className="hidden sm:inline">{touch ? VIEWER_TEXT.hintTouch : VIEWER_TEXT.hint}</span>+ </div>+ )}+ {phase === 'ready' && message && (+ <div className="absolute bottom-8 left-3 t-mono text-red-300" data-testid="model-viewer-note">{message}</div>+ )}+ </div>+ )+}++function Btn({ children, title, onClick, pressed, testid }: { children: React.ReactNode; title: string; onClick: () => void; pressed?: boolean; testid: string }) {+ return (+ <button+ type="button"+ title={title}+ aria-label={title}+ aria-pressed={pressed}+ onClick={onClick}+ data-testid={testid}+ className={cn(+ 'lu-on-dark w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 backdrop-blur transition-colors',+ pressed ? 'text-white bg-white/15' : 'text-gray-200 hover:text-white hover:bg-black/70',+ )}+ >+ {children}+ </button>+ )+}diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex 59e11271..b8aa36b9 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -36,7 +36,10 @@ import { contentPolicySnapshot, loadContentPolicy } from './useContentPolicy'import { effectiveContentPolicy } from '../lib/content-policy-cap'import { signalCreditsExhausted } from '../lib/credits-exhausted'import { resolveRunSeed } from '../lib/run-seed'-import { intentRoles, intentRequiredInputs, isStudioModel, resolveIntentPick, studioExtraPhotoSlots, cloudTakesEndImage } from '../lib/render/create-studio'+import { intentRoles, intentRequiredInputs, isStudioModel, resolveIntentPick, studioExtraPhotoSlots, cloudTakesEndImage, studioIntentOf } from '../lib/render/create-studio'+import { threeDMaxViews } from '../lib/three/three-d-models'+import { threeDProvenance } from '../lib/three/run-local-3d'+import { THREE_D_TEXT } from '../lib/three/three-d-text'import { bumpSeed, runImageCount } from '../lib/render/image-count'import { STUDIO_MODELS, studioFields } from '../lib/render/studio-contract'import { modelLabel } from '../lib/render/preset-models'@@ -289,12 +292,14 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// models (create-studio.ts, ported P2); resolveIntentPick's list already// contains both, so it replaces resolveOpPick for exactly these four.// Character-use never touches Studio: it stays on its fixed -lora family.- const roleIntent = !characterUse && intentRoles(intent).length > 0+ // The 3D tab runs another set of models per way (create-studio.ts).+ const pickIntent = studioIntentOf(intent, s.threeDWay)+ const roleIntent = !characterUse && intentRoles(pickIntent).length > 0let picked: stringif (characterUse) {picked = resolveCharacterModel(s.selectedCharacter?.family ?? '', s.cloudOpModel) ?? ''} else if (roleIntent) {- picked = resolveIntentPick(intent, s.cloudOpModel)+ picked = resolveIntentPick(pickIntent, s.cloudOpModel)} else if (specialOp) {// Same resolution rule as the chip's display — a pick left over from// another intent must not survive into this op's submit (take-01: the@@ -326,7 +331,10 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// Motion Control, the utility ops, training) sends none: the store holds one// prompt for every tab, and the text left from another tab would steer the// run unseen or fail the content check for words nobody sees here.- const prompt = intentTakesPrompt(intent, characterUse) ? s.prompt : ''+ const prompt = intentTakesPrompt(intent, characterUse, s.threeDWay) ? s.prompt : ''+ // 3D from a picture or a video: where those pictures came from, for the+ // content gate here and on the server (params.source_prompt).+ const provenance = intent === '3d' && s.threeDWay !== 'text' ? threeDProvenance(s) : ''s.setError(null)if (!cloudMediaLive()) {// Server MEDIA_LIVE switch is off — the GPU fleet isn't up, a submit@@ -352,7 +360,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {const sendsClassicKnobs = !studioModel && !specialOp && op !== 'removebg' && op !== 'upscale' && op !== 'eraser'const lyrics = op === 'music' && !studioModel ? s.musicLyrics : ''const triggerWord = op === 'lora-train' ? s.triggerWord : ''- const verdict = clientSafety(`${prompt} ${lyrics} ${triggerWord}`, sendsClassicKnobs ? s.negativePrompt : '')+ const verdict = clientSafety(`${prompt} ${lyrics} ${triggerWord} ${provenance}`, sendsClassicKnobs ? s.negativePrompt : '')if (verdict.blocked) {s.setError(blockMessageFor(verdict.reason))return@@ -530,7 +538,10 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// Also exactly what a Studio role's `image` input needs (source_path),// the SAME staged upload, studio-contract.ts just names it a schema// field instead of a fixed param.- if (op !== 'generate' && s.source) {+ if (provenance) params.source_prompt = provenance+ // "From text" sends no picture: a source left on the Stage from another+ // way belongs to that way.+ if (op !== 'generate' && s.source && !(intent === '3d' && s.threeDWay === 'text')) {params.source_path = await uploadInput(dataUrlToBlob(s.source.url), 'source', ...uploadEnds(ac))// Ein Studio-Modell, das eine Bilderliste liest (Edit mit mehreren// Vorlagen, Referenz zu Video), bekommt das Standbild der Oberflaeche als@@ -541,7 +552,9 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// Das Standbild ist das erste Foto, die Leiste liefert die weiteren// bis zur Grenze dieses Modells. Jedes geht in die eigene Ablage.const extras = intent === 'edit' || intent === 'animate'- ? s.references.slice(0, studioExtraPhotoSlots(studioModel)) : []+ ? s.references.slice(0, studioExtraPhotoSlots(studioModel))+ // 3D: the further sides (or still frames) after the Front.+ : intent === '3d' ? s.threeDViews.slice(0, threeDMaxViews(studioModel) - 1) : []const more: string[] = []for (const [i, ref] of extras.entries()) {if (ac.signal.aborted) return@@ -749,7 +762,9 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// list view (GET /api/jobs), not the only source of the gallery name.let label: string | undefinedif (studioModel) {- label = prompt.trim() ? undefined : modelLabel(studioModel)+ label = prompt.trim() ? undefined+ : intent === '3d' ? THREE_D_TEXT.gallery[s.threeDWay]+ : modelLabel(studioModel)if (label) params.label = label} else if (OP_GALLERY_LABEL[op]) {label = OP_GALLERY_LABEL[op]@@ -828,7 +843,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// Video renders and character training routinely run several minutes// and can queue behind other jobs on the shared fleet — give them a// much longer client deadline than images.- const verb = opProgressVerb(op)+ const verb = kind === '3d' ? THREE_D_TEXT.cloudPhase : opProgressVerb(op)const addResult = (job: CloudJob, index = 0) => useCreateStore.getState().addToGallery({...galleryItemFromJob(job),...resultFields(index),diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 1e85e8aa..5bbf445e 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -1,5 +1,7 @@import { useState, useCallback, useRef, useEffect } from 'react'import { blobFromUrl } from '../lib/render/data-url'+import { THREE_D_TEXT } from '../lib/three/three-d-text'+import { MAC_3D_MODEL, MAC_DETAIL_RESOLUTION, PC_3D_MODEL, threeDGalleryItem, threeDPicturePrompt, threeDProvenance } from '../lib/three/run-local-3d'import { coverCropBlob } from '../lib/cover-crop'import { videoRunGivenUp, videoRunProgress, videoRunStatus } from '../lib/mlx-video-progress'import { featherMaskBlob } from '../lib/mask-feather'@@ -103,7 +105,7 @@ import { buildTrainCaption } from '../lib/train-captions'import { trainTriggerWord } from '../lib/train-trigger'import { characterThisWouldReplace, useTrainReplaceStore } from '../stores/trainReplaceStore'import { buildStyleCaption, missingNameLine, trainedLine, trainedLoraFile } from '../lib/train-kind'-import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState, type GalleryItem } from '../stores/createStore'+import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, imageModelParams, type CreateState, type GalleryItem } from '../stores/createStore'import { useWorkflowStore } from '../stores/workflowStore'import { useSettingsStore } from '../stores/settingsStore'import { useRenderPreviewStore } from '../stores/renderPreviewStore'@@ -179,6 +181,72 @@ async function freeMacMemoryForRender(say: (text: string) => void): Promise<Rend}}+/**+ * The local 3D run (3.1.0, C3D-PLAN 2.3/2.4): the picture on the Stage, and+ * the sides of a video, become one GLB in the gallery. The content gate ran+ * before this in runOnce. A Mac hands the chat model's memory over first, as+ * for any render.+ */+async function runLocalThreeD(state: CreateState, seed: number, abortRef: { current: AbortController | null }): Promise<void> {+ const { source, setError, setIsGenerating, setProgress, addToGallery } = state+ setError(null)+ if (!source) {+ setError(THREE_D_TEXT.needSource)+ return+ }+ const own = new AbortController()+ abortRef.current = own+ setIsGenerating(true)+ state.setProgressPhase('loading-model')+ setProgress(0, THREE_D_TEXT.phases.ready)+ const mac = isMlxImageHost()+ const eviction = mac ? await freeMacMemoryForRender((text) => setProgress(0, text)) : null+ const started = Date.now()+ const way = state.threeDWay+ const prompt = way === 'text' ? state.prompt.trim() : ''+ const onProgress = (percent: number | undefined, text: string) => {+ useCreateStore.getState().setProgressPhase('sampling')+ useCreateStore.getState().setProgress(percent ?? 0, text)+ }+ try {+ if (mac) {+ const api = await import('../api/mlx-3d')+ const staged = source.filename || await stageStartImage(await blobFromUrl(source.url))+ const made = await api.runMacMesh3d(+ { imagePath: staged, resolution: MAC_DETAIL_RESOLUTION[state.threeDDetail], cutout: state.threeDCutout },+ { signal: own.signal, onProgress: (percent, text) => onProgress(percent, text) },+ )+ if (own.signal.aborted) return+ addToGallery(threeDGalleryItem({+ id: uuid(), way, model: MAC_3D_MODEL, prompt, seed, localPath: made.path, sourceName: source.name,+ }))+ } else {+ const { runComfyThreeD } = await import('../lib/local-3d-comfy')+ const made = await runComfyThreeD({+ imageName: source.filename, detail: state.threeDDetail, cutout: state.threeDCutout, seed,+ signal: own.signal, onProgress: (line, percent) => onProgress(percent, line),+ })+ if (own.signal.aborted) return+ addToGallery(threeDGalleryItem({+ id: uuid(), way, model: PC_3D_MODEL, prompt, seed,+ filename: made.filename, subfolder: made.subfolder, comfyType: made.type, sourceName: source.name,+ }))+ }+ useCreateStore.getState().setLastGenTime(`${Math.round((Date.now() - started) / 1000)}s`)+ useCreateStore.getState().setProgressPhase('complete')+ setProgress(100, 'Complete!')+ } catch (e) {+ if (!own.signal.aborted) {+ useCreateStore.getState().setError(`3D failed: ${e instanceof Error ? e.message : String(e)}`)+ }+ } finally {+ if (abortRef.current === own) abortRef.current = null+ useCreateStore.getState().setIsGenerating(false)+ useCreateStore.getState().setProgress(0)+ if (eviction) void restoreChatBackendsAfterRender(eviction)+ }+}+/*** The `[event, payload]` pairs of a `/history` status entry.*@@ -771,7 +839,7 @@ export function useCreate() {// one prompt for every tab, and the text left from another tab would steer// the run unseen or fail this check for words nobody sees here.// Motion Control has an optional field here and sends what is typed in it.- const typedPrompt = intentTakesPrompt(state.intent(), state.cloudOp === 'character' && state.characterTab === 'use')+ const typedPrompt = intentTakesPrompt(state.intent(), state.cloudOp === 'character' && state.characterTab === 'use', state.threeDWay)|| intentTakesOptionalPrompt(state.intent(), 'local')? state.prompt: ''@@ -788,8 +856,12 @@ export function useCreate() {{// The negative prompt is read apart (B30, safety.ts): there it keeps// things out of the picture.+ // 3D also reads where its pictures came from (C3D-PLAN 2.8): the gate+ // sees no pixels, so the name of a file and the prompt of a gallery+ // picture are what it can check.+ const provenance = state.intent() === '3d' ? threeDProvenance(state) : ''const verdict = checkPromptSafety(- `${typedPrompt} ${state.musicLyrics} ${state.triggerWord} ${state.videoShots.join(' ')}`,+ `${typedPrompt} ${state.musicLyrics} ${state.triggerWord} ${state.videoShots.join(' ')} ${provenance}`,{ negative: state.negativePrompt },)if (verdict.blocked) {@@ -822,6 +894,14 @@ export function useCreate() {const isI2I = mode === 'image' && state.imageSubMode === 'img2img'// Which redesign intent produced this run (gallery tag).const intent = state.intent()++ // ── 3D (3.1.0): the picture on the Stage becomes a GLB. TripoSR on a+ // Mac (commands/mesh3d.rs), TRELLIS.2 in ComfyUI elsewhere. "From text"+ // painted that picture in a run of its own first (generateInner). ──+ if (intent === '3d') {+ await runLocalThreeD(state, runSeed, abortRef)+ return+ }// The redesigned Create page drives its unified Stage input via `source`/`mask`// ImageRefs. On the local path their `.filename` IS the ComfyUI /upload/image// name, so they map straight onto the existing i2iImage/i2vImage handles.@@ -2688,6 +2768,38 @@ export function useCreate() {const generateInner = useCallback(async () => {const s = useCreateStore.getState()const mac = isMlxImageHost()+ // 3D from text on this machine is two runs (C3D-PLAN 1.2): a picture+ // first, with the image model the user has, then the model from it. The+ // picture lands on the Stage under "From image", where Create makes it 3D+ // and "From text" paints a new one.+ if (s.intent() === '3d' && s.backend === 'local' && s.threeDWay === 'text') {+ if (!s.prompt.trim()) { s.setError('Describe the object first.'); return }+ const lane = imageLaneModels(s.imageModelList, 'image')+ const pick = lane.find((m) => m.name === s.imageModel) ?? lane[0]+ if (!pick) { s.setError(THREE_D_TEXT.needImageModel); return }+ const before = new Set(s.gallery.map((g) => g.id))+ await runOnce({+ mode: 'image', imageSubMode: 'text2img', cloudOp: null, utilityOp: null, removebg: false,+ imageModel: pick.name, imageModelType: pick.type,+ ...imageModelParams({ imageModel: pick.name, imageModelType: pick.type }),+ width: 1024, height: 1024,+ prompt: threeDPicturePrompt(s.prompt), batchSize: 1, hiresFixEnabled: false, improvePrompt: false,+ source: null, mask: null, references: [], i2iImage: null,+ }, { stepLabel: THREE_D_TEXT.pictureFirst })+ const after = useCreateStore.getState()+ if (after.error) return+ const made = after.gallery.find((g) => !before.has(g.id) && g.type === 'image')+ if (!made) return+ try {+ const blob = await fetchGalleryItemBlob(made)+ const ref = await loadImageRef(new File([blob], made.filename || 'picture.png', { type: blob.type || 'image/png' }))+ after.setThreeDWay('image')+ after.setSource(ref)+ } catch (e) {+ after.setError(e instanceof Error ? e.message : String(e))+ }+ return+ }// A long local clip (B18): several sections, each continuing the clip so// far, or one pass with context windows. ComfyUI only; the Mac's MLX// lanes keep their own lengths.diff --git a/src/lib/__tests__/howto-lines-follow-the-film.test.ts b/src/lib/__tests__/howto-lines-follow-the-film.test.tsindex a6d71070..5640b0c6 100644--- a/src/lib/__tests__/howto-lines-follow-the-film.test.ts+++ b/src/lib/__tests__/howto-lines-follow-the-film.test.ts@@ -5,14 +5,21 @@ import { HOWTO, HOWTO_GUIDE_BASE, HOWTO_VIDEO_BASE, howtoGuideUrl, howtoLineAt,import { INTENTS } from '../../components/create/experimental/intents'describe('how it works', () => {+ // 3D (3.1.0) has no film yet: it is recorded once the tab is live. Until+ // then the stage offers none (stageHowtoTopic answers null), instead of a+ // link to a film that is not on the server.+ const NO_FILM_YET = new Set(['3d'])+ const filmed = INTENTS.filter((i) => !NO_FILM_YET.has(i.id))+it('has a film for every Create tab, for Code and for Agent', () => {- for (const intent of INTENTS) expect(HOWTO[intent.id], intent.id).toBeTruthy()+ for (const intent of filmed) expect(HOWTO[intent.id], intent.id).toBeTruthy()+ for (const id of NO_FILM_YET) expect(stageHowtoTopic(id, 'cloud')).toBeNull()expect(HOWTO.code.films.map((f) => f.label)).toEqual(['Modes', 'Slash commands'])expect(HOWTO.agent).toBeTruthy()})it('names each Create film after the tab it stands on', () => {- for (const intent of INTENTS) expect(HOWTO[intent.id].title).toBe(`How ${intent.short} works`)+ for (const intent of filmed) expect(HOWTO[intent.id].title).toBe(`How ${intent.short} works`)})it('keeps the lines of every film in the order they are shown', () => {diff --git a/src/lib/__tests__/local-3d-comfy.test.ts b/src/lib/__tests__/local-3d-comfy.test.tsnew file mode 100644index 00000000..2c7f16ec--- /dev/null+++ b/src/lib/__tests__/local-3d-comfy.test.ts@@ -0,0 +1,205 @@+// Local 3D on Windows and Linux (3.1.0): readiness, the run, its progress line+// and where the finished model is found. ComfyUI is mocked at the module edge.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const submitWorkflow = vi.fn()+const getHistory = vi.fn()+const promptQueueState = vi.fn()+const abandonPrompt = vi.fn()+const folderRead = vi.fn()+vi.mock('../../api/comfyui', async (importOriginal) => {+ const real = await importOriginal<typeof import('../../api/comfyui')>()+ return {+ ...real,+ submitWorkflow: (...a: unknown[]) => submitWorkflow(...a),+ getHistory: (...a: unknown[]) => getHistory(...a),+ promptQueueState: (...a: unknown[]) => promptQueueState(...a),+ abandonPrompt: (...a: unknown[]) => abandonPrompt(...a),+ COMFY_MODEL_FOLDERS: real.COMFY_MODEL_FOLDERS.map((f) => ({ subfolder: f.subfolder, read: () => folderRead(f.subfolder) })),+ }+})+const wsListeners: Array<(e: unknown) => void> = []+const wsConnect = vi.fn()+vi.mock('../../api/comfyui-ws', () => ({+ CLIENT_ID: 'lu-test',+ comfyWS: {+ connect: (...a: unknown[]) => wsConnect(...a),+ mark: () => 0,+ on: (l: (e: unknown) => void) => { wsListeners.push(l); return () => { wsListeners.splice(wsListeners.indexOf(l), 1) } },+ },+}))+const buildLocalThreeDWorkflow = vi.fn()+vi.mock('../../api/dynamic-workflow', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../api/dynamic-workflow')>()),+ buildLocalThreeDWorkflow: (...a: unknown[]) => buildLocalThreeDWorkflow(...a),+}))++import {+ comfyThreeDReady, runComfyThreeD, createThreeDProgress, threeDOutputFromHistory, threeDPhaseForNode,+} from '../local-3d-comfy'+import { buildThreeDWorkflow, THREE_D_NODES, THREE_D_CUTOUT_NODES, THREE_D_SAVE_NODE } from '../../api/dynamic-workflow'+import { TRELLIS2_FILES } from '../../api/model-bundles'++const ALL = Object.fromEntries([...THREE_D_NODES, ...THREE_D_CUTOUT_NODES].map((n) => [n, {}]))+const graph = buildThreeDWorkflow({ image: 'chair.png', detail: 'standard', cutout: true, seed: 7 }, ALL)+const GLB = { filename: 'locally_uncensored_3d_x_00001_.glb', subfolder: '3d', type: 'output' }+const success = { status: { status_str: 'success', completed: true }, outputs: { [THREE_D_SAVE_NODE]: { '3d': [GLB], camera_info: [null] } } }++const ON_DISK: Record<string, string[]> = {+ diffusion_models: [TRELLIS2_FILES.model, 'flux.safetensors'],+ vae: [TRELLIS2_FILES.shapeVae, TRELLIS2_FILES.textureVae],+ clip_vision: [TRELLIS2_FILES.imageEncoder],+ background_removal: [TRELLIS2_FILES.cutout],+}++beforeEach(() => {+ vi.clearAllMocks()+ wsListeners.length = 0+ folderRead.mockImplementation(async (sub: string) => ON_DISK[sub] ?? [])+ buildLocalThreeDWorkflow.mockResolvedValue(graph)+ submitWorkflow.mockResolvedValue('p1')+ getHistory.mockResolvedValue(null)+ promptQueueState.mockResolvedValue('queued')+ wsConnect.mockResolvedValue(undefined)+})+afterEach(() => { vi.useRealTimers() })++describe('comfyThreeDReady', () => {+ it('is true with all five files listed in their folders', async () => {+ expect(await comfyThreeDReady()).toBe(true)+ })++ it('is false with one file missing', async () => {+ folderRead.mockImplementation(async (sub: string) => sub === 'background_removal' ? [] : ON_DISK[sub] ?? [])+ expect(await comfyThreeDReady()).toBe(false)+ })++ it('is false when a folder\'s loader is not registered (older ComfyUI)', async () => {+ folderRead.mockImplementation(async (sub: string) => sub === 'background_removal' ? null : ON_DISK[sub] ?? [])+ expect(await comfyThreeDReady()).toBe(false)+ })++ it('is false when ComfyUI cannot be asked', async () => {+ folderRead.mockRejectedValue(new Error('down'))+ expect(await comfyThreeDReady()).toBe(false)+ })++ it('finds a file ComfyUI lists in a subfolder', async () => {+ folderRead.mockImplementation(async (sub: string) =>+ sub === 'diffusion_models' ? [`3d\\${TRELLIS2_FILES.model}`] : ON_DISK[sub] ?? [])+ expect(await comfyThreeDReady()).toBe(true)+ })+})++describe('the progress line', () => {+ it('names the phases of plan 1.8 and never goes back', () => {+ const p = createThreeDProgress(graph, true)+ const lines: string[] = []+ const pct: number[] = []+ for (const id of ['122', '193', '192', '312', '299', '3', '241', '12', '186', '147', '260', THREE_D_SAVE_NODE]) {+ const r = p.executing(id)+ lines.push(r.line)+ pct.push(r.percent)+ }+ expect(lines[0]).toBe('Getting the model ready…')+ expect(lines).toContain('Cutting out your object…')+ expect(lines).toContain('Building the shape…')+ expect(lines).toContain('Painting the surface…')+ expect(lines.at(-1)).toBe('Saving your model…')+ // Remesh (shape) after the texture sampler (paint) keeps the paint line.+ expect(lines[8]).toBe('Painting the surface…')+ for (let i = 1; i < pct.length; i++) expect(pct[i]).toBeGreaterThanOrEqual(pct[i - 1])+ expect(Math.max(...pct)).toBeLessThan(100)+ })++ it('moves inside a sampler', () => {+ const p = createThreeDProgress(graph, true)+ const a = p.executing('18').percent+ const b = p.step(10, 20).percent+ expect(b).toBeGreaterThanOrEqual(a)+ })++ it('without a cutout the crop is part of getting ready', () => {+ expect(threeDPhaseForNode('312', false)).toBe('load')+ expect(threeDPhaseForNode('312', true)).toBe('cutout')+ })+})++describe('threeDOutputFromHistory', () => {+ it('takes the GLB of the save node', () => {+ expect(threeDOutputFromHistory(success)).toEqual(GLB)+ })+ it('is null without a mesh file', () => {+ expect(threeDOutputFromHistory({ outputs: { '1': { images: [{ filename: 'x.png', type: 'temp' }] } } })).toBeNull()+ expect(threeDOutputFromHistory(null)).toBeNull()+ })+})++describe('runComfyThreeD', () => {+ it('queues the graph and hands back the GLB when ComfyUI says it is done', async () => {+ getHistory.mockResolvedValue(success)+ const lines: string[] = []+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'standard', cutout: true, seed: 7, onProgress: (l) => lines.push(l) })+ await vi.waitFor(() => expect(wsListeners.length).toBe(1))+ wsListeners[0]({ type: 'executing', data: { node: '3', prompt_id: 'p1' } })+ wsListeners[0]({ type: 'executing', data: { node: '3', prompt_id: 'someone-else' } })+ wsListeners[0]({ type: 'execution_success', data: { prompt_id: 'p1' } })+ await expect(run).resolves.toEqual(GLB)+ expect(buildLocalThreeDWorkflow).toHaveBeenCalledWith({ image: 'chair.png', detail: 'standard', cutout: true, seed: 7 })+ expect(submitWorkflow).toHaveBeenCalledWith(graph, 'lu-test')+ expect(lines).toContain('Building the shape…')+ expect(lines.at(-1)).toBe('Saving your model…')+ expect(wsListeners.length).toBe(0)+ })++ it('reports ComfyUI\'s own error', async () => {+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'draft', cutout: false })+ await vi.waitFor(() => expect(wsListeners.length).toBe(1))+ wsListeners[0]({ type: 'execution_error', data: { prompt_id: 'p1', exception_message: 'CUDA out of memory', node_type: 'KSampler' } })+ await expect(run).rejects.toThrow('CUDA out of memory (KSampler)')+ })++ it('a cancel takes only this prompt out of ComfyUI', async () => {+ const ctl = new AbortController()+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'draft', cutout: true, signal: ctl.signal })+ await vi.waitFor(() => expect(wsListeners.length).toBe(1))+ ctl.abort()+ await expect(run).rejects.toMatchObject({ name: 'AbortError' })+ expect(abandonPrompt).toHaveBeenCalledWith('p1')+ })++ it('a cancel before the submit queues nothing', async () => {+ const ctl = new AbortController()+ ctl.abort()+ await expect(runComfyThreeD({ imageName: 'chair.png', detail: 'draft', cutout: true, signal: ctl.signal }))+ .rejects.toMatchObject({ name: 'AbortError' })+ expect(submitWorkflow).not.toHaveBeenCalled()+ })++ it('finishes from the history poll when there is no socket', async () => {+ vi.useFakeTimers()+ wsConnect.mockRejectedValue(new Error('no ws'))+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'fine', cutout: true })+ await vi.advanceTimersByTimeAsync(0)+ getHistory.mockResolvedValue(success)+ await vi.advanceTimersByTimeAsync(10_000)+ await expect(run).resolves.toEqual(GLB)+ })++ it('says so when a finished run left no model', async () => {+ getHistory.mockResolvedValue({ status: { status_str: 'success', completed: true }, outputs: {} })+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'fine', cutout: true })+ await vi.waitFor(() => expect(wsListeners.length).toBe(1))+ wsListeners[0]({ type: 'executing', data: { node: null, prompt_id: 'p1' } })+ await expect(run).rejects.toThrow(/no 3D model came out/)+ })++ it('gives up on a prompt ComfyUI no longer has', async () => {+ vi.useFakeTimers()+ promptQueueState.mockResolvedValue('gone')+ const run = runComfyThreeD({ imageName: 'chair.png', detail: 'fine', cutout: true })+ const done = expect(run).rejects.toThrow(/no longer has this 3D run/)+ await vi.advanceTimersByTimeAsync(20_000)+ await done+ })+})diff --git a/src/lib/__tests__/render-safety.test.ts b/src/lib/__tests__/render-safety.test.tsindex a462a4cf..fcb7c504 100644--- a/src/lib/__tests__/render-safety.test.ts+++ b/src/lib/__tests__/render-safety.test.ts@@ -146,7 +146,14 @@ describe('both render paths gate the same fields', () => {// The local path also counts Motion Control's optional field (intents.ts// intentTakesOptionalPrompt), which shows on the local lanes only.expect(local).toMatch(/const typedPrompt = intentTakesPrompt\([^\n]+\)\n\s+\|\| intentTakesOptionalPrompt\(state\.intent\(\), 'local'\)\n\s+\? state\.prompt\n\s+: ''/)- expect(cloud).toMatch(/const prompt = intentTakesPrompt\(intent, characterUse\) \? s\.prompt : ''/)+ expect(cloud).toMatch(/const prompt = intentTakesPrompt\(intent, characterUse, s\.threeDWay\) \? s\.prompt : ''/)+ })++ it('3D also gates where its pictures came from, on both paths (C3D 2.8)', () => {+ expect(local).toMatch(/const provenance = state\.intent\(\) === '3d' \? threeDProvenance\(state\) : ''/)+ expect(local).toMatch(/\$\{provenance\}`/)+ expect(cloud).toMatch(/const provenance = intent === '3d' && s\.threeDWay !== 'text' \? threeDProvenance\(s\) : ''/)+ expect(cloud).toContain('if (provenance) params.source_prompt = provenance')})/** The negative prompt is handed over apart since B30 (safety.ts): the@@ -163,7 +170,7 @@ describe('both render paths gate the same fields', () => {it('the cloud path reads the same fields, each only when its run sends it (B30-Rest)', () => {// Bare names there: the lyrics of a classic music run, the trigger word of// a training run, the negative prompt where the classic knobs go out.- expect(cloud).toMatch(/clientSafety\(`\$\{prompt\} \$\{lyrics\} \$\{triggerWord\}`, sendsClassicKnobs \? s\.negativePrompt : ''\)/)+ expect(cloud).toMatch(/clientSafety\(`\$\{prompt\} \$\{lyrics\} \$\{triggerWord\} \$\{provenance\}`, sendsClassicKnobs \? s\.negativePrompt : ''\)/)expect(cloud).toMatch(/const lyrics = op === 'music' && !studioModel \? s\.musicLyrics : ''/)expect(cloud).toMatch(/const triggerWord = op === 'lora-train' \? s\.triggerWord : ''/)})diff --git a/src/lib/create/bridge/cloud-jobs.ts b/src/lib/create/bridge/cloud-jobs.tsindex 61e4ff02..3a378394 100644--- a/src/lib/create/bridge/cloud-jobs.ts+++ b/src/lib/create/bridge/cloud-jobs.ts@@ -15,6 +15,7 @@ export { listLoras } from '../../../api/cloud/loras'/** Which queue kind and op a subcategory renders as. 'video_upscale' is its* own subcategory on the web; the queue knows it as an upscale of kind video. */export function intentToJob(intent: StudioIntent): { kind: RenderKind; op: RenderOp } {+ if (intent === '3d-text' || intent === '3d-image' || intent === '3d-video') return desktopIntentToJob('3d')return intent === 'video_upscale' ? { kind: 'video', op: 'upscale' } : desktopIntentToJob(intent)}diff --git a/src/lib/create/bridge/create-store.ts b/src/lib/create/bridge/create-store.tsindex 0475890a..6bcf1ee2 100644--- a/src/lib/create/bridge/create-store.ts+++ b/src/lib/create/bridge/create-store.ts@@ -1,4 +1,7 @@// The Create subcategories as the web app names them. The web keeps// 'video_upscale' as its own intent; on the desktop the Create tab reaches it// from the gallery, and the type that carries all thirteen is StudioIntent.-export type { StudioIntent as CreateIntent } from '../../render/create-studio'+import type { StudioIntent } from '../../render/create-studio'+// The three ways of the 3D tab are studio intents of the Create tab only:+// chat does not make 3D models (lib/create/order.ts chatKind).+export type CreateIntent = Exclude<StudioIntent, '3d-text' | '3d-image' | '3d-video'>diff --git a/src/lib/local-3d-comfy.ts b/src/lib/local-3d-comfy.tsnew file mode 100644index 00000000..83051015--- /dev/null+++ b/src/lib/local-3d-comfy.ts@@ -0,0 +1,270 @@+// Local 3D on Windows and Linux (3.1.0): one picture in, one GLB out, through+// the TRELLIS.2 core nodes of the pinned ComfyUI (v0.42.4). The Mac has no+// ComfyUI and runs its own engine (api/mlx-3d.ts).+//+// Two calls for Create:+// comfyThreeDReady() are all five files of the bundle in ComfyUI's lists+// runComfyThreeD() queue the graph, follow it, hand back the saved file+//+// The graph is buildThreeDWorkflow (api/dynamic-workflow.ts), where its source+// is written down. The phase words are the Mac's (lib/mac-3d.ts), so both+// platforms say the same thing at the same point.++import {+ COMFY_MODEL_FOLDERS, abandonPrompt, extractComfyOutputFiles, getHistory, promptQueueState, submitWorkflow,+ type ComfyUIOutput,+} from '../api/comfyui'+import { CLIENT_ID, comfyWS, type ComfyWSEvent } from '../api/comfyui-ws'+import {+ THREE_D_SAVE_NODE, buildLocalThreeDWorkflow, type ThreeDDetail,+} from '../api/dynamic-workflow'+import { getThreeDBundles } from '../api/model-bundles'+import type { ComfyApiGraph, ComfyHistoryEntry } from '../types/comfy-graph'+import { MESH3D_PHASE_TEXT, type Mesh3dPhase } from './mac-3d'+import { resolveRunSeed } from './run-seed'++export type { ThreeDDetail } from '../api/dynamic-workflow'++const MESH_EXT = /\.(glb|gltf|obj|ply|stl)$/i++function baseName(name: string): string {+ return (name.split(/[\\/]/).pop() ?? name).toLowerCase()+}++/**+ * Whether ComfyUI lists every file of the 3D bundle, each in the folder the+ * bundle puts it in. False when ComfyUI cannot be asked, or when a folder's+ * loader is not registered (a ComfyUI older than the lane), so the setup card+ * shows instead of a run that fails on its first node.+ */+export async function comfyThreeDReady(): Promise<boolean> {+ const [bundle] = getThreeDBundles()+ if (!bundle) return false+ const wanted = bundle.files.filter((f) => f.filename && f.subfolder)+ const folders = [...new Set(wanted.map((f) => f.subfolder!))]+ try {+ const lists = await Promise.all(folders.map(async (sub) => {+ const entry = COMFY_MODEL_FOLDERS.find((f) => f.subfolder === sub)+ const names = entry ? await entry.read() : null+ return [sub, names ? new Set(names.map(baseName)) : null] as const+ }))+ const bySub = new Map(lists)+ return wanted.every((f) => bySub.get(f.subfolder!)?.has(f.filename!.toLowerCase()) ?? false)+ } catch {+ return false+ }+}++export interface RunComfyThreeDOptions {+ /** The picture, already uploaded to ComfyUI's input folder (ImageRef.filename). */+ imageName: string+ detail: ThreeDDetail+ cutout: boolean+ seed?: number+ signal?: AbortSignal+ onProgress?: (line: string, percent?: number) => void+}++/** The phase a node of the 3D graph belongs to, by the graph's node id (the+ * template's ids, see buildThreeDWorkflow). Ids not named here are loaders+ * and model patches, which belong to getting the model ready. */+const PHASE_BY_NODE: Record<string, Mesh3dPhase> = {+ '193': 'cutout', '192': 'cutout', '312': 'cutout',+ '299': 'shape', '87': 'shape', '3': 'shape', '119': 'shape', '91': 'shape', '18': 'shape',+ '94': 'shape', '23': 'shape', '92': 'shape', '241': 'shape', '186': 'shape', '238': 'shape',+ '98': 'paint', '12': 'paint', '93': 'paint', '196': 'paint', '147': 'paint', '224': 'paint',+ '233': 'paint', '210': 'paint',+ '260': 'save', [THREE_D_SAVE_NODE]: 'save',+}+const PHASE_ORDER: Mesh3dPhase[] = ['load', 'cutout', 'shape', 'paint', 'save']++/** The phase of one node. Without a cutout the crop is part of getting ready. */+export function threeDPhaseForNode(nodeId: string, cutout: boolean): Mesh3dPhase {+ const phase = PHASE_BY_NODE[nodeId] ?? 'load'+ return phase === 'cutout' && !cutout ? 'load' : phase+}++/** Follows one run: which nodes are done, which one runs and how far its+ * sampler is. The line only moves forward, because ComfyUI does not run the+ * graph in the order a person reads it. Pure, so it is under test. */+export function createThreeDProgress(graph: ComfyApiGraph, cutout: boolean) {+ const total = Math.max(1, Object.keys(graph).length)+ const done = new Set<string>()+ let current: string | null = null+ let fraction = 0+ let phase: Mesh3dPhase = 'load'+ let percent = 0+ const advance = (p: Mesh3dPhase) => {+ if (PHASE_ORDER.indexOf(p) > PHASE_ORDER.indexOf(phase)) phase = p+ }+ const report = () => {+ const raw = Math.round((100 * (done.size + fraction)) / total)+ percent = Math.min(99, Math.max(percent, raw))+ return { line: MESH3D_PHASE_TEXT[phase], percent }+ }+ return {+ executing(node: string | null) {+ if (current) done.add(current)+ current = node && node in graph ? node : null+ fraction = 0+ if (current) advance(threeDPhaseForNode(current, cutout))+ return report()+ },+ cached(nodes: string[]) {+ for (const n of nodes) if (n in graph) done.add(n)+ return report()+ },+ step(value: number, max: number) {+ fraction = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0+ return report()+ },+ get phase() { return phase },+ }+}++/** The saved model in a finished run's history: the save node's file first,+ * any mesh file of any node after it. Null when there is none. */+export function threeDOutputFromHistory(history: ComfyHistoryEntry | null): ComfyUIOutput | null {+ const outputs = history?.outputs ?? {}+ const ids = [THREE_D_SAVE_NODE, ...Object.keys(outputs).filter((k) => k !== THREE_D_SAVE_NODE)]+ for (const id of ids) {+ const file = extractComfyOutputFiles(outputs[id]).find((f) => MESH_EXT.test(f.filename))+ if (file) return file+ }+ return null+}++function historyError(history: ComfyHistoryEntry): string {+ const messages = Array.isArray(history.status?.messages) ? history.status!.messages! : []+ const err = messages.find(([t]) => t === 'execution_error')?.[1]+ const msg = typeof err?.exception_message === 'string' ? err.exception_message.trim() : ''+ const node = typeof err?.node_type === 'string' ? ` (${err.node_type})` : ''+ return msg ? msg + node : 'ComfyUI stopped the 3D run with an error.'+}++function cancelled(): Error {+ const e = new Error('Cancelled')+ e.name = 'AbortError'+ return e+}++const NO_MODEL = 'The run finished, but no 3D model came out of it. The ComfyUI log says why.'+const POLL_MS = 10_000++/**+ * Queue the 3D graph for one uploaded picture and wait for its GLB.+ *+ * Progress comes over ComfyUI's socket; the history is polled every ten+ * seconds as well, so a missed completion or a socket that never came up+ * still ends the run. Cancel takes this prompt out of ComfyUI's queue (or+ * interrupts it when it is the one running) and nothing else.+ */+export async function runComfyThreeD(opts: RunComfyThreeDOptions): Promise<ComfyUIOutput> {+ const { signal, onProgress } = opts+ if (signal?.aborted) throw cancelled()+ onProgress?.(MESH3D_PHASE_TEXT.load, 0)+ const graph = await buildLocalThreeDWorkflow({+ image: opts.imageName,+ detail: opts.detail,+ cutout: opts.cutout,+ seed: resolveRunSeed(opts.seed ?? -1),+ })+ if (signal?.aborted) throw cancelled()++ let useWS = false+ let mark = 0+ try {+ await comfyWS.connect(3000)+ useWS = true+ mark = comfyWS.mark()+ } catch { /* the history poll below carries the run alone */ }++ const promptId = await submitWorkflow(graph, CLIENT_ID)+ const progress = createThreeDProgress(graph, opts.cutout)++ return await new Promise<ComfyUIOutput>((resolve, reject) => {+ let settled = false+ let gone = 0+ let off: (() => void) | null = null+ let poll: ReturnType<typeof setInterval> | null = null++ const finish = (fn: () => void) => {+ if (settled) return+ settled = true+ off?.()+ if (poll) clearInterval(poll)+ signal?.removeEventListener('abort', onAbort)+ fn()+ }+ const fail = (message: string) => finish(() => reject(new Error(message)))+ const fromHistory = (history: ComfyHistoryEntry | null): boolean => {+ if (!history) return false+ const status = history.status?.status_str+ if (status === 'error') { fail(historyError(history)); return true }+ if (status !== 'success' && history.status?.completed !== true) return false+ const file = threeDOutputFromHistory(history)+ if (!file) { fail(NO_MODEL); return true }+ onProgress?.(MESH3D_PHASE_TEXT.save, 100)+ finish(() => resolve(file))+ return true+ }+ function onAbort() {+ void abandonPrompt(promptId)+ finish(() => reject(cancelled()))+ }+ signal?.addEventListener('abort', onAbort)++ if (useWS) {+ off = comfyWS.on((event: ComfyWSEvent) => {+ if (settled) return+ if ('prompt_id' in event.data && event.data.prompt_id !== promptId) return+ // ComfyUI says "finished" as execution_success (the desktop's socket+ // proxy may name it execution_complete) and as an `executing` with no+ // node. Any of the three looks into the history.+ const checkHistory = () => { void getHistory(promptId).then((h) => { if (!settled) fromHistory(h) }) }+ if ((event as { type: string }).type === 'execution_success') { checkHistory(); return }+ switch (event.type) {+ case 'executing': {+ const r = progress.executing(event.data.node)+ onProgress?.(r.line, r.percent)+ if (event.data.node === null) checkHistory()+ break+ }+ case 'execution_cached': {+ const r = progress.cached(event.data.nodes ?? [])+ onProgress?.(r.line, r.percent)+ break+ }+ case 'progress': {+ const r = progress.step(event.data.value, event.data.max)+ onProgress?.(r.line, r.percent)+ break+ }+ case 'execution_complete':+ checkHistory()+ break+ case 'execution_error': {+ const msg = (event.data.exception_message || 'ComfyUI stopped the 3D run with an error.').trim()+ fail(msg + (event.data.node_type ? ` (${event.data.node_type})` : ''))+ break+ }+ }+ }, mark)+ }++ poll = setInterval(() => {+ if (settled) return+ void (async () => {+ if (fromHistory(await getHistory(promptId))) return+ // Not in the history and not in the queue: ComfyUI dropped it (a+ // restart, a cleared queue). Twice in a row, so a run that is just+ // moving from the queue into the history is not called lost.+ const state = await promptQueueState(promptId).catch(() => 'unknown' as const)+ gone = state === 'gone' ? gone + 1 : 0+ if (gone >= 2 && !fromHistory(await getHistory(promptId))) {+ fail('ComfyUI no longer has this 3D run. It may have restarted. Try again.')+ }+ })()+ }, POLL_MS)+ })+}diff --git a/src/lib/render/create-studio.ts b/src/lib/render/create-studio.tsindex a1427cdf..46cbd56b 100644--- a/src/lib/render/create-studio.ts+++ b/src/lib/render/create-studio.ts@@ -30,7 +30,14 @@ import { intentToJob, type CreateIntentLike } from './cloud-jobs'// crystal-upscaler, flux-3-upscale) is correctly wired and tested, but// reachable only by calling these functions directly with 'video_upscale',// which no UI path does today.-export type StudioIntent = CreateIntentLike | 'video_upscale'+export type StudioIntent = CreateIntentLike | 'video_upscale' | '3d-text' | '3d-image' | '3d-video'++/** The studio intent of the tab on screen. The 3D tab runs another set of+ * models per way (words, one picture, the frames of a video), so it is+ * three studio intents; every other tab is its own. */+export function studioIntentOf(intent: CreateIntentLike, threeDWay?: 'text' | 'image' | 'video'): StudioIntent {+ return intent === '3d' ? `3d-${threeDWay ?? 'image'}` : intent+}/** Die Rolle, die eine Create-Unterkategorie faehrt. Absichten ohne Eintrag* (Bild, Video, Animate, Edit) haben ihre eigenen, aelteren Waehler. */@@ -42,6 +49,12 @@ const INTENT_ROLE: Partial<Record<StudioIntent, StepRole[]>> = {extend: ['extend'],motion: ['motion'],video_upscale: ['upscale'],+ // 3D: a video sends its frames to a model that takes several sides first,+ // and to a one-picture model with its best frame where none is there.+ '3d-text': ['mesh-text'],+ '3d-image': ['mesh-image', 'mesh-views'],+ '3d-video': ['mesh-views', 'mesh-image'],+ '3d': ['mesh-image', 'mesh-views', 'mesh-text'],}export function intentRoles(intent: StudioIntent): StepRole[] {diff --git a/src/lib/render/local-model-tier.ts b/src/lib/render/local-model-tier.tsindex 0f884189..ad038be3 100644--- a/src/lib/render/local-model-tier.ts+++ b/src/lib/render/local-model-tier.ts@@ -20,6 +20,7 @@ const BEST = new Set(['ltx25', 'minimaxh3', // Video mit Ton'qwenimage', 'zimage', 'flux2', 'krea2', 'ernie_image', // Bild'yue2', // Musik+ 'trellis2', // 3D (Windows und Linux, api/model-bundles getThreeDBundles)])/** Von einer neueren Familie abgeloest. Nicht versteckt, nur nach unten gesammelt. */diff --git a/src/lib/render/preset-models.ts b/src/lib/render/preset-models.tsindex b22ce1eb..dade8a5b 100644--- a/src/lib/render/preset-models.ts+++ b/src/lib/render/preset-models.ts@@ -21,6 +21,8 @@ export type StepRole =| 'duo' | 'extend' | 'motion' | 'restyle' | 'angles' | 'edit' | 'upscale'// 02.10.2026: Text zu Video, Referenz zu Video.| 'video' | 'reference'+ // 3.1.0: 3D from words, from one picture, from several sides.+ | 'mesh-text' | 'mesh-image' | 'mesh-views'export interface PresetModel {id: string@@ -43,6 +45,7 @@ const ROLE_OP: Record<StepRole, RenderOp> = {extend: 'extend', motion: 'motion', restyle: 'studio', angles: 'studio',edit: 'edit', upscale: 'upscale',video: 'generate', reference: 'studio',+ 'mesh-text': 'studio', 'mesh-image': 'studio', 'mesh-views': 'studio',}/** The staged inputs a NON-studio member consumes, as provider field -> job@@ -56,6 +59,7 @@ export const ROLE_INPUTS: Record<StepRole, Record<string, string>> = {edit: { image: 'source_path' },upscale: { video: 'video_path' },video: {}, reference: {},+ 'mesh-text': {}, 'mesh-image': { image: 'source_path' }, 'mesh-views': { images: 'image_paths' },}function studioIds(match: (id: string) => boolean): string[] {@@ -117,6 +121,11 @@ const ROLE_MEMBERS: Record<StepRole, () => string[]> = {edit: () => [...STUDIO_EDIT_MODELS, 'qwen-image-edit'],// A finished clip goes in, the same clip at more pixels comes out.upscale: () => ['video-upscaler', 'flashvsr', 'video-upscaler-pro', 'ultimate-video-upscaler', 'crystal-upscaler', 'flux-3-upscale'],+ // 3D (3.1.0): every studio model of kind '3d', sorted by what it reads.+ // Nothing: words. One picture: source_path. A list: several sides.+ 'mesh-text': () => studioIds((id) => STUDIO_MODELS[id].kind === '3d' && !Object.keys(STUDIO_MODELS[id].inputs).length),+ 'mesh-image': () => studioIds((id) => STUDIO_MODELS[id].kind === '3d' && Object.values(STUDIO_MODELS[id].inputs).includes('source_path')),+ 'mesh-views': () => studioIds((id) => STUDIO_MODELS[id].kind === '3d' && Object.values(STUDIO_MODELS[id].inputs).includes('image_paths')),}/** Classic ids that a studio entry already covers on the same endpoint. The@@ -308,6 +317,7 @@ const CLASSIC_PROMPT: Record<StepRole, boolean> = {video: true, reference: true,talking: false, presenter: false, motion: false, soundtrack: false, duo: false,angles: false, upscale: false,+ 'mesh-text': true, 'mesh-image': false, 'mesh-views': false,}export function rolePrompts(role: StepRole): boolean {diff --git a/src/lib/render/studio-contract.ts b/src/lib/render/studio-contract.tsindex 31ebf0b6..20572a28 100644--- a/src/lib/render/studio-contract.ts+++ b/src/lib/render/studio-contract.ts@@ -11,7 +11,9 @@ export type ModelTier = 'best' | 'standard' | 'older'export type ModelWeights = 'open' | 'open-family' | 'closed'export interface StudioModel {baselineUsd: number; sourceModel?: string; promptField?: string- label: string; endpoint: string; kind: 'image' | 'video' | 'audio'; adult: boolean+ label: string; endpoint: string; kind: 'image' | 'video' | 'audio' | '3d'; adult: boolean+ /** The usual run time in seconds (3D, shown while the cloud builds). */+ typical_s?: numbertier: ModelTier; weights: ModelWeightsinputs: Record<string, string>; defaults: Record<string, unknown>// `resolutionField` / `durationField`: nicht jeder Endpunkt nennt die beidendiff --git a/src/lib/starter-bundle.ts b/src/lib/starter-bundle.tsindex 7712fb3c..3da92353 100644--- a/src/lib/starter-bundle.ts+++ b/src/lib/starter-bundle.ts@@ -2,9 +2,9 @@ import { bundleForVideoIntent } from '../api/comfyui'import {getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles,} from '../api/discover'-import type { ModelBundle } from '../api/model-bundles'+import { getThreeDBundles, type ModelBundle } from '../api/model-bundles'-export type StarterKind = 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale'+export type StarterKind = 'image' | 'video' | 'audio' | 'lipsync' | 'motion' | 'upscale' | '3d'/*** The bundle the Create setup card installs for a lane. One place, because@@ -22,6 +22,8 @@ export function starterBundleFor(kind: StarterKind, intent: string): ModelBundle: kind === 'audio' ? getAudioBundles(): kind === 'lipsync' ? getLipsyncBundles(): kind === 'upscale' ? getUpscaleBundles()+ // 3D on Windows and Linux: TRELLIS.2 and its cutout model (api/model-bundles).+ : kind === '3d' ? getThreeDBundles(): getMotionBundles())[0]}diff --git a/src/lib/three/__tests__/three-d-logic.test.ts b/src/lib/three/__tests__/three-d-logic.test.tsnew file mode 100644index 00000000..f35be3d3--- /dev/null+++ b/src/lib/three/__tests__/three-d-logic.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { checkPromptSafety } from '../../render/safety'+import { threeDProvenance, threeDPicturePrompt, threeDGalleryItem, MAC_DETAIL_RESOLUTION } from '../run-local-3d'+import { studioIntentOf, intentRoles } from '../../render/create-studio'+import { intentToJob, quotaCostKind } from '../../render/cloud-jobs'+import { evenPick } from '../../../components/create/experimental/ThreeDControls'+import { useCreateStore, opSlot } from '../../../stores/createStore'+import { galleryLabel } from '../../render/gallery-label'+import { writePoster, readPoster, deletePoster, onPoster, __resetPostersForTests } from '../mesh-poster'++const ref = (name: string, url = `data:image/png;base64,${name}`) => ({ filename: '', url, width: 1, height: 1, name })++describe('3D content gate reads where the pictures came from', () => {+ it('names every picture: the front and every side', () => {+ const text = threeDProvenance({ source: ref('teapot.png'), threeDViews: [ref('left.png'), ref('back.png')], gallery: [] })+ expect(text).toContain('teapot.png')+ expect(text).toContain('left.png')+ expect(text).toContain('back.png')+ })+ it('a gallery picture brings its prompt, and a blocked prompt there blocks the run', () => {+ const url = 'data:image/png;base64,abc'+ const gallery = [{ prompt: 'nude schoolgirl', promptOriginal: '', label: '', dataUrl: url }]+ const text = threeDProvenance({ source: ref('x.png', url), threeDViews: [], gallery })+ expect(checkPromptSafety(` ${text}`).blocked).toBe(true)+ })+ it('a harmless picture passes', () => {+ const text = threeDProvenance({ source: ref('clay-teapot.jpg'), threeDViews: [], gallery: [] })+ expect(checkPromptSafety(text).blocked).toBe(false)+ })+ it('a file name alone can block', () => {+ const text = threeDProvenance({ source: ref('loli-nude.png'), threeDViews: [], gallery: [] })+ expect(checkPromptSafety(text).blocked).toBe(true)+ })+})++describe('3D studio intents', () => {+ it('each way runs its own roles', () => {+ expect(studioIntentOf('3d', 'text')).toBe('3d-text')+ expect(studioIntentOf('3d', 'image')).toBe('3d-image')+ expect(studioIntentOf('3d', 'video')).toBe('3d-video')+ expect(studioIntentOf('music', 'video')).toBe('music')+ expect(intentRoles('3d-text')).toEqual(['mesh-text'])+ expect(intentRoles('3d-video')[0]).toBe('mesh-views')+ })+ it('cloud 3D is a studio run of kind 3d', () => {+ expect(intentToJob('3d')).toEqual({ kind: '3d', op: 'studio' })+ expect(quotaCostKind('3d')).toBe('image')+ expect(quotaCostKind('video')).toBe('video')+ })+})++describe('3D helpers', () => {+ it('spreads the picked moments over the video', () => {+ expect(evenPick(8, 4)).toEqual([0, 2, 4, 5])+ expect(evenPick(8, 1)).toEqual([3])+ expect(evenPick(2, 4)).toEqual([0, 1])+ expect(evenPick(0, 4)).toEqual([])+ })+ it('steers the picture of "From text" to one whole object', () => {+ expect(threeDPicturePrompt('a clay teapot.')).toMatch(/^a clay teapot, a single object/)+ })+ it('names a gallery entry by its way when it has no prompt', () => {+ const item = threeDGalleryItem({ id: 'a', way: 'image', model: 'TripoSR', prompt: '', seed: 1, localPath: '/x.glb' })+ expect(item.type).toBe('3d')+ expect(galleryLabel(item)).toBe('3D from image')+ const named = threeDGalleryItem({ id: 'b', way: 'text', model: 'TripoSR', prompt: 'a robot', seed: 1 })+ expect(galleryLabel(named)).toBe('a robot')+ })+ it('the detail steps map onto growing grids', () => {+ expect(MAC_DETAIL_RESOLUTION.draft).toBeLessThan(MAC_DETAIL_RESOLUTION.standard)+ expect(MAC_DETAIL_RESOLUTION.standard).toBeLessThan(MAC_DETAIL_RESOLUTION.fine)+ })+})++describe('3D in the store', () => {+ beforeEach(() => {+ useCreateStore.setState({ threeDWay: 'image', threeDViews: [], cloudStudioOptions: {} })+ })+ it('a new way drops the sides and the studio options of the old one', () => {+ const s = useCreateStore.getState()+ s.setThreeDViews([ref('l'), ref('b'), ref('r'), ref('x'), ref('y')])+ expect(useCreateStore.getState().threeDViews).toHaveLength(4)+ useCreateStore.setState({ cloudStudioOptions: { resolution: '1536' } })+ s.setIntent('3d')+ s.setThreeDWay('video')+ expect(useCreateStore.getState().threeDViews).toEqual([])+ })+ it('each way is its own pick slot', () => {+ const s = useCreateStore.getState()+ s.setIntent('3d')+ expect(opSlot({ ...useCreateStore.getState(), threeDWay: 'text' })).toBe('3d:text')+ expect(opSlot({ ...useCreateStore.getState(), threeDWay: 'image' })).toBe('3d:image')+ })+ it('the 3D tab keeps the picture on the Stage', () => {+ const s = useCreateStore.getState()+ s.setIntent('image')+ s.setSource(ref('teapot'))+ s.setIntent('3d')+ expect(useCreateStore.getState().source?.name).toBe('teapot')+ expect(useCreateStore.getState().intent()).toBe('3d')+ })+})++describe('3D posters', () => {+ beforeEach(() => __resetPostersForTests())+ it('keeps a still per entry and tells the tiles', async () => {+ const heard: string[] = []+ onPoster((id) => heard.push(id))+ await writePoster('a', 'data:image/jpeg;base64,AAAA')+ expect(await readPoster('a')).toBe('data:image/jpeg;base64,AAAA')+ expect(heard).toEqual(['a'])+ await deletePoster('a')+ expect(await readPoster('a')).toBeNull()+ })+ it('takes only pictures', async () => {+ await writePoster('b', 'javascript:alert(1)')+ expect(await readPoster('b')).toBeNull()+ })+})diff --git a/src/lib/three/mesh-load.ts b/src/lib/three/mesh-load.tsindex d57ec8ed..bc87b1d3 100644--- a/src/lib/three/mesh-load.ts+++ b/src/lib/three/mesh-load.ts@@ -20,9 +20,11 @@ export interface LoadedMesh {}export class MeshLoadError extends Error {- constructor(message: string, readonly reason: 'not-glb' | 'compressed' | 'broken') {+ readonly reason: 'not-glb' | 'compressed' | 'broken'+ constructor(message: string, reason: 'not-glb' | 'compressed' | 'broken') {super(message)this.name = 'MeshLoadError'+ this.reason = reason}}diff --git a/src/lib/three/mesh-poster.ts b/src/lib/three/mesh-poster.tsnew file mode 100644index 00000000..8a9c89e1--- /dev/null+++ b/src/lib/three/mesh-poster.ts@@ -0,0 +1,89 @@+// The still on a 3D model's gallery tile (C3D-PLAN 1.7). The 3D view draws it+// from its own canvas the first time it shows a model, and it is kept here+// per device, under the id of the gallery entry. A small database of its own:+// a poster that cannot be written must never count as a failed write of the+// app's stores (idbStorage reports those to the user).+//+// Without IndexedDB (tests, a locked-down webview) the stills live in memory+// for the session, and the tile shows the cube until one is drawn.++const DB = 'lu-3d-posters'+const STORE = 'posters'+const memory = new Map<string, string>()+const listeners = new Set<(id: string) => void>()++function open(): Promise<IDBDatabase | null> {+ if (typeof indexedDB === 'undefined') return Promise.resolve(null)+ return new Promise((resolve) => {+ try {+ const req = indexedDB.open(DB, 1)+ req.onupgradeneeded = () => req.result.createObjectStore(STORE)+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => resolve(null)+ } catch {+ resolve(null)+ }+ })+}++let dbPromise: Promise<IDBDatabase | null> | null = null+const db = () => (dbPromise ??= open())++/** The still of an entry, or null when none was drawn yet. */+export async function readPoster(id: string): Promise<string | null> {+ const hit = memory.get(id)+ if (hit) return hit+ const d = await db()+ if (!d) return null+ return new Promise((resolve) => {+ try {+ const req = d.transaction(STORE, 'readonly').objectStore(STORE).get(id)+ req.onsuccess = () => {+ const v = typeof req.result === 'string' ? req.result : null+ if (v) memory.set(id, v)+ resolve(v)+ }+ req.onerror = () => resolve(null)+ } catch {+ resolve(null)+ }+ })+}++/** Keep the still of an entry. Only JPEG and PNG data URLs are taken. */+export async function writePoster(id: string, dataUrl: string): Promise<void> {+ if (!/^data:image\/(jpeg|png);base64,/.test(dataUrl) || dataUrl.length > 400_000) return+ memory.set(id, dataUrl)+ for (const fn of listeners) fn(id)+ const d = await db()+ if (!d) return+ try {+ d.transaction(STORE, 'readwrite').objectStore(STORE).put(dataUrl, id)+ } catch {+ // The memory copy stays for this session.+ }+}++/** Drop the still of a deleted entry. */+export async function deletePoster(id: string): Promise<void> {+ memory.delete(id)+ const d = await db()+ if (!d) return+ try {+ d.transaction(STORE, 'readwrite').objectStore(STORE).delete(id)+ } catch {+ // Nothing to do: a leftover still is never shown without its entry.+ }+}++/** Called with the id whenever a still is written. */+export function onPoster(fn: (id: string) => void): () => void {+ listeners.add(fn)+ return () => listeners.delete(fn)+}++export function __resetPostersForTests(): void {+ memory.clear()+ listeners.clear()+ dbPromise = null+}diff --git a/src/lib/three/run-local-3d.ts b/src/lib/three/run-local-3d.tsnew file mode 100644index 00000000..d01853ed--- /dev/null+++ b/src/lib/three/run-local-3d.ts@@ -0,0 +1,60 @@+// The local 3D run (C3D-PLAN 2.3, 2.4): one picture in, one GLB out.+//+// On a Mac the picture goes to LU's own TripoSR engine (api/mlx-3d.ts, a+// process of its own per run). On Windows and Linux it goes to ComfyUI's+// TRELLIS.2 core nodes (lib/local-3d-comfy.ts). Both are called with a+// picture that is already on the Stage: "From text" painted it first, "From+// video" took it from a still frame.+//+// The content gate has run before this is called (useCreate runOnce), on the+// prompt and on where every picture came from (threeDProvenance).+import type { GalleryItem, ImageRef, ThreeDDetail, ThreeDWay } from '../../stores/createStore'+import { THREE_D_TEXT } from './three-d-text'++export const MAC_3D_MODEL = 'TripoSR'+export const PC_3D_MODEL = 'TRELLIS.2'++/** The words that steer the picture of a two-step "From text" towards what an+ * image-to-3D model reads best: one object, whole, on a plain ground. */+export function threeDPicturePrompt(prompt: string): string {+ const p = prompt.trim().replace(/[.,;\s]+$/, '')+ return `${p}, a single object, whole and centered, plain light background, soft studio light, three-quarter view`+}++/** The text the content gate reads besides the prompt: the names of every+ * picture the run takes, and what the gallery knows about where they came+ * from. A picture of the gallery carries its prompt, a file its name. */+export function threeDProvenance(s: { source: ImageRef | null; threeDViews: ImageRef[]; gallery: Pick<GalleryItem, 'prompt' | 'promptOriginal' | 'label' | 'dataUrl' | 'remoteUrl'>[] }): string {+ const pics = [s.source, ...s.threeDViews].filter((p): p is ImageRef => !!p)+ const out: string[] = []+ for (const p of pics) {+ if (p.name) out.push(p.name)+ if (p.filename) out.push(p.filename)+ const from = s.gallery.find((g) => (g.dataUrl && g.dataUrl === p.url) || (g.remoteUrl && g.remoteUrl === p.url))+ if (from) out.push(from.prompt ?? '', from.promptOriginal ?? '', from.label ?? '')+ }+ return out.filter(Boolean).join(' ')+}++/** The gallery entry of a finished local model. */+export function threeDGalleryItem(args: {+ id: string; way: ThreeDWay; model: string; prompt: string; seed: number+ localPath?: string; dataUrl?: string; filename?: string; subfolder?: string; comfyType?: string; sourceName?: string+}): GalleryItem {+ return {+ id: args.id, type: '3d',+ filename: args.filename ?? '', subfolder: args.subfolder ?? '', comfyType: args.comfyType,+ localPath: args.localPath, dataUrl: args.dataUrl,+ prompt: args.prompt, negativePrompt: '',+ label: args.prompt ? undefined : THREE_D_TEXT.gallery[args.way],+ sourceName: args.sourceName,+ model: args.model, modelType: 'unknown', toolModel: args.model,+ seed: args.seed, steps: 0, cfgScale: 0, sampler: '', scheduler: '',+ width: 0, height: 0, batchSize: 1,+ createdAt: Date.now(), builderUsed: 'dynamic', intent: '3d',+ }+}++/** The marching-cubes grid of TripoSR per detail step. 256 is the engine's+ * own default (run.py `--mc-resolution`). */+export const MAC_DETAIL_RESOLUTION: Record<ThreeDDetail, number> = { draft: 192, standard: 256, fine: 320 }diff --git a/src/lib/three/three-d-models.ts b/src/lib/three/three-d-models.tsnew file mode 100644index 00000000..9ed8f73a--- /dev/null+++ b/src/lib/three/three-d-models.ts@@ -0,0 +1,65 @@+// What the 3D row of the Composer offers for the model that will run+// (C3D-PLAN 1.2, 2.5). Local: one picture, a detail step, LU's own cutout.+// Cloud: a studio model says in its own entry how many pictures it takes+// (`images -> image_paths` with the schema's maxItems) and which field its+// detail step moves; the provider cuts out the object itself.+import type { CreateBackend, ThreeDDetail } from '../../stores/createStore'+import { STUDIO_MODELS, studioSchema } from '../render/studio-contract'++export interface ThreeDControlFacts {+ maxViews: number+ hasDetail: boolean+ hasCutout: boolean+}++/** At most four sides: Front, Left, Back, Right. */+const MAX_SIDES = 4++export function threeDMaxViews(studioId: string | undefined): number {+ const m = studioId ? STUDIO_MODELS[studioId] : undefined+ if (!m) return 1+ const field = Object.entries(m.inputs).find(([, role]) => role === 'image_paths')?.[0]+ if (!field) return 1+ let max = MAX_SIDES+ try {+ max = studioSchema(studioId!).properties?.[field]?.maxItems ?? MAX_SIDES+ } catch {+ // An entry without a schema takes the four sides the tab draws.+ }+ return Math.max(1, Math.min(MAX_SIDES, max))+}++/** The field of a cloud 3D model that its Detail step moves, with the value+ * of each step. Read from the schema's choices: the first, middle and last+ * value of the field the price runs over. */+export function threeDDetailField(studioId: string | undefined): { field: string; values: Record<ThreeDDetail, unknown> } | null {+ const m = studioId ? STUDIO_MODELS[studioId] : undefined+ if (!m) return null+ const field = m.price.resolutionField ?? (m.price.rates && Object.keys(m.price.rates).length > 1 ? 'resolution' : undefined)+ if (!field) return null+ let choices: unknown[] | undefined+ try {+ choices = studioSchema(studioId!).properties?.[field]?.enum+ } catch {+ return null+ }+ if (!choices || choices.length < 2) return null+ const mid = choices[Math.floor((choices.length - 1) / 2)]+ return { field, values: { draft: choices[0], standard: mid, fine: choices[choices.length - 1] } }+}++/** Which step a cloud model's field stands on: its value, else the schema's+ * default, else Standard. */+export function cloudDetailOf(f: { field: string; values: Record<ThreeDDetail, unknown> }, value: unknown, studioId: string | undefined): ThreeDDetail {+ let v = value+ if (v === undefined && studioId) {+ try { v = studioSchema(studioId).properties?.[f.field]?.default } catch { v = undefined }+ }+ const hit = (Object.keys(f.values) as ThreeDDetail[]).find((d) => f.values[d] === v)+ return hit ?? 'standard'+}++export function threeDControlFacts(backend: CreateBackend, studioId: string | undefined): ThreeDControlFacts {+ if (backend === 'local') return { maxViews: 1, hasDetail: true, hasCutout: true }+ return { maxViews: threeDMaxViews(studioId), hasDetail: !!threeDDetailField(studioId), hasCutout: false }+}diff --git a/src/lib/three/three-d-text.ts b/src/lib/three/three-d-text.tsnew file mode 100644index 00000000..0dd544a4--- /dev/null+++ b/src/lib/three/three-d-text.ts@@ -0,0 +1,45 @@+// Every sentence of the 3D tab (C3D-PLAN 1.8), in one place for the desktop+// and the phone. English, short, plain, no closing phrase.+import type { ThreeDDetail, ThreeDWay } from '../../stores/createStore'++export const THREE_D_TEXT = {+ ways: { text: 'From text', image: 'From image', video: 'From video' } as Record<ThreeDWay, string>,+ waysShort: { text: 'Text', image: 'Image', video: 'Video' } as Record<ThreeDWay, string>,+ prompt: 'Describe one object. A worn leather armchair, a tiny robot, a clay teapot…',+ examples: ['a worn leather armchair', 'a small friendly robot, toy style', 'a clay teapot with a bamboo handle'],+ pictureFirst: 'LU paints a picture first, then builds the model from it.',+ pictureFirstSwitch: 'Picture first',+ afterPicture: 'Here is your picture',+ makeIt3d: 'Make it 3D',+ newPicture: 'New picture',+ dropImage: 'Drop a picture of one object',+ dropImageSub: 'One thing, fully in frame. LU cuts it out for you.',+ moreSides: 'Add more sides',+ sides: ['Front', 'Left', 'Back', 'Right'],+ moreSidesSub: 'One picture is enough. More sides give a truer shape.',+ dropVideo: 'Drop a short video of one object',+ dropVideoSub: 'Walk around it once, slowly. 5 to 20 seconds is plenty.',+ framesMany: 'LU picked four moments from your video. Swap any of them.',+ framesOne: 'Pick the moment that shows it best.',+ framesReading: 'Reading your video…',+ videoHonest: 'LU builds the model from still frames of your video.',+ cutout: 'Cut out the background',+ detail: 'Detail',+ details: { draft: 'Draft', standard: 'Standard', fine: 'Fine' } as Record<ThreeDDetail, string>,+ phases: {+ ready: 'Getting the model ready…',+ cutout: 'Cutting out your object…',+ shape: 'Building the shape…',+ paint: 'Painting the surface…',+ save: 'Saving your model…',+ },+ cloudPhase: 'Building your model in the cloud…',+ cloudPhaseSub: 'This takes about a minute. You can keep working, it lands in your gallery.',+ noObject: 'LU could not find a clear object in this picture. Try one with a plain background.',+ needImageModel: 'Local 3D from text needs an image model first. Get one in the Model Manager, or start from a picture.',+ needSource: 'Add a picture of one object first.',+ needVideo: 'Add a short video of the object first.',+ filtered: 'Filtered by provider',+ filteredTip: 'The company that runs this model checks prompts and pictures. LU cannot switch that off.',+ gallery: { text: '3D model', image: '3D from image', video: '3D from video' } as Record<ThreeDWay, string>,+}diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex fd4373bd..8e94bcd8 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -70,7 +70,7 @@ import { mlxMakesMusic } from '../lib/mac-music'import { MAC_EDIT_DEAD_SIDE, MAC_EDIT_SIDE_INSTEAD, imageLaneModels, mlxTakesEditImage } from '../lib/image-engines'import { STUDIO_MODELS } from '../lib/render/studio-contract'import { cloudModelsFor } from './cloudCatalogStore'-import { createRunModel } from '../lib/render/create-studio'+import { createRunModel, studioIntentOf } from '../lib/render/create-studio'import { DEFAULT_UPSCALE_FACTOR, normalizeUpscaleFactor, normalizeUpscaleLongSide, type UpscaleFactor } from '../lib/local-upscale'import { characterLoraFile, isLocalCharacter, type CharacterRef } from '../lib/character-ref'import { triggerWordNote, typedTriggerWord } from '../lib/train-trigger'@@ -126,7 +126,8 @@ export type ThreeDDetail = 'draft' | 'standard' | 'fine'// Character joined in 2.6.0: trainer.rs ships the musubi venv install, so// the train lane is a real local tab now (it was cloud-first while 2.5.8// had no trainer runtime).-export const LOCAL_LANE_OPS: ReadonlySet<CloudOp> = new Set(['music', 'lipsync', 'extend', 'motion', 'character'])+// 3D joined in 3.1.0: TRELLIS.2 on the core nodes of the pinned ComfyUI.+export const LOCAL_LANE_OPS: ReadonlySet<CloudOp> = new Set(['music', 'lipsync', 'extend', 'motion', 'character', '3d'])/** An audio/video file (or training image) staged in the composer before* upload. `blob` carries the bytes for the cloud upload; `url` is a local@@ -165,10 +166,10 @@ export function deriveIntent(s: {/** The model the tab in this state would run in the cloud. */function runModelOf(s: Parameters<typeof deriveIntent>[0] & Pick<CreateState,- 'cloudImageModel' | 'cloudVideoModel' | 'cloudOpModel' | 'characterTab' | 'selectedCharacter'>): string {+ 'cloudImageModel' | 'cloudVideoModel' | 'cloudOpModel' | 'characterTab' | 'selectedCharacter'> & Partial<Pick<CreateState, 'threeDWay'>>): string {const intent = deriveIntent(s)return createRunModel(- intent,+ studioIntentOf(intent, s.threeDWay),{ image: s.cloudImageModel, video: s.cloudVideoModel, op: s.cloudOpModel },intent === 'character' && s.characterTab === 'use' ? s.selectedCharacter?.family ?? '' : undefined,)@@ -976,7 +977,7 @@ export function distilledImageCheckpoint(model: string, type: ModelType): boolea* Image, Edit and the other image intents only flipped the mode, so sd_turbo* rendered with MiniMax H3's 20 steps, res_multistep and 1344x768 (3.0.4* Gegenprobe 9). */-function imageModelParams(state: { imageModel: string; imageModelType: ModelType }) {+export function imageModelParams(state: { imageModel: string; imageModelType: ModelType }) {const defaults = state.imageModelType === 'hidream'? hidreamDefaults(state.imageModel): MODEL_TYPE_DEFAULTS[state.imageModelType] || MODEL_TYPE_DEFAULTS.unknown@@ -1737,6 +1738,9 @@ export const useCreateStore = create<CreateState>()(// uses a character through mflux and trains one with mflux-train.|| (get().cloudOp === 'lipsync' && mlxTalking(get().videoModelList).tab)|| get().cloudOp === 'character'+ // 3D (3.1.0) is always a local tab on a Mac: its Stage offers the+ // engine's one-time setup when it is not there.+ || get().cloudOp === '3d'const strandsOnMac = backend === 'local' && isMlxImageHost() && !!get().cloudOp && !keepsExtend && !macRunsOpconst heldMode = get().modeset((s) => withOwnStudioOptions(s, ((): Partial<CreateState> => {