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): TripoSR engine for 3D on the Mac
purple2d381ab03df6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c442a72f..5d8f6723 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -643,7 +643,7 @@ jobs:with:python-version: '3.12'- - name: Engine pins still resolve (pip install --dry-run, four engines)+ - name: Engine pins still resolve (pip install --dry-run, five engines)shell: bashtimeout-minutes: 20env:diff --git a/dev-server/mlx-media-stubs.ts b/dev-server/mlx-media-stubs.tsindex cc3f5abc..1d55ac16 100644--- a/dev-server/mlx-media-stubs.ts+++ b/dev-server/mlx-media-stubs.ts@@ -83,6 +83,14 @@ export function registerMlxMediaStubs(routes: RouteMount): void {'/local-api/mlx-music-generate','/local-api/mlx-music-progress','/local-api/mlx-music-cancel',+ '/local-api/mlx-mesh3d-status',+ '/local-api/mlx-mesh3d-install',+ '/local-api/mlx-mesh3d-install-status',+ '/local-api/mlx-mesh3d-cancel-install',+ '/local-api/mlx-mesh3d-delete',+ '/local-api/mlx-mesh3d-generate',+ '/local-api/mlx-mesh3d-progress',+ '/local-api/mlx-mesh3d-cancel','/local-api/mlx-train-status','/local-api/mlx-train-stage','/local-api/mlx-train-clear',diff --git a/scripts/mac-engine-pins.d.mts b/scripts/mac-engine-pins.d.mtsindex 61cbda7e..dca1971a 100644--- a/scripts/mac-engine-pins.d.mts+++ b/scripts/mac-engine-pins.d.mts@@ -2,7 +2,7 @@* implementation stays .mjs and the types live here. */export interface EnginePins {- id: 'image' | 'mflux' | 'mlx-video' | 'ltx-2-mlx'+ id: 'image' | 'mflux' | 'mlx-video' | 'ltx-2-mlx' | 'mesh3d'label: stringsource: stringspecs: string[]diff --git a/scripts/mac-engine-pins.mjs b/scripts/mac-engine-pins.mjsindex d1fba698..9ea6b004 100644--- a/scripts/mac-engine-pins.mjs+++ b/scripts/mac-engine-pins.mjs@@ -1,17 +1,17 @@#!/usr/bin/env node-// mac-engine-pins.mjs: what the four Mac media engines hand to pip, read from+// mac-engine-pins.mjs: what the Mac media engines hand to pip, read from// the place the app itself reads it from.//// WHY THIS EXISTS// ----------------// The four engines are not part of the .app. A customer's Mac resolves their+// The engines are not part of the .app. A customer's Mac resolves their// packages from PyPI and GitHub the first time a model is installed, so a// yanked release or a wheel that is missing for arm64 shows up there and// nowhere else. `macos-gate` in ci.yml asks pip the same question ahead of// time (scripts/mac-engine-pins-dry-run.sh, `pip install --dry-run`).//-// The lists are NOT copied into this file. Three of them are Rust constants,-// the fourth is a requirements file, and a copy would be out of date the day+// The lists are NOT copied into this file. Four of them are Rust constants,+// one is a requirements file, and a copy would be out of date the day// somebody moves a pin. This file parses the sources and refuses to answer// when a source no longer has the shape it reads: a declared array length// that does not match, a constant that is gone, an entry that is neither@@ -23,9 +23,12 @@// mflux src-tauri/src/commands/image_mflux.rs PINNED// mlx-video src-tauri/src/commands/video.rs MLX_VIDEO_PINNED, MLX_VIDEO_PIP_SPEC// ltx-2-mlx src-tauri/src/commands/video_ltx2mlx.rs PINNED, PACKAGES, SOURCE, COMMIT+// mesh3d src-tauri/src/commands/mesh3d.rs PINNED (the TripoSR source is+// not a pip package: Rust fetches+// it by sha256, so pip never sees it)//// Usage:-// node scripts/mac-engine-pins.mjs # print the four lists+// node scripts/mac-engine-pins.mjs # print the lists// node scripts/mac-engine-pins.mjs --json # the same as JSON// node scripts/mac-engine-pins.mjs --write <dir> # one <engine>.txt per engine, for `pip -r`//@@ -43,6 +46,7 @@ export const SOURCES = {mflux: 'src-tauri/src/commands/image_mflux.rs','mlx-video': 'src-tauri/src/commands/video.rs','ltx-2-mlx': 'src-tauri/src/commands/video_ltx2mlx.rs',+ mesh3d: 'src-tauri/src/commands/mesh3d.rs',}/** The Python line the app's own interpreter is on, e.g. "3.12". */@@ -125,7 +129,7 @@ function ltxSpecs(source) {}/**- * The four lists. `read` takes a path relative to the repository and returns+ * The five lists. `read` takes a path relative to the repository and returns* the file's text; the default reads the working tree.*/export function readEnginePins(read = (rel) => readFileSync(join(REPO_ROOT, rel), 'utf8')) {@@ -154,6 +158,7 @@ export function readEnginePins(read = (rel) => readFileSync(join(REPO_ROOT, rel)rustStrConst(src, 'MLX_VIDEO_PIP_SPEC'),])add('ltx-2-mlx', 'second video engine (ltx-2-mlx)', ltxSpecs)+ add('mesh3d', '3D engine (TripoSR)', (src) => rustStrArray(src, 'PINNED'))return engines}diff --git a/src-tauri/resources/mesh3d/__pycache__/run_triposr.cpython-312.pyc b/src-tauri/resources/mesh3d/__pycache__/run_triposr.cpython-312.pycnew file mode 100644index 00000000..4be705e3Binary files /dev/null and b/src-tauri/resources/mesh3d/__pycache__/run_triposr.cpython-312.pyc differdiff --git a/src-tauri/resources/mesh3d/__pycache__/test_run_triposr.cpython-312.pyc b/src-tauri/resources/mesh3d/__pycache__/test_run_triposr.cpython-312.pycnew file mode 100644index 00000000..307b9ee2Binary files /dev/null and b/src-tauri/resources/mesh3d/__pycache__/test_run_triposr.cpython-312.pyc differdiff --git a/src-tauri/resources/mesh3d/run_triposr.py b/src-tauri/resources/mesh3d/run_triposr.pynew file mode 100644index 00000000..94079a22--- /dev/null+++ b/src-tauri/resources/mesh3d/run_triposr.py@@ -0,0 +1,337 @@+"""LU's own runner of TripoSR: one picture in, one GLB with vertex colours out.++The app starts this once per model (`src-tauri/src/commands/mesh3d.rs`) with+`python -I -u run_triposr.py --lu-mesh3d-job <job.json>` and reads what it says+on stdout: lines that begin with `LU-MESH3D `, each a JSON object with a+`phase` (load, shape, paint, save, done, error, note) and, for shape, a+`fraction` from 0 to 1.++What it changes against `run.py` of TripoSR, and why (read at the pinned+commit, see mesh3d.rs):++1. `torchmcubes` comes as a `git+https` requirement and has to be compiled,+ which a customer's Mac cannot do. `tsr/models/isosurface.py` imports it at+ module level, so a stand-in module is put in its place that runs+ `skimage.measure.marching_cubes`. The surface itself is extracted below+ with scikit-image directly, so the progress can be told.+2. `rembg` is imported at module level by `tsr/utils.py` and downloads a model+ of its own on first use. LU cuts the object out with Apple's Vision before+ this runs, so a stand-in is put in its place that refuses to work.+3. The DINO image encoder reads its `config.json` from the hub at start+ (`tsr/models/tokenizers/image.py`). The app downloads that file at a fixed+ revision during the install; the hub call is pointed at that file here,+ and the whole run is offline (`HF_HUB_OFFLINE=1`).+4. No texture baking (`moderngl`, `xatlas`): colours per vertex, written as+ GLB by trimesh.++The weights are read with `torch.load(..., weights_only=True)`: a checkpoint+that holds anything but tensors is refused instead of run.++`--lu-mesh3d-selftest <out.glb>` runs the same surface, colour and GLB code on+a small sphere without the model, and imports TripoSR with the stand-ins. The+install uses it to prove the venv.+"""++import json+import os+import shutil+import sys+import time+import traceback+import types++PREFIX = "LU-MESH3D "+JOB_FLAG = "--lu-mesh3d-job"+SELFTEST_FLAG = "--lu-mesh3d-selftest"++DINO_REPO = "facebook/dino-vitb16"++# The points of the grid that go to the device in one go. The renderer splits+# each of these again into pieces of `chunk` points.+POINTS_PER_STEP = 1 << 18+++def say(**fields):+ print(PREFIX + json.dumps(fields), flush=True)+++# ── Stand-ins for what a Mac cannot install ─────────────────────────────+++def marching_cubes_numpy(volume, level=0.0):+ """Vertices in the index order of `volume` (axis 0, 1, 2) and triangles.++ `volume` is positive inside the object. The triangles face outwards: the+ signed volume of the mesh is made positive, whatever winding scikit-image+ chose, since the axis order of TripoSR flips handedness once.+ """+ import numpy as np+ from skimage import measure++ vol = np.ascontiguousarray(volume, dtype=np.float32)+ if not (vol.max() > level and vol.min() < level):+ return np.zeros((0, 3), dtype=np.float32), np.zeros((0, 3), dtype=np.int64)+ verts, faces, _normals, _values = measure.marching_cubes(vol, level=level)+ verts = verts.astype(np.float32)+ faces = faces.astype(np.int64)+ if signed_volume(verts, faces) < 0:+ faces = faces[:, ::-1].copy()+ return verts, faces+++def signed_volume(verts, faces):+ import numpy as np++ if len(faces) == 0:+ return 0.0+ a, b, c = verts[faces[:, 0]], verts[faces[:, 1]], verts[faces[:, 2]]+ return float(np.einsum("ij,ij->i", a, np.cross(b, c)).sum() / 6.0)+++def install_stand_ins():+ """Put `torchmcubes` and `rembg` into `sys.modules` before TripoSR loads."""++ def torchmcubes_marching_cubes(volume, threshold):+ # The order torchmcubes answers in: x along the last axis. TripoSR+ # turns it back with `v_pos[..., [2, 1, 0]]`.+ import torch++ verts, faces = marching_cubes_numpy(volume.detach().cpu().numpy(), threshold)+ return torch.from_numpy(verts[:, ::-1].copy()), torch.from_numpy(faces)++ mc = types.ModuleType("torchmcubes")+ mc.marching_cubes = torchmcubes_marching_cubes+ sys.modules["torchmcubes"] = mc++ def no_rembg(*_args, **_kwargs):+ raise RuntimeError("LU cuts the object out with Vision before the run; rembg is not used")++ rembg = types.ModuleType("rembg")+ rembg.remove = no_rembg+ rembg.new_session = no_rembg+ sys.modules["rembg"] = rembg+++def import_tsr(source, dino_config):+ """TripoSR from the pinned source, with the encoder config read from disk."""+ if source not in sys.path:+ sys.path.insert(0, source)+ install_stand_ins()+ import tsr.models.tokenizers.image as tokenizer++ def local_config(repo_id, filename, **_kwargs):+ if repo_id == DINO_REPO and filename == "config.json":+ return dino_config+ raise RuntimeError(f"the run is offline and has no {repo_id}/{filename}")++ tokenizer.hf_hub_download = local_config+ from tsr.system import TSR+ from tsr.utils import resize_foreground, scale_tensor++ return TSR, resize_foreground, scale_tensor+++# ── The picture ─────────────────────────────────────────────────────────+++def prepare_image(path, foreground_ratio, resize_foreground):+ """The picture as TripoSR takes it: RGB, object centred on grey.++ A picture with transparent pixels (the cutout) is cropped to the object,+ padded to `foreground_ratio` and laid on 50 percent grey, as `run.py`+ does after rembg. A picture without transparency is taken as it is.+ """+ import numpy as np+ from PIL import Image, ImageOps++ image = ImageOps.exif_transpose(Image.open(path))+ if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):+ rgba = image.convert("RGBA")+ alpha = np.asarray(rgba)[..., 3]+ if not (alpha > 0).any():+ raise ValueError("no object")+ if (alpha < 255).any():+ rgba = resize_foreground(rgba, foreground_ratio)+ pixels = np.asarray(rgba).astype(np.float32) / 255.0+ rgb = pixels[:, :, :3] * pixels[:, :, 3:4] + (1 - pixels[:, :, 3:4]) * 0.5+ return Image.fromarray((rgb * 255.0).astype(np.uint8))+ return image.convert("RGB")+++# ── The surface and the colours ─────────────────────────────────────────+++def to_gltf_orientation(mesh):+ """Upright in glTF's Y-up frame, with the side the photo shows towards +Z,+ where a glTF viewer's camera stands. TripoSR's own demo turns it upright+ the same way (`to_gradio_3d_orientation` in `tsr/utils.py`) but leaves+ the photographed side at -Z; seen on the first real run (13.11.2026), so+ the turn about Y here is the other way round."""+ import numpy as np+ import trimesh++ mesh.apply_transform(trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]))+ mesh.apply_transform(trimesh.transformations.rotation_matrix(-np.pi / 2, [0, 1, 0]))+ return mesh+++def write_glb(verts, faces, colors, work, output):+ """Write the mesh as GLB in the job folder, then move it into place."""+ import numpy as np+ import trimesh++ rgba = np.concatenate(+ [np.clip(colors, 0.0, 1.0) * 255.0, np.full((len(colors), 1), 255.0)], axis=1+ ).astype(np.uint8)+ mesh = trimesh.Trimesh(vertices=verts, faces=faces, vertex_colors=rgba, process=False)+ mesh = to_gltf_orientation(mesh)+ part = os.path.join(work, "model.glb")+ mesh.export(part, file_type="glb")+ os.makedirs(os.path.dirname(output), exist_ok=True)+ shutil.move(part, output)+ return len(mesh.faces), len(mesh.vertices)+++def pick_device(asked):+ import torch++ if asked == "cpu":+ return "cpu"+ if torch.backends.mps.is_available():+ return "mps"+ return "cpu"+++def run(job):+ import numpy as np+ import torch+ from omegaconf import OmegaConf++ started = time.time()+ say(phase="load")+ TSR, resize_foreground, scale_tensor = import_tsr(job["source"], job["dino_config"])+ cfg = OmegaConf.load(job["config"])+ OmegaConf.resolve(cfg)+ model = TSR(cfg)+ state = torch.load(job["weights"], map_location="cpu", weights_only=True)+ model.load_state_dict(state)+ del state+ model.renderer.set_chunk_size(int(job["chunk"]))+ device = pick_device(job.get("device", "auto"))+ model.to(device)+ model.eval()+ say(phase="note", note=f"device {device}", device=device)++ try:+ image = prepare_image(job["image"], float(job["foreground_ratio"]), resize_foreground)+ except ValueError:+ say(phase="error", error="no object", code="no_object")+ sys.exit(6)++ say(phase="shape", fraction=0.0)+ with torch.no_grad():+ try:+ scene_codes = model([image], device=device)+ except RuntimeError as e:+ if device == "cpu":+ raise+ # An operation MPS cannot run even with the fallback: once more on+ # the CPU, which is slower and always there.+ say(phase="note", note="the graphics chip could not run the model, using the CPU: " + str(e)[:200], device="cpu")+ device = "cpu"+ model.to(device)+ scene_codes = model([image], device=device)+ scene_code = scene_codes[0]+ say(phase="shape", fraction=0.1)++ resolution = int(job["resolution"])+ radius = float(model.renderer.cfg.radius)+ axis = torch.linspace(0.0, 1.0, resolution)+ grid = torch.stack(torch.meshgrid(axis, axis, axis, indexing="ij"), dim=-1).reshape(-1, 3)+ points = scale_tensor(grid, (0.0, 1.0), (-radius, radius))+ del grid+ density = torch.empty(points.shape[0], dtype=torch.float32)+ total = points.shape[0]+ told = 0.1+ for start in range(0, total, POINTS_PER_STEP):+ end = min(total, start + POINTS_PER_STEP)+ out = model.renderer.query_triplane(model.decoder, points[start:end].to(device), scene_code)+ density[start:end] = out["density_act"].reshape(-1).float().cpu()+ fraction = 0.1 + 0.8 * end / total+ if fraction - told >= 0.02 or end == total:+ told = fraction+ say(phase="shape", fraction=round(fraction, 3))+ del points++ level = (density - float(job["threshold"])).reshape(resolution, resolution, resolution).numpy()+ del density+ verts, faces = marching_cubes_numpy(level, 0.0)+ del level+ if len(faces) == 0:+ say(phase="error", error="no object", code="no_object")+ sys.exit(6)+ verts = verts / (resolution - 1.0) * (2.0 * radius) - radius+ say(phase="shape", fraction=1.0)++ say(phase="paint")+ colors = []+ positions = torch.from_numpy(verts.astype(np.float32))+ for start in range(0, positions.shape[0], POINTS_PER_STEP):+ out = model.renderer.query_triplane(model.decoder, positions[start:start + POINTS_PER_STEP].to(device), scene_code)+ colors.append(out["color"].float().cpu().numpy())+ colors = np.concatenate(colors, axis=0)++ say(phase="save")+ triangles, vertices = write_glb(verts, faces, colors, job["work"], job["output"])+ say(+ phase="done",+ output=job["output"],+ triangles=int(triangles),+ vertices=int(vertices),+ device=device,+ seconds=round(time.time() - started, 1),+ )+++def selftest(out):+ """The surface, colour and GLB path on a sphere, without the model."""+ import numpy as np++ n = 32+ axis = np.linspace(-1.0, 1.0, n, dtype=np.float32)+ x, y, z = np.meshgrid(axis, axis, axis, indexing="ij")+ level = 0.6 - np.sqrt(x * x + y * y + z * z)+ verts, faces = marching_cubes_numpy(level, 0.0)+ assert len(faces) > 100, "the sphere has no surface"+ assert signed_volume(verts, faces) > 0, "the triangles face inwards"+ verts = verts / (n - 1.0) * 2.0 - 1.0+ colors = (verts + 1.0) / 2.0+ work = os.path.dirname(os.path.abspath(out))+ triangles, vertices = write_glb(verts, faces, colors, work, out)+ with open(out, "rb") as f:+ assert f.read(4) == b"glTF", "not a GLB"+ say(phase="selftest", triangles=int(triangles), vertices=int(vertices))+++def main(argv):+ if SELFTEST_FLAG in argv:+ out = argv[argv.index(SELFTEST_FLAG) + 1]+ selftest(out)+ if "--source" in argv:+ import_tsr(argv[argv.index("--source") + 1], "unused")+ say(phase="selftest", imported="tsr.system")+ return+ with open(argv[argv.index(JOB_FLAG) + 1], encoding="utf-8") as f:+ job = json.load(f)+ try:+ run(job)+ except SystemExit:+ raise+ except BaseException as e:+ traceback.print_exc()+ say(phase="error", error=(type(e).__name__ + ": " + str(e))[-600:])+ sys.exit(5)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/src-tauri/resources/mesh3d/test_run_triposr.py b/src-tauri/resources/mesh3d/test_run_triposr.pynew file mode 100644index 00000000..74284569--- /dev/null+++ b/src-tauri/resources/mesh3d/test_run_triposr.py@@ -0,0 +1,126 @@+"""Tests of LU's TripoSR runner on a small grid, without the model.++Run with the engine's venv (it has numpy, scikit-image, trimesh, Pillow):++ <data_dir>/mesh3d/venv/bin/python -I -m unittest discover -s src-tauri/resources/mesh3d -p 'test_*.py'++`-I` keeps the folder of the test out of the import path, so the runner is+loaded by its file path below and nothing else from this folder is.+"""++import importlib.util+import json+import os+import struct+import tempfile+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+spec = importlib.util.spec_from_file_location("run_triposr", os.path.join(HERE, "run_triposr.py"))+runner = importlib.util.module_from_spec(spec)+spec.loader.exec_module(runner)+++def read_glb_json(path):+ with open(path, "rb") as f:+ data = f.read()+ magic, _version, length = struct.unpack_from("<4sII", data, 0)+ chunk_len, chunk_type = struct.unpack_from("<I4s", data, 12)+ assert magic == b"glTF" and length == len(data) and chunk_type == b"JSON"+ return json.loads(data[20:20 + chunk_len])+++class MiniGrid(unittest.TestCase):+ def sphere(self, n=24, r=0.5):+ import numpy as np++ axis = np.linspace(-1.0, 1.0, n, dtype=np.float32)+ x, y, z = np.meshgrid(axis, axis, axis, indexing="ij")+ return r - np.sqrt(x * x + y * y + z * z)++ def test_a_sphere_has_a_closed_surface_that_faces_outwards(self):+ verts, faces = runner.marching_cubes_numpy(self.sphere(), 0.0)+ self.assertGreater(len(faces), 100)+ self.assertGreater(runner.signed_volume(verts, faces), 0)+ # Every vertex is near the radius, in grid units.+ import numpy as np++ centre = (24 - 1) / 2.0+ radius = np.linalg.norm(verts - centre, axis=1) / centre+ self.assertLess(abs(float(radius.mean()) - 0.5), 0.05)++ def test_an_inverted_field_is_still_turned_outwards(self):+ verts, faces = runner.marching_cubes_numpy(-self.sphere(), 0.0)+ # Inside out: the "object" is everything but the ball, its surface+ # still has a winding the runner makes consistent.+ self.assertNotEqual(runner.signed_volume(verts, faces), 0)++ def test_an_empty_field_has_no_surface(self):+ import numpy as np++ verts, faces = runner.marching_cubes_numpy(np.full((8, 8, 8), -1.0), 0.0)+ self.assertEqual((len(verts), len(faces)), (0, 0))++ def test_the_torchmcubes_stand_in_answers_in_its_axis_order(self):+ try:+ import torch+ except ImportError:+ self.skipTest("torch is not in this Python")+ runner.install_stand_ins()+ import sys++ mc = sys.modules["torchmcubes"]+ field = self.sphere()+ field[:, :, :4] = -1.0 # break the symmetry along the last axis+ verts, faces = mc.marching_cubes(torch.from_numpy(field), 0.0)+ ours, _ = runner.marching_cubes_numpy(field, 0.0)+ self.assertTrue(torch.allclose(verts[:, [2, 1, 0]], torch.from_numpy(ours)))+ self.assertEqual(faces.dtype, torch.int64)++ def test_rembg_is_never_used(self):+ runner.install_stand_ins()+ import sys++ with self.assertRaises(RuntimeError):+ sys.modules["rembg"].remove(None)++ def test_the_selftest_writes_a_glb_with_vertex_colours(self):+ with tempfile.TemporaryDirectory() as tmp:+ out = os.path.join(tmp, "sphere.glb")+ runner.selftest(out)+ gltf = read_glb_json(out)+ primitive = gltf["meshes"][0]["primitives"][0]+ self.assertIn("COLOR_0", primitive["attributes"])+ self.assertIn("POSITION", primitive["attributes"])++ def test_a_cutout_is_centred_on_grey_and_a_plain_photo_is_left_alone(self):+ from PIL import Image++ def resize_foreground(image, ratio):+ # The real one comes from TripoSR; this keeps the size.+ return image++ with tempfile.TemporaryDirectory() as tmp:+ cut = Image.new("RGBA", (16, 16), (0, 0, 0, 0))+ for x in range(4, 12):+ for y in range(4, 12):+ cut.putpixel((x, y), (200, 10, 10, 255))+ path = os.path.join(tmp, "cut.png")+ cut.save(path)+ rgb = runner.prepare_image(path, 0.85, resize_foreground)+ self.assertEqual(rgb.mode, "RGB")+ self.assertEqual(rgb.getpixel((0, 0)), (127, 127, 127))+ self.assertEqual(rgb.getpixel((8, 8)), (200, 10, 10))++ empty = os.path.join(tmp, "empty.png")+ Image.new("RGBA", (8, 8), (0, 0, 0, 0)).save(empty)+ with self.assertRaises(ValueError):+ runner.prepare_image(empty, 0.85, resize_foreground)++ photo = os.path.join(tmp, "photo.png")+ Image.new("RGB", (8, 8), (1, 2, 3)).save(photo)+ self.assertEqual(runner.prepare_image(photo, 0.85, resize_foreground).getpixel((0, 0)), (1, 2, 3))+++if __name__ == "__main__":+ unittest.main()diff --git a/src-tauri/src/commands/gallery_files.rs b/src-tauri/src/commands/gallery_files.rsindex d67f4c76..ed874a48 100644--- a/src-tauri/src/commands/gallery_files.rs+++ b/src-tauri/src/commands/gallery_files.rs@@ -15,7 +15,7 @@ use tauri::State;use crate::commands::download::{safe_subfolder, sanitize_filename};use crate::state::AppState;-const MEDIA_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "gif", "mp4", "webm", "mov", "mkv", "wav", "mp3", "flac", "ogg"];+const MEDIA_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "gif", "mp4", "webm", "mov", "mkv", "wav", "mp3", "flac", "ogg", "glb"];#[derive(Debug, Serialize, PartialEq)]#[serde(rename_all = "camelCase")]@@ -99,7 +99,7 @@ pub struct OutputFile {pub filename: String,/// Below the output folder, with "/" between the parts; "" for the folder itself.pub subfolder: String,- /// "image", "video" or "audio".+ /// "image", "video", "audio" or "3d" (a GLB model).pub kind: &'static str,pub modified_ms: u64,pub bytes: u64,@@ -128,6 +128,8 @@ fn kind_of(ext: &str) -> Option<&'static str> {"png" | "jpg" | "jpeg" | "webp" | "gif" => Some("image"),"mp4" | "webm" | "mov" | "mkv" => Some("video"),"wav" | "mp3" | "flac" | "ogg" => Some("audio"),+ // A 3D model as Create writes it (3.1.0). The gallery calls it "3d".+ "glb" => Some("3d"),_ => None,}}@@ -404,6 +406,8 @@ mod tests {std::fs::create_dir_all(out.join("video/deep")).unwrap();std::fs::write(out.join("video/clip.mp4"), b"x").unwrap();std::fs::write(out.join("video/deep/s.wav"), b"x").unwrap();+ std::fs::create_dir_all(out.join("3d")).unwrap();+ std::fs::write(out.join("3d/chair.glb"), b"glTF").unwrap();std::fs::write(out.join("notes.txt"), b"x").unwrap();std::fs::write(out.join("model.safetensors"), b"x").unwrap();std::fs::create_dir_all(out.join(".cache")).unwrap();@@ -412,7 +416,7 @@ mod tests {assert!(!truncated);let mut names: Vec<_> = files.iter().map(|f| format!("{}|{}|{}", f.subfolder, f.filename, f.kind)).collect();names.sort();- assert_eq!(names, vec!["video/deep|s.wav|audio", "video|clip.mp4|video", "|a.png|image"]);+ assert_eq!(names, vec!["3d|chair.glb|3d", "video/deep|s.wav|audio", "video|clip.mp4|video", "|a.png|image"]);let a = files.iter().find(|f| f.filename == "a.png").unwrap();assert_eq!(a.parameters.as_deref(), Some("a cat\nSteps: 20"));assert_eq!((a.width, a.height), (Some(832), Some(1216)));@@ -442,6 +446,7 @@ mod tests {assert_eq!(output_file(&out, "x.png", "../.."), None);assert_eq!(output_file(&out, "x.png", "/etc"), None);assert_eq!(output_file(&out, "model.safetensors", ""), None);+ assert_eq!(output_file(&out, "chair.glb", "3d"), Some(out.join("3d").join("chair.glb")), "a 3D model goes to the Trash too");assert_eq!(output_file(&out, "noext", ""), None);assert_eq!(output_file(&out, "", ""), None);}diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rsindex f8ea2d15..5c712eb0 100644--- a/src-tauri/src/commands/media_cmds.rs+++ b/src-tauri/src/commands/media_cmds.rs@@ -66,6 +66,7 @@ async fn off_main(static IMAGE_LANE: std::sync::Mutex<()> = std::sync::Mutex::new(());static VIDEO_LANE: std::sync::Mutex<()> = std::sync::Mutex::new(());static MUSIC_LANE: std::sync::Mutex<()> = std::sync::Mutex::new(());+static MESH3D_LANE: std::sync::Mutex<()> = std::sync::Mutex::new(());/// Run `work` when no other command holds `lane`.fn in_turn<T>(lane: &std::sync::Mutex<()>, work: impl FnOnce() -> T) -> T {@@ -334,6 +335,50 @@ pub async fn mlx_music_cancel(app: AppHandle, args: Value) -> Result<Value, Strioff_main(app, args, crate::commands::music::music_cancel).await}+// ── 3D on the Mac (TripoSR) ──────────────────────────────────────────────++#[tauri::command]+pub async fn mlx_mesh3d_status(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main(app, args, crate::commands::mesh3d::mesh3d_status).await+}++#[tauri::command]+pub async fn mlx_mesh3d_install(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main_in_turn(app, args, &MESH3D_LANE, crate::commands::mesh3d::mesh3d_install).await+}++#[tauri::command]+pub async fn mlx_mesh3d_install_status(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main(app, args, crate::commands::mesh3d::mesh3d_install_status).await+}++#[tauri::command]+pub async fn mlx_mesh3d_cancel_install(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main(app, args, crate::commands::mesh3d::mesh3d_cancel_install).await+}++#[tauri::command]+pub async fn mlx_mesh3d_delete(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main_in_turn(app, args, &MESH3D_LANE, crate::commands::mesh3d::mesh3d_delete).await+}++/// Async like `mlx_music_generate`: it waits for the image engine to let go+/// of its model before the run starts, with its claim taken before that.+#[tauri::command]+pub async fn mlx_mesh3d_generate(state: State<'_, AppState>, args: Value) -> Result<Value, String> {+ crate::commands::mesh3d::mesh3d_generate(state.inner(), &args).await+}++#[tauri::command]+pub async fn mlx_mesh3d_progress(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main(app, args, crate::commands::mesh3d::mesh3d_progress).await+}++#[tauri::command]+pub async fn mlx_mesh3d_cancel(app: AppHandle, args: Value) -> Result<Value, String> {+ off_main(app, args, crate::commands::mesh3d::mesh3d_cancel).await+}+// ── Character training on the Mac (mflux-train) ─────────────────────────#[tauri::command]@@ -394,6 +439,8 @@ fn allowed_media_roots() -> Vec<PathBuf> {crate::commands::mlx::images_root(),// Tracks of the music lane (commands/music.rs).crate::commands::music::outputs_root(),+ // Models of the 3D lane (commands/mesh3d.rs), read by the viewer.+ crate::commands::mesh3d::outputs_root(),]}diff --git a/src-tauri/src/commands/mesh3d.rs b/src-tauri/src/commands/mesh3d.rsnew file mode 100644index 00000000..2c69e3db--- /dev/null+++ b/src-tauri/src/commands/mesh3d.rs@@ -0,0 +1,1634 @@+//! The local 3D engine of the Mac: TripoSR, one picture in, one GLB out.+//!+//! A Mac has no ComfyUI, so this runs the way the music engine runs+//! (`music.rs`): a venv of its own with every package pinned, the source of+//! the engine at one commit, the weights of the official repository at one+//! revision, and one Python process per model that the app starts, reads and+//! can end. A process that ends gives all its memory back.+//!+//! The process runs LU's own runner (`resources/mesh3d/run_triposr.py`) and+//! not TripoSR's `run.py`. Three things of `run.py` cannot run on a+//! customer's Mac, read at the pinned commit (13.11.2026):+//! - `torchmcubes` is a `git+https` requirement that is compiled on install+//! (`requirements.txt`) and imported by `tsr/models/isosurface.py`. The+//! runner puts a stand-in on scikit-image's marching cubes in its place.+//! - `rembg` is imported by `tsr/utils.py` and downloads a model of its own.+//! The object is cut out before the run with Vision (`mlx_cutout.rs`),+//! and the runner puts a stand-in in place of rembg that refuses to work.+//! - the texture bake needs `moderngl` and `xatlas`. The runner writes+//! colours per vertex instead.+//!+//! The DINO encoder reads `config.json` of `facebook/dino-vitb16` from the hub+//! when it is built (`tsr/models/tokenizers/image.py`, `hf_hub_download`+//! without a revision). The install fetches that one file at a fixed revision+//! and the runner hands it over from disk; a run is offline.+//!+//! Content filter: none. `grep -riE "safety|nsfw|censor|filter|explicit|porn|+//! nude|watermark|blocklist|moderat"` over every `.py` file of the source at+//! `SOURCE_COMMIT` finds nothing, and the only network calls are the two+//! `hf_hub_download` above, neither of which a run makes.+//!+//! Every download goes through `voice_loop::fetch::fetch_verified`: resumable,+//! with the size and the sha256 compiled in here, and a file is kept under its+//! real name only when both match.+//!+//! Where it was read:+//! - the code, MIT: <https://github.com/VAST-AI-Research/TripoSR> at+//! `SOURCE_COMMIT` (head of `main`, 04.06.2026, a README change on top of+//! the last code change of 14.05.2024)+//! - the weights, MIT, not gated: <https://huggingface.co/stabilityai/TripoSR>+//! at `REVISION` (`model.ckpt`, `config.yaml`, sizes and the LFS sha256+//! from the hub's tree listing)+//! - the encoder config, Apache 2.0: <https://huggingface.co/facebook/dino-vitb16>+//! at `DINO_REVISION`++use crate::commands::voice_loop::manifest::RemoteFile;+use crate::commands::{bad_request, internal, not_found, CmdResult};+use crate::install_state::InstallSlot;+use crate::os_error;+use crate::state::AppState;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::atomic::{AtomicBool, Ordering::SeqCst};+use std::sync::Mutex;+use std::time::{Duration, Instant};++// ── The pins ──────────────────────────────────────────────────────────++/// The head of `main` on 13.11.2026. The repository has no releases.+pub(crate) const SOURCE_COMMIT: &str = "107cefdc244c39106fa830359024f6a2f1c78871";+/// The archive of the commit. Only `tsr/` and the licence are kept from it.+const SOURCE: &str = "https://github.com/VAST-AI-Research/TripoSR/archive";+const SOURCE_BYTES: u64 = 31_282_920;+const SOURCE_SHA256: &str = "a7b3871a1b4377bef96cbfb99bdc952bdd4f5df9f65fea4208d978a343fd1162";++/// The official repository of the weights, at its own sha.+pub(crate) const REPO: &str = "stabilityai/TripoSR";+pub(crate) const REVISION: &str = "5b521936b01fbe1890f6f9baed0254ab6351c04a";+const CKPT_BYTES: u64 = 1_677_246_742;+const CKPT_SHA256: &str = "429e2c6b22a0923967459de24d67f05962b235f79cde6b032aa7ed2ffcd970ee";+const CONFIG_BYTES: u64 = 987;+const CONFIG_SHA256: &str = "74ca708ce086bf68e97709ea6b3d91f14717921c04691e84043f0eb8fcc68e62";++/// The one file of the image encoder's repository the model reads.+const DINO_REPO: &str = "facebook/dino-vitb16";+const DINO_REVISION: &str = "f205d5d8e640a89a2b8ef0369670dfc37cc07fc2";+const DINO_CONFIG_BYTES: u64 = 454;+const DINO_CONFIG_SHA256: &str = "b87c0270b97db085fd82cf114a761fd0f62ae7914fbd407c752a2260646b689c";++/// Bytes of the three files of the model.+pub(crate) const WEIGHTS_BYTES: u64 = CKPT_BYTES + CONFIG_BYTES + DINO_CONFIG_BYTES;++/// Every package the runner pulls in, with all they need, resolved by pip+/// for Python 3.12 on Apple Silicon as wheels only (13.11.2026), 34 packages+/// from PyPI. torch, numpy, transformers and what they share stand at the+/// versions of the music engine (`music.rs`), so the wheels are fetched once.+/// `omegaconf` 2.4.0 has no `antlr4` any more, whose 4.9 release is a source+/// archive; `tifffile`, `imageio` and `lazy-loader` stand a few releases+/// back from the newest, which were days old.+const PINNED: [&str; 34] = [+ "certifi==2026.1.4", "charset-normalizer==3.4.4", "einops==0.8.2", "filelock==3.20.3", "fsspec==2026.1.0",+ "hf-xet==1.2.0", "huggingface-hub==0.36.0", "idna==3.11", "imageio==2.37.4", "jinja2==3.1.6",+ "lazy-loader==0.5", "markupsafe==3.0.3", "mpmath==1.3.0", "networkx==3.6.1", "numpy==2.3.5",+ "omegaconf==2.4.0", "packaging==26.0", "pillow==12.1.0", "pyyaml==6.0.3", "regex==2026.1.15",+ "requests==2.32.5", "safetensors==0.7.0", "scikit-image==0.26.0", "scipy==1.17.0", "setuptools==71.1.0",+ "sympy==1.14.0", "tifffile==2026.9.20", "tokenizers==0.22.2", "torch==2.10.0", "tqdm==4.67.1",+ "transformers==4.57.6", "trimesh==5.1.1", "typing-extensions==4.15.0", "urllib3==2.6.3",+];++/// What the install proves it can import before the self test.+const MODULE: &str = "torch, transformers, omegaconf, trimesh, skimage.measure, einops, PIL";++/// What the venv takes on disk, with room for the wheels pip unpacks.+const ENGINE_INSTALL_BYTES: u64 = 1_500_000_000;++/// The one model this engine offers, as the Model Manager and Create name it.+pub(crate) const MODEL_ID: &str = "triposr";+pub(crate) const MODEL_NAME: &str = "TripoSR";++/// Below this a run is refused. The README names about 6 GB of graphics+/// memory, and on a Mac that memory is shared with macOS and the app.+pub(crate) const MIN_RAM_GB: u32 = 16;++/// The grid the surface is taken from, per side. 256 is TripoSR's default.+const DEFAULT_RESOLUTION: u32 = 256;+const MIN_RESOLUTION: u32 = 64;+const MAX_RESOLUTION: u32 = 384;+/// The density the surface is drawn at (`extract_mesh`'s default).+const THRESHOLD: f64 = 25.0;+/// Points per call of the decoder (`run.py`'s default `--chunk-size`).+const CHUNK: u32 = 8192;+/// How much of the picture the object fills (`run.py`'s default).+const FOREGROUND_RATIO: f64 = 0.85;++/// A run that is still going after this long is not going to end.+const GENERATE_TIMEOUT: Duration = Duration::from_secs(30 * 60);+/// A run that has said nothing for this long has hung.+const STALL_AFTER: Duration = Duration::from_secs(5 * 60);++/// LU's runner, compiled in and written next to the engine before a run.+const RUNNER: &str = include_str!("../../resources/mesh3d/run_triposr.py");++// ── Where it lives ────────────────────────────────────────────────────++/// Everything of the engine in one folder under the app's data folder.+fn root() -> PathBuf {+ crate::os_paths::data_dir().join("mesh3d")+}++fn venv_dir(root: &Path) -> PathBuf {+ root.join("venv")+}++fn venv_python(venv: &Path) -> PathBuf {+ venv.join("bin").join("python")+}++/// The `tsr` package of the pinned commit and its licence.+fn source_dir(root: &Path) -> PathBuf {+ root.join("source").join(SOURCE_COMMIT)+}++/// `model.ckpt`, `config.yaml` and the encoder's `dino-vitb16/config.json`.+fn weights_dir(root: &Path) -> PathBuf {+ root.join("weights")+}++/// Where the downloads that are not the weights wait to be unpacked.+fn downloads_dir(root: &Path) -> PathBuf {+ root.join("downloads")+}++fn work_dir(root: &Path) -> PathBuf {+ root.join("work")+}++fn runner_file(root: &Path) -> PathBuf {+ root.join("runner").join("run_triposr.py")+}++fn run_pid_file(root: &Path) -> PathBuf {+ root.join("run.pid")+}++/// Where the models are kept, beside the images, the videos and the tracks.+pub(crate) fn outputs_root() -> PathBuf {+ crate::os_paths::config_root().join("3d")+}++fn ensure_apple_silicon() -> Result<(), String> {+ if cfg!(all(target_os = "macos", target_arch = "aarch64")) {+ Ok(())+ } else {+ Err(bad_request("Local 3D on a Mac needs Apple Silicon. Use the ComfyUI lane on this system."))+ }+}++// ── The engine ────────────────────────────────────────────────────────++fn pip_args() -> Vec<String> {+ ["-m", "pip", "install", "--upgrade", "--only-binary", ":all:", "--disable-pip-version-check"]+ .iter()+ .map(|a| a.to_string())+ .chain(PINNED.iter().map(|p| p.to_string()))+ .collect()+}++fn stamp_file(venv: &Path) -> PathBuf {+ venv.join(".lu-mesh3d-engine")+}++fn stamp() -> String {+ PINNED.join("\n")+}++fn engine_ready_at(venv: &Path) -> bool {+ venv_python(venv).exists() && std::fs::read_to_string(stamp_file(venv)).is_ok_and(|s| s == stamp())+}++fn python_has_module(python: &str, module: &str) -> bool {+ crate::python::python_command(python)+ .args(["-I", "-c", &format!("import {module}")])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}++fn create_venv(slot: &InstallSlot, base: &str, venv: &Path) -> Result<(), String> {+ if let Some(parent) = venv.parent() {+ std::fs::create_dir_all(parent).map_err(|e| os_error::english(&e))?;+ }+ slot.log(format!("creating the 3D engine environment at {}", venv.display()));+ let mut cmd = crate::python::python_command(base);+ cmd.args(["-m", "venv", "--clear"]).arg(venv.as_os_str());+ crate::commands::video::run_streamed(slot, &mut cmd)+ .map_err(|e| format!("Could not create the Python environment for the 3D engine. {e}"))?;+ if !venv_python(venv).exists() {+ return Err("Python reported a new environment, but there is no interpreter in it.".to_string());+ }+ Ok(())+}++/// The engine's interpreter, with the packages installed first when they are+/// not. Built from LU's own Python (`private_python`), never one found on the+/// Mac. `base` is for the tests.+fn ensure_engine_at(slot: &InstallSlot, base: Option<String>, venv: &Path) -> Result<String, String> {+ let python = venv_python(venv).to_string_lossy().to_string();+ if engine_ready_at(venv) {+ return Ok(python);+ }+ if !(venv_python(venv).exists() && python_has_module(&python, "pip")) {+ let base = match base {+ Some(base) => base,+ None => crate::private_python::ensure(slot)?.to_string_lossy().to_string(),+ };+ slot.log(format!("Python: {base}"));+ create_venv(slot, &base, venv)?;+ }+ let _ = std::fs::remove_file(stamp_file(venv));+ slot.log(format!("installing the 3D engine packages, {} pinned (one-time)", PINNED.len()));+ let mut pip = crate::python::python_command(&python);+ pip.args(pip_args());+ crate::commands::video::run_streamed(slot, &mut pip).map_err(|e| format!("Could not install the 3D engine. {e}"))?;+ if !python_has_module(&python, MODULE) {+ return Err(format!("pip install finished but `import {MODULE}` still fails"));+ }+ std::fs::write(stamp_file(venv), stamp()).map_err(|e| os_error::english(&e))?;+ Ok(python)+}++// ── The source ────────────────────────────────────────────────────────++fn source_remote() -> RemoteFile {+ RemoteFile { url: format!("{SOURCE}/{SOURCE_COMMIT}.zip"), size: SOURCE_BYTES, sha256: SOURCE_SHA256.to_string() }+}++const SOURCE_MARKER: &str = ".lu-triposr-source";++fn source_ready_at(root: &Path) -> bool {+ let dir = source_dir(root);+ dir.join("tsr").join("system.py").is_file()+ && std::fs::read_to_string(dir.join(SOURCE_MARKER)).is_ok_and(|s| s.trim() == SOURCE_SHA256)+}++/// The part of an archive entry that is kept: what lies under `tsr/` as a+/// Python file, and the licence. `None` for everything else (the examples,+/// the figures, `run.py`, the Gradio app) and for any name that would leave+/// the folder.+fn kept_entry(name: &str) -> Option<PathBuf> {+ let top = format!("TripoSR-{SOURCE_COMMIT}/");+ let rest = name.strip_prefix(&top)?;+ let path = Path::new(rest);+ if path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {+ return None;+ }+ if rest == "LICENSE" || (rest.starts_with("tsr/") && rest.ends_with(".py")) {+ Some(path.to_path_buf())+ } else {+ None+ }+}++/// Unpack the verified archive into its folder, through a folder beside it+/// that gets the real name only once every file is written.+fn unpack_source(archive: &Path, root: &Path) -> Result<(), String> {+ let target = source_dir(root);+ let staging = target.with_extension("unpack");+ let _ = std::fs::remove_dir_all(&staging);+ std::fs::create_dir_all(&staging).map_err(|e| os_error::english(&e))?;+ let file = std::fs::File::open(archive).map_err(|e| os_error::english(&e))?;+ let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("The TripoSR archive could not be read ({e})."))?;+ let mut kept = 0usize;+ for i in 0..zip.len() {+ let mut entry = zip.by_index(i).map_err(|e| format!("The TripoSR archive could not be read ({e})."))?;+ if !entry.is_file() {+ continue;+ }+ let name = entry.name().map(|n| n.to_string()).unwrap_or_default();+ let Some(rel) = kept_entry(&name) else { continue };+ let out = staging.join(&rel);+ if let Some(parent) = out.parent() {+ std::fs::create_dir_all(parent).map_err(|e| os_error::english(&e))?;+ }+ let mut dest = std::fs::File::create(&out).map_err(|e| os_error::english(&e))?;+ std::io::copy(&mut entry, &mut dest).map_err(|e| os_error::english(&e))?;+ kept += 1;+ }+ if !staging.join("tsr").join("system.py").is_file() {+ let _ = std::fs::remove_dir_all(&staging);+ return Err("The TripoSR archive has no tsr/system.py. Start the download again.".to_string());+ }+ std::fs::write(staging.join(SOURCE_MARKER), SOURCE_SHA256).map_err(|e| os_error::english(&e))?;+ let _ = std::fs::remove_dir_all(&target);+ std::fs::rename(&staging, &target).map_err(|e| os_error::english(&e))?;+ tracing::info!("[mesh3d] TripoSR source unpacked, {kept} files");+ Ok(())+}++// ── The weights ───────────────────────────────────────────────────────++/// One file of the model: where it comes from and where it goes.+struct WeightFile {+ remote: RemoteFile,+ /// Below `weights_dir`.+ path: &'static str,+}++fn weight_files() -> [WeightFile; 3] {+ let hub = |repo: &str, revision: &str, file: &str| format!("https://huggingface.co/{repo}/resolve/{revision}/{file}");+ [+ WeightFile {+ remote: RemoteFile { url: hub(REPO, REVISION, "model.ckpt"), size: CKPT_BYTES, sha256: CKPT_SHA256.to_string() },+ path: "model.ckpt",+ },+ WeightFile {+ remote: RemoteFile { url: hub(REPO, REVISION, "config.yaml"), size: CONFIG_BYTES, sha256: CONFIG_SHA256.to_string() },+ path: "config.yaml",+ },+ WeightFile {+ remote: RemoteFile {+ url: hub(DINO_REPO, DINO_REVISION, "config.json"),+ size: DINO_CONFIG_BYTES,+ sha256: DINO_CONFIG_SHA256.to_string(),+ },+ path: "dino-vitb16/config.json",+ },+ ]+}++/// Written when every file was downloaded and checked. The sizes are held+/// against it on every look; the digests were checked when the files came.+const MANIFEST: &str = ".lu-mesh3d-weights.json";++#[derive(Serialize, Deserialize, Debug, PartialEq)]+struct Manifest {+ revision: String,+ dino_revision: String,+}++fn this_manifest() -> Manifest {+ Manifest { revision: REVISION.to_string(), dino_revision: DINO_REVISION.to_string() }+}++fn weights_complete(dir: &Path) -> bool {+ let manifest = std::fs::read_to_string(dir.join(MANIFEST)).ok().and_then(|s| serde_json::from_str::<Manifest>(&s).ok());+ manifest.is_some_and(|m| m == this_manifest())+ && weight_files()+ .iter()+ .all(|f| std::fs::metadata(dir.join(f.path)).map(|m| m.is_file() && m.len() == f.remote.size).unwrap_or(false))+}++/// Engine, source and weights. This is what the tile, the Create tab and a+/// run ask.+fn installed_at(root: &Path) -> bool {+ engine_ready_at(&venv_dir(root)) && source_ready_at(root) && weights_complete(&weights_dir(root))+}++/// What an install still has to write.+fn bytes_to_fetch(root: &Path) -> u64 {+ let weights = if weights_complete(&weights_dir(root)) {+ 0+ } else {+ WEIGHTS_BYTES.saturating_sub(crate::install_state::dir_size(&weights_dir(root)))+ };+ let source = if source_ready_at(root) { 0 } else { SOURCE_BYTES };+ weights + source + if engine_ready_at(&venv_dir(root)) { 0 } else { ENGINE_INSTALL_BYTES }+}++/// Fetch every `(remote, destination)` that is not there yet, one after the+/// other, with one bar over all of them.+fn fetch_files(slot: &InstallSlot, files: &[(RemoteFile, PathBuf)], what: &str) -> Result<(), String> {+ use crate::commands::voice_loop::fetch;+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|e| format!("The download could not be started: {}.", os_error::io_english(&e)))?;+ let client = fetch::http_client()?;+ let total: u64 = files.iter().map(|(r, _)| r.size).sum();+ let cancel = slot.cancel_flag();+ let started = Instant::now();+ let mut before = 0u64;+ let mut base: Option<u64> = None;+ for (remote, dest) in files {+ let meter = slot.clone();+ let offset = before;+ let base_ref = &mut base;+ let mut on_progress = move |done: u64| {+ let all = offset + done;+ let first = *base_ref.get_or_insert(all);+ let seconds = started.elapsed().as_secs_f64().max(0.001);+ meter.set_download(all, total, (all.saturating_sub(first) as f64 / seconds) as u64);+ };+ let fetched = runtime.block_on(fetch::fetch_verified(&client, remote, dest, &cancel, &mut on_progress));+ if let Err(e) = fetched {+ slot.set_download(0, 0, 0);+ return Err(e.user_message(what));+ }+ before += remote.size;+ }+ slot.set_download(0, 0, 0);+ Ok(())+}++fn install_source(slot: &InstallSlot, root: &Path) -> Result<(), String> {+ if source_ready_at(root) {+ return Ok(());+ }+ slot.log(format!("downloading the TripoSR source at {}", &SOURCE_COMMIT[..7]));+ let archive = downloads_dir(root).join(format!("TripoSR-{SOURCE_COMMIT}.zip"));+ fetch_files(slot, &[(source_remote(), archive.clone())], "the TripoSR source")?;+ unpack_source(&archive, root)?;+ let _ = std::fs::remove_file(&archive);+ Ok(())+}++fn install_weights(slot: &InstallSlot, root: &Path) -> Result<(), String> {+ let dir = weights_dir(root);+ if weights_complete(&dir) {+ slot.log("the weights of TripoSR are on disk already");+ return Ok(());+ }+ slot.log(format!("downloading {REPO} ({})", crate::commands::mlx_snapshot::human_bytes(WEIGHTS_BYTES)));+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;+ let _ = std::fs::remove_file(dir.join(MANIFEST));+ let files: Vec<(RemoteFile, PathBuf)> = weight_files().into_iter().map(|f| (f.remote, dir.join(f.path))).collect();+ fetch_files(slot, &files, "the TripoSR model")?;+ // Two strings: this cannot fail to serialise.+ let record = serde_json::to_string(&this_manifest()).unwrap_or_default();+ std::fs::write(dir.join(MANIFEST), record).map_err(|e| os_error::english(&e))?;+ Ok(())+}++/// The runner on the disk, as compiled into this build.+fn write_runner(root: &Path) -> Result<PathBuf, String> {+ let file = runner_file(root);+ if std::fs::read_to_string(&file).is_ok_and(|s| s == RUNNER) {+ return Ok(file);+ }+ if let Some(dir) = file.parent() {+ std::fs::create_dir_all(dir).map_err(|e| os_error::english(&e))?;+ }+ std::fs::write(&file, RUNNER).map_err(|e| os_error::english(&e))?;+ Ok(file)+}++/// The runner's own test: a sphere through the surface, colour and GLB code,+/// and TripoSR imported with the stand-ins. Proves the venv and the source.+fn self_test(slot: &InstallSlot, python: &str, root: &Path) -> Result<(), String> {+ let runner = write_runner(root)?;+ let out = work_dir(root).join("selftest.glb");+ std::fs::create_dir_all(work_dir(root)).map_err(|e| os_error::english(&e))?;+ let mut cmd = crate::python::python_command(python);+ cmd.arg("-I").arg(&runner).arg("--lu-mesh3d-selftest").arg(&out).arg("--source").arg(source_dir(root));+ cmd.current_dir(work_dir(root)).env("HF_HUB_OFFLINE", "1");+ crate::commands::video::run_streamed(slot, &mut cmd).map_err(|e| format!("The 3D engine did not pass its self test. {e}"))?;+ let _ = std::fs::remove_file(&out);+ Ok(())+}++// ── Commands: status, install, remove ─────────────────────────────────++const DESCRIPTION: &str = "Turns one picture of an object into a 3D model with colours, on this Mac. The download is the official TripoSR release.";++fn model_json(installed: bool) -> Value {+ json!({+ "id": MODEL_ID,+ "name": MODEL_NAME,+ "repo": REPO,+ "sizeGB": ((WEIGHTS_BYTES as f64) / 1e8).round() / 10.0,+ "minRamGB": MIN_RAM_GB,+ "unfiltered": false,+ "description": DESCRIPTION,+ "installed": installed,+ })+}++pub fn mesh3d_status(_state: &AppState, _args: &Value) -> CmdResult {+ let apple_silicon = ensure_apple_silicon().is_ok();+ let root = root();+ let engine = engine_ready_at(&venv_dir(&root));+ let installed = installed_at(&root);+ Ok(json!({+ "available": apple_silicon,+ "appleSilicon": apple_silicon,+ "engineInstalled": engine,+ "engineCommit": SOURCE_COMMIT,+ "installed": installed,+ "running": busy(),+ "outputsRoot": outputs_root(),+ "model": model_json(installed),+ }))+}++pub fn mesh3d_install(state: &AppState, _args: &Value) -> CmdResult {+ ensure_apple_silicon()?;+ let root = root();+ let slot = state.install_mesh3d();+ if slot.is_running() {+ return Ok(json!({ "ok": true, "status": "installing" }));+ }+ if installed_at(&root) {+ if slot.try_start() {+ slot.complete(format!("{MODEL_ID} already installed"));+ }+ return Ok(json!({ "ok": true, "status": "complete", "id": MODEL_ID }));+ }+ let note = if engine_ready_at(&venv_dir(&root)) { "" } else { "incl. the one-time 3D engine" };+ crate::commands::system::ensure_free_space(&crate::os_paths::data_dir(), MODEL_NAME, bytes_to_fetch(&root), note)+ .map_err(bad_request)?;+ std::fs::create_dir_all(&root).map_err(|e| internal(os_error::english(&e)))?;+ crate::media_store::keep_out_of_backups(&root);+ if !slot.try_start() {+ return Ok(json!({ "ok": true, "status": "installing" }));+ }+ crate::install_state::spawn_install(slot, move |slot| {+ let python = ensure_engine_at(slot, None, &venv_dir(&root))?;+ install_source(slot, &root)?;+ self_test(slot, &python, &root)?;+ install_weights(slot, &root)?;+ if !installed_at(&root) {+ return Err("The download finished, but the model is not complete on disk. Start it again.".to_string());+ }+ Ok(format!("{MODEL_ID} installed"))+ });+ Ok(json!({ "ok": true, "status": "installing", "id": MODEL_ID }))+}++pub fn mesh3d_install_status(state: &AppState, _args: &Value) -> CmdResult {+ Ok(serde_json::to_value(state.install_mesh3d().snapshot()).unwrap_or(Value::Null))+}++pub fn mesh3d_cancel_install(state: &AppState, _args: &Value) -> CmdResult {+ Ok(json!({ "ok": true, "cancelled": state.install_mesh3d().cancel() }))+}++/// Remove the weights. The engine and the source stay, as with music.+pub fn mesh3d_delete(state: &AppState, _args: &Value) -> CmdResult {+ if busy() {+ return Err(bad_request("A 3D model is being made. Wait for it to finish before removing the model."));+ }+ if state.install_mesh3d().is_running() {+ return Err(bad_request("The 3D model is still installing. Wait for it to finish, or stop it first."));+ }+ delete_at(&root())?;+ Ok(json!({ "ok": true, "id": MODEL_ID }))+}++fn delete_at(root: &Path) -> Result<(), String> {+ let dir = weights_dir(root);+ if !dir.is_dir() {+ return Err(not_found(format!("{MODEL_ID} is not installed")));+ }+ std::fs::remove_dir_all(&dir).map_err(|e| internal(format!("delete {MODEL_ID}: {}", os_error::english(&e))))?;+ let _ = std::fs::remove_dir_all(downloads_dir(root));+ Ok(())+}++// ── A run ─────────────────────────────────────────────────────────────++#[derive(Deserialize, Debug, Default)]+#[serde(rename_all = "camelCase")]+struct GenerateArgs {+ /// The name the caller gives the run: the name of the file, and what a+ /// Cancel names.+ run: String,+ /// A picture staged by Create (`video_stage_start_image`).+ image_path: String,+ #[serde(default)]+ resolution: Option<u32>,+ /// Cut the object out with Vision first. On unless asked otherwise; a+ /// picture that is transparent already is never cut again.+ #[serde(default)]+ cutout: Option<bool>,+}++/// The grid side a run uses, within what this lane offers, on steps of 32.+fn resolution_for(asked: Option<u32>) -> u32 {+ let r = asked.unwrap_or(DEFAULT_RESOLUTION).clamp(MIN_RESOLUTION, MAX_RESOLUTION);+ (r + 16) / 32 * 32+}++/// The run's name as a file name: letters, digits, `-` and `_`, at most 80.+/// Anything else is not a name this app gave.+fn run_file_stem(run: &str) -> Option<&str> {+ let ok = !run.is_empty() && run.len() <= 80 && run.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');+ ok.then_some(run)+}++/// The file a run writes, never one that is there already.+fn output_for(dir: &Path, run: &str, job: &str) -> PathBuf {+ let first = dir.join(format!("{run}.glb"));+ if first.exists() {+ dir.join(format!("{run}-{}.glb", &job[..8]))+ } else {+ first+ }+}++/// Whether a picture has transparent pixels: the cutout of an earlier step.+fn has_transparency(path: &Path) -> bool {+ let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else {+ return false;+ };+ let Ok(picture) = reader.decode() else { return false };+ picture.color().has_alpha() && picture.to_rgba8().pixels().any(|p| p[3] < 255)+}++/// What the runner reads, one file per run.+fn job_json(root: &Path, image: &Path, resolution: u32, job_dir: &Path, output: &Path) -> Value {+ let weights = weights_dir(root);+ json!({+ "image": image,+ "source": source_dir(root),+ "weights": weights.join("model.ckpt"),+ "config": weights.join("config.yaml"),+ "dino_config": weights.join("dino-vitb16").join("config.json"),+ "resolution": resolution,+ "threshold": THRESHOLD,+ "chunk": CHUNK,+ "foreground_ratio": FOREGROUND_RATIO,+ "device": "auto",+ "work": job_dir,+ "output": output,+ })+}++/// The flag that names the job file. It is also how a run is recognised+/// after a crash of the app.+const JOB_FLAG: &str = "--lu-mesh3d-job";++/// The command line and the environment of a run.+fn run_command(root: &Path, runner: &Path, job_file: &Path) -> Command {+ let mut cmd = crate::python::python_command(venv_python(&venv_dir(root)));+ // `-I`: nothing from the working folder or the environment's PYTHON*+ // variables is imported; the runner adds the pinned source itself.+ // `-u`: through a pipe Python holds its lines back in blocks.+ cmd.arg("-I").arg("-u").arg(runner).arg(JOB_FLAG).arg(job_file.as_os_str());+ cmd.current_dir(work_dir(root))+ // What MPS cannot run goes to the CPU instead of ending the run.+ .env("PYTORCH_ENABLE_MPS_FALLBACK", "1")+ .env("HF_HUB_OFFLINE", "1")+ .env("TRANSFORMERS_OFFLINE", "1")+ .env("HF_HOME", root.join(".hf-cache"))+ .env("TOKENIZERS_PARALLELISM", "false")+ .stdin(Stdio::null());+ cmd+}++fn memory_refusal(total_bytes: u64) -> Option<String> {+ if total_bytes == 0 {+ return None;+ }+ let have = (total_bytes as f64 / 1_073_741_824.0).round() as u32;+ (have < MIN_RAM_GB).then(|| {+ format!("{MODEL_NAME} needs a Mac with {MIN_RAM_GB} GB of memory, and this one has {have} GB. It was not started, because loading it would freeze this Mac.")+ })+}++/// What a poll is told about the run: the last one, or the one under way.+#[derive(Clone, Debug, Default, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+struct View {+ job: Option<String>,+ run: Option<String>,+ /// idle, running, complete, error or cancelled.+ status: &'static str,+ /// load, cutout, shape, paint or save: the interface words it.+ phase: String,+ detail: String,+ percent: u32,+ error: Option<String>,+ /// `no_object` when no object was found in the picture.+ error_code: Option<String>,+ output: Option<String>,+ triangles: Option<u64>,+ vertices: Option<u64>,+ /// mps or cpu, as the runner reports it.+ device: Option<String>,+ logs: Vec<String>,+}++struct Runs {+ pid: Mutex<Option<u32>>,+ held: Mutex<Option<String>>,+ stopped: AtomicBool,+ view: Mutex<View>,+ heard: Mutex<Option<Instant>>,+}++impl Runs {+ const fn new() -> Self {+ Self {+ pid: Mutex::new(None),+ held: Mutex::new(None),+ stopped: AtomicBool::new(false),+ view: Mutex::new(View {+ job: None,+ run: None,+ status: "idle",+ phase: String::new(),+ detail: String::new(),+ percent: 0,+ error: None,+ error_code: None,+ output: None,+ triangles: None,+ vertices: None,+ device: None,+ logs: Vec::new(),+ }),+ heard: Mutex::new(None),+ }+ }++ fn pid(&self) -> std::sync::MutexGuard<'_, Option<u32>> {+ self.pid.lock().unwrap_or_else(|e| e.into_inner())+ }++ fn held(&self) -> std::sync::MutexGuard<'_, Option<String>> {+ self.held.lock().unwrap_or_else(|e| e.into_inner())+ }++ fn view(&self) -> std::sync::MutexGuard<'_, View> {+ self.view.lock().unwrap_or_else(|e| e.into_inner())+ }++ fn heard_now(&self) {+ *self.heard.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());+ }++ fn silent_for(&self) -> Duration {+ self.heard.lock().unwrap_or_else(|e| e.into_inner()).map(|t| t.elapsed()).unwrap_or_default()+ }++ fn claim(&self, run: &str, job: &str) -> Option<Claim<'_>> {+ let mut held = self.held();+ if held.is_some() {+ return None;+ }+ self.stopped.store(false, SeqCst);+ *held = Some(run.to_string());+ *self.view() = View {+ job: Some(job.to_string()),+ run: Some(run.to_string()),+ status: "running",+ phase: "load".to_string(),+ ..View::default()+ };+ self.heard_now();+ Some(Claim(self))+ }++ fn busy(&self) -> bool {+ let held = self.held().is_some();+ held || self.pid().is_some()+ }++ fn stop(&self) -> bool {+ let pid = {+ let pid = self.pid();+ if pid.is_none() && self.held().is_none() {+ return false;+ }+ self.stopped.store(true, SeqCst);+ *pid+ };+ if let Some(pid) = pid {+ crate::process_util::kill_pid_tree(pid);+ }+ true+ }++ /// End the run that carries this name, and no other.+ fn stop_run(&self, run: Option<&str>) -> bool {+ if let Some(name) = run {+ if self.held().as_deref() != Some(name) {+ return false;+ }+ }+ self.stop()+ }++ fn set_phase(&self, phase: &str, percent: u32) {+ self.heard_now();+ let mut view = self.view();+ view.phase = phase.to_string();+ view.percent = view.percent.max(percent);+ }++ /// Read one line of the run.+ fn note(&self, line: &str) {+ self.heard_now();+ let mut view = self.view();+ if let Some(said) = line.strip_prefix("LU-MESH3D ").and_then(|j| serde_json::from_str::<Value>(j).ok()) {+ let mut at = |phase: &str, percent: u32| {+ view.phase = phase.to_string();+ view.percent = view.percent.max(percent);+ };+ match said["phase"].as_str().unwrap_or("") {+ "load" => at("load", 8),+ "shape" => {+ let f = said["fraction"].as_f64().filter(|f| f.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);+ at("shape", (15.0 + f * 65.0).round() as u32);+ }+ "paint" => at("paint", 82),+ "save" => at("save", 92),+ "note" => {+ if let Some(device) = said["device"].as_str() {+ view.device = Some(device.to_string());+ }+ view.detail = said["note"].as_str().unwrap_or("").to_string();+ }+ "error" => {+ view.error = said["error"].as_str().map(str::to_string);+ view.error_code = said["code"].as_str().map(str::to_string);+ }+ "done" => {+ view.percent = 100;+ view.triangles = said["triangles"].as_u64();+ view.vertices = said["vertices"].as_u64();+ if let Some(device) = said["device"].as_str() {+ view.device = Some(device.to_string());+ }+ }+ _ => {}+ }+ return;+ }+ view.logs.push(line.to_string());+ let over = view.logs.len().saturating_sub(40);+ view.logs.drain(..over);+ }++ fn conclude(&self, verdict: &Result<(), String>) {+ let mut view = self.view();+ match verdict {+ Ok(()) => {+ view.status = "complete";+ view.percent = 100;+ view.error = None;+ }+ Err(why) if why == STOPPED => {+ view.status = "cancelled";+ view.error = Some("cancelled".to_string());+ }+ Err(why) => {+ view.status = "error";+ if why == NO_OBJECT {+ view.error_code = Some("no_object".to_string());+ }+ view.error = Some(why.clone());+ }+ }+ }+}++struct Claim<'a>(&'a Runs);++impl Drop for Claim<'_> {+ fn drop(&mut self) {+ *self.0.held() = None;+ }+}++static RUNS: Runs = Runs::new();++/// Whether a 3D model is being made right now.+pub(crate) fn busy() -> bool {+ RUNS.busy()+}++/// The sentence another engine of the Mac refuses its run with while a 3D+/// model is being made.+pub(crate) fn refusal() -> Option<&'static str> {+ busy().then_some("A 3D model is being made on this Mac. Wait for it to finish, then try again.")+}++/// End the run that is under way. The quit path calls this.+pub(crate) fn stop() -> bool {+ RUNS.stop()+}++const STOPPED: &str = "The 3D model was not finished because the app stopped the engine.";+const HUNG: &str = "The 3D engine said nothing for five minutes and was ended. Start it again.";+/// The words of Create for a picture without a clear object (plan 1.8).+const NO_OBJECT: &str = "LU could not find a clear object in this picture. Try one with a plain background.";++fn start(runs: &Runs, mut cmd: Command, pid_file: Option<&Path>) -> Result<std::process::Child, String> {+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut slot = runs.pid();+ if slot.is_some() {+ return Err("A 3D model is already being made on this Mac. Wait for it to finish.".to_string());+ }+ if runs.stopped.swap(false, SeqCst) {+ return Err(STOPPED.to_string());+ }+ let child = cmd.spawn().map_err(|e| format!("Could not start the 3D engine: {}", os_error::english(&e)))?;+ if let Some(note) = pid_file {+ if let Some(dir) = note.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ let _ = std::fs::write(note, child.id().to_string());+ }+ *slot = Some(child.id());+ runs.heard_now();+ Ok(child)+}++fn finish(runs: &Runs, mut child: std::process::Child, out: &Path, pid_file: Option<&Path>, limit: Duration, stall: Duration) -> Result<(), String> {+ let (stdout, stderr) = (child.stdout.take(), child.stderr.take());+ let started = Instant::now();+ let status = std::thread::scope(|scope| {+ scope.spawn(|| crate::commands::music::read_lines(stdout, |line| runs.note(line)));+ scope.spawn(|| crate::commands::music::read_lines(stderr, |line| runs.note(line)));+ let status = loop {+ match child.try_wait() {+ Ok(Some(status)) => break Ok(Some(status)),+ Ok(None) => {}+ Err(e) => break Err(e),+ }+ if started.elapsed() > limit {+ let _ = crate::process_util::kill_tree(&mut child);+ let _ = child.wait();+ break Ok(None);+ }+ if runs.silent_for() > stall {+ let _ = crate::process_util::kill_tree(&mut child);+ let _ = child.wait();+ runs.view().error = Some(HUNG.to_string());+ break Ok(None);+ }+ std::thread::sleep(Duration::from_millis(200));+ };+ *runs.pid() = None;+ if let Some(note) = pid_file {+ let _ = std::fs::remove_file(note);+ }+ status+ });+ let stopped = runs.stopped.swap(false, SeqCst);+ let (said, code) = {+ let view = runs.view();+ (view.error.clone(), view.error_code.clone())+ };+ let status = status.map_err(|e| format!("wait failed: {}", os_error::english(&e)))?;+ let verdict = outcome(status.as_ref(), out.is_file(), said.as_deref(), code.as_deref(), stopped);+ if verdict.is_err() {+ let _ = std::fs::remove_file(out);+ }+ verdict+}++fn outcome(status: Option<&std::process::ExitStatus>, wrote: bool, said: Option<&str>, code: Option<&str>, stopped: bool) -> Result<(), String> {+ if stopped {+ return Err(STOPPED.to_string());+ }+ let Some(status) = status else {+ return Err(match said {+ Some(HUNG) => HUNG.to_string(),+ _ => "The 3D engine did not finish within half an hour and was stopped.".to_string(),+ });+ };+ if status.success() && wrote {+ return Ok(());+ }+ if code == Some("no_object") {+ return Err(NO_OBJECT.to_string());+ }+ if let Some(why) = said.filter(|w| !w.is_empty()) {+ return Err(format!("The 3D engine stopped: {why}"));+ }+ if status.success() {+ return Err("The 3D engine finished without writing a model.".to_string());+ }+ if let Some(code) = status.code() {+ return Err(format!("The 3D engine stopped with exit code {code}. Its last lines are in the log."));+ }+ Err("The 3D engine was ended by macOS. This usually means the model did not fit into memory. Close other apps and try again, or pick a lower detail.".to_string())+}++/// Cut the object out of `input` into `job_dir` with Vision, as Remove+/// Background does on a Mac. A picture that is transparent already is+/// taken as it is.+fn cut_out_for_run(input: &Path, job_dir: &Path) -> Result<PathBuf, String> {+ if has_transparency(input) {+ return Ok(input.to_path_buf());+ }+ #[cfg(target_os = "macos")]+ {+ match crate::commands::mlx_cutout::cut_out(input, job_dir) {+ Ok((path, _, _)) => Ok(path),+ Err(why) if why == crate::commands::mlx_cutout::NO_SUBJECT => Err(NO_OBJECT.to_string()),+ Err(why) => Err(why),+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = job_dir;+ Err("The cutout before a 3D run needs a Mac.".to_string())+ }+}++pub async fn mesh3d_generate(state: &AppState, args: &Value) -> CmdResult {+ ensure_apple_silicon()?;+ let req: GenerateArgs = serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;+ let run = run_file_stem(req.run.trim()).ok_or_else(|| bad_request("The run needs a name of letters, digits and dashes."))?.to_string();+ let input = crate::commands::mlx_cutout::staged_input(&req.image_path, &crate::commands::mlx_cutout::staged_images_dir())+ .map_err(|e| bad_request(if e == crate::commands::mlx_cutout::NO_IMAGE { "Add a picture of one object first.".to_string() } else { e }))?;+ let root = root();+ if !installed_at(&root) {+ return Err(bad_request(format!("{MODEL_NAME} is not installed. Install it in the Model Manager first.")));+ }+ if let Some(refusal) = memory_refusal(crate::commands::system::total_memory_bytes()) {+ return Err(bad_request(refusal));+ }+ // One model in the memory at a time.+ if let Some(why) = crate::commands::mlx::train::refusal() {+ return Err(bad_request(why));+ }+ if crate::commands::mlx::image_engine_busy() {+ return Err(bad_request("An image is being generated on this Mac. Wait for it to finish, then make the 3D model."));+ }+ if state.video_process().lock().map(|p| p.is_some()).unwrap_or(true) {+ return Err(bad_request("A video is being generated on this Mac. Wait for it to finish, then make the 3D model."));+ }+ if crate::commands::music::busy() {+ return Err(bad_request("A track is being made on this Mac. Wait for it to finish, then make the 3D model."));+ }+ let job = uuid::Uuid::new_v4().simple().to_string();+ let claim = RUNS+ .claim(&run, &job)+ .ok_or_else(|| bad_request("A 3D model is already being made on this Mac. Wait for it to finish."))?;+ let _ = crate::commands::mlx::mlx_unload(state, &Value::Null).await;++ let out_dir = outputs_root();+ let job_dir = work_dir(&root).join("jobs").join(&job);+ for dir in [&out_dir, &job_dir] {+ if let Err(e) = std::fs::create_dir_all(dir) {+ let why = format!("mkdir {}: {}", dir.display(), os_error::english(&e));+ RUNS.conclude(&Err(why.clone()));+ return Err(internal(why));+ }+ }+ let runner = match write_runner(&root) {+ Ok(path) => path,+ Err(why) => {+ RUNS.conclude(&Err(why.clone()));+ return Err(internal(why));+ }+ };+ let output = output_for(&out_dir, &run, &job);+ let resolution = resolution_for(req.resolution);+ let cutout = req.cutout.unwrap_or(true);+ RUNS.view().output = Some(output.to_string_lossy().to_string());+ tracing::info!("[mesh3d] TripoSR at {}: grid {resolution}, cutout {cutout}", &SOURCE_COMMIT[..7]);+ let pid_file = run_pid_file(&root);+ let out = output.clone();+ std::thread::spawn(move || {+ let verdict = (|| {+ let picture = if cutout {+ RUNS.set_phase("cutout", 2);+ cut_out_for_run(&input, &job_dir)?+ } else {+ input.clone()+ };+ RUNS.set_phase("load", 5);+ let job_file = job_dir.join("job.json");+ std::fs::write(&job_file, job_json(&root, &picture, resolution, &job_dir, &out).to_string())+ .map_err(|e| format!("write {}: {}", job_file.display(), os_error::english(&e)))?;+ let child = start(&RUNS, run_command(&root, &runner, &job_file), Some(&pid_file))?;+ finish(&RUNS, child, &out, Some(&pid_file), GENERATE_TIMEOUT, STALL_AFTER)+ })();+ // A Cancel during the cutout, before there was a process.+ let verdict = match verdict {+ Err(_) if RUNS.stopped.swap(false, SeqCst) => Err(STOPPED.to_string()),+ other => other,+ };+ if let Err(why) = &verdict {+ tracing::error!("[mesh3d] {why}");+ let _ = std::fs::remove_file(&out);+ }+ RUNS.conclude(&verdict);+ let _ = std::fs::remove_dir_all(&job_dir);+ drop(claim);+ });+ Ok(json!({+ "ok": true,+ "jobId": job,+ "run": run,+ "output": output,+ "resolution": resolution,+ "cutout": cutout,+ }))+}++pub fn mesh3d_progress(_state: &AppState, _args: &Value) -> CmdResult {+ let view = RUNS.view().clone();+ let mut answer = serde_json::to_value(&view).unwrap_or(Value::Null);+ answer["running"] = json!(busy());+ answer["pid"] = json!(*RUNS.pid());+ if let Some(bytes) = view.output.as_deref().filter(|_| view.status == "complete").and_then(|p| std::fs::metadata(p).ok()).map(|m| m.len()) {+ answer["bytes"] = json!(bytes);+ }+ Ok(answer)+}++#[derive(Deserialize, Default)]+struct CancelArgs {+ #[serde(default)]+ run: Option<String>,+}++pub fn mesh3d_cancel(_state: &AppState, args: &Value) -> CmdResult {+ let a: CancelArgs = serde_json::from_value(args.clone()).unwrap_or_default();+ Ok(json!({ "ok": true, "stopped": RUNS.stop_run(a.run.as_deref()) }))+}++// ── A run that outlived the app ───────────────────────────────────────++#[cfg(any(target_os = "macos", test))]+struct Leftover {+ parent: Option<u32>,+ cmd: Vec<String>,+}++#[cfg(any(target_os = "macos", test))]+fn is_orphaned_run(row: &Leftover, work: &Path) -> bool {+ row.parent == Some(1) && row.cmd.windows(2).any(|w| w[0] == JOB_FLAG && Path::new(&w[1]).starts_with(work))+}++/// End the run the last session left behind, if there is one, and return its+/// pid. Called once at app start, off the main thread.+#[cfg(target_os = "macos")]+pub(crate) fn reap_orphaned_run() -> Option<u32> {+ let root = root();+ let pid_file = run_pid_file(&root);+ let pid: u32 = std::fs::read_to_string(&pid_file).ok()?.trim().parse().ok()?;+ let table = crate::process_util::process_table_with_cmdlines();+ let Some(process) = table.process(sysinfo::Pid::from_u32(pid)) else {+ let _ = std::fs::remove_file(&pid_file);+ return None;+ };+ let row = Leftover { parent: process.parent().map(|p| p.as_u32()), cmd: crate::process_util::cmdline_of(process) };+ if !is_orphaned_run(&row, &work_dir(&root)) {+ if row.parent == Some(1) {+ let _ = std::fs::remove_file(&pid_file);+ }+ return None;+ }+ crate::process_util::kill_pid_tree(pid);+ let _ = std::fs::remove_file(&pid_file);+ Some(pid)+}++/// For `real_run_mac`: whatever the last run said, for the record.+#[cfg(all(test, target_os = "macos"))]+pub(crate) fn real_run_view() -> Value {+ serde_json::to_value(RUNS.view().clone()).unwrap_or(Value::Null)+}++/// For `real_run_mac`: the venv of the engine, to measure it.+#[cfg(all(test, target_os = "macos"))]+pub(crate) fn real_run_root() -> PathBuf {+ root()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn production_source() -> &'static str {+ let src = include_str!("mesh3d.rs");+ &src[..src.find("#[cfg(test)]\nmod tests").unwrap()]+ }++ fn put(path: PathBuf, bytes: u64) {+ crate::test_support::sized_file(&path, bytes);+ }++ fn args_of(cmd: &Command) -> Vec<String> {+ cmd.get_args().map(|a| a.to_string_lossy().to_string()).collect()+ }++ fn env_of(cmd: &Command, key: &str) -> Option<String> {+ cmd.get_envs().find(|(k, _)| *k == key).and_then(|(_, v)| v).map(|v| v.to_string_lossy().to_string())+ }++ fn hex40(s: &str) -> bool {+ s.len() == 40 && s.chars().all(|c| c.is_ascii_hexdigit())+ }++ fn hex64(s: &str) -> bool {+ s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())+ }++ #[test]+ fn the_source_and_the_weights_are_pinned_by_commit_revision_size_and_digest() {+ assert!(hex40(SOURCE_COMMIT) && hex40(REVISION) && hex40(DINO_REVISION));+ for sha in [SOURCE_SHA256, CKPT_SHA256, CONFIG_SHA256, DINO_CONFIG_SHA256] {+ assert!(hex64(sha), "{sha}");+ }+ assert_eq!(source_remote().url, format!("https://github.com/VAST-AI-Research/TripoSR/archive/{SOURCE_COMMIT}.zip"));+ assert_eq!(CKPT_BYTES, 1_677_246_742, "the size the plan read from the hub");+ let files = weight_files();+ assert_eq!(files.map(|f| f.path), ["model.ckpt", "config.yaml", "dino-vitb16/config.json"]);+ for f in &weight_files() {+ assert!(f.remote.url.starts_with("https://huggingface.co/"), "{}", f.remote.url);+ assert!(f.remote.url.contains(REVISION) || f.remote.url.contains(DINO_REVISION), "{}", f.remote.url);+ assert!(!f.remote.url.contains("/main/"), "{}", f.remote.url);+ }+ assert_eq!(model_json(false)["sizeGB"], 1.7);+ let src = production_source();+ let code: String = src.lines().filter(|l| !l.trim_start().starts_with("//")).collect::<Vec<_>>().join("\n");+ assert!(!code.contains("@main") && !code.contains("git+"));+ }++ #[test]+ fn every_package_has_its_version_and_torch_is_the_music_engines() {+ for spec in &PINNED {+ let (name, version) = spec.split_once("==").unwrap_or_else(|| panic!("{spec} is not pinned"));+ assert!(!name.is_empty() && !version.is_empty() && !version.contains(['<', '>', '*', ' ']), "{spec}");+ }+ let mut names: Vec<&str> = PINNED.iter().map(|s| s.split("==").next().unwrap()).collect();+ let sorted = names.clone();+ names.sort();+ assert_eq!(names, sorted, "kept in order, so a diff shows what moved");+ names.dedup();+ assert_eq!(names.len(), PINNED.len());+ // The same wheels as the music engine where both stand on them.+ let music = include_str!("music.rs");+ for shared in ["torch==", "numpy==", "transformers==", "huggingface-hub==", "safetensors==", "tokenizers==", "einops==", "pillow=="] {+ let ours = PINNED.iter().find(|p| p.starts_with(shared)).unwrap_or_else(|| panic!("{shared}"));+ assert!(music.contains(&format!("\"{ours}\"")), "{ours} differs from the music engine");+ }+ // What a Mac cannot install, and what the runner replaces.+ for never in ["torchmcubes", "rembg", "xatlas", "moderngl", "gradio", "onnxruntime", "antlr4-python3-runtime"] {+ assert!(!PINNED.iter().any(|p| p.starts_with(&format!("{never}=="))), "{never}");+ }+ let pip = pip_args();+ assert_eq!(&pip[..7], ["-m", "pip", "install", "--upgrade", "--only-binary", ":all:", "--disable-pip-version-check"]);+ assert_eq!(&pip[7..], PINNED.map(String::from));+ }++ #[test]+ fn everything_lives_in_one_folder_of_the_app_and_models_beside_the_videos() {+ let root = root();+ assert!(root.starts_with(crate::os_paths::data_dir()));+ for dir in [venv_dir(&root), source_dir(&root), weights_dir(&root), downloads_dir(&root), work_dir(&root), runner_file(&root), run_pid_file(&root)] {+ assert!(dir.starts_with(&root), "{}", dir.display());+ }+ assert_ne!(venv_dir(&root), crate::os_paths::data_dir().join("acestep").join("venv"), "never the music engine's venv");+ assert_eq!(outputs_root().parent(), crate::commands::video::outputs_root().parent());+ assert_eq!(outputs_root().file_name().unwrap(), "3d");+ }++ #[test]+ fn a_venv_without_the_stamp_of_this_pin_is_not_the_engine() {+ let tmp = tempfile::tempdir().unwrap();+ let venv = tmp.path().join("venv");+ assert!(!engine_ready_at(&venv));+ put(venv_python(&venv), 1);+ assert!(!engine_ready_at(&venv));+ std::fs::write(stamp_file(&venv), "torch==2.9.0").unwrap();+ assert!(!engine_ready_at(&venv), "the stamp of another pin");+ std::fs::write(stamp_file(&venv), stamp()).unwrap();+ assert!(engine_ready_at(&venv));+ }++ #[test]+ fn only_the_tsr_package_and_the_licence_are_taken_from_the_archive() {+ let top = format!("TripoSR-{SOURCE_COMMIT}/");+ assert_eq!(kept_entry(&format!("{top}tsr/system.py")), Some(PathBuf::from("tsr/system.py")));+ assert_eq!(kept_entry(&format!("{top}tsr/models/tokenizers/image.py")), Some(PathBuf::from("tsr/models/tokenizers/image.py")));+ assert_eq!(kept_entry(&format!("{top}LICENSE")), Some(PathBuf::from("LICENSE")));+ for other in ["run.py", "gradio_app.py", "requirements.txt", "examples/chair.png", "tsr/../../evil.py", "tsr/x.so"] {+ assert_eq!(kept_entry(&format!("{top}{other}")), None, "{other}");+ }+ assert_eq!(kept_entry("TripoSR-main/tsr/system.py"), None, "the archive of another commit");+ assert_eq!(kept_entry("/etc/passwd"), None);+ }++ #[test]+ fn an_archive_is_unpacked_whole_or_not_at_all() {+ use std::io::Write;+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ let zip_path = root.join("a.zip");+ let write = |names: &[&str]| {+ let mut zip = zip::ZipWriter::new(std::fs::File::create(&zip_path).unwrap());+ for name in names {+ zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();+ zip.write_all(b"# py").unwrap();+ }+ zip.finish().unwrap();+ };+ let top = format!("TripoSR-{SOURCE_COMMIT}");+ write(&[&format!("{top}/run.py")]);+ assert!(unpack_source(&zip_path, root).unwrap_err().contains("tsr/system.py"));+ assert!(!source_ready_at(root));+ write(&[&format!("{top}/tsr/system.py"), &format!("{top}/tsr/utils.py"), &format!("{top}/examples/a.png"), &format!("{top}/LICENSE")]);+ unpack_source(&zip_path, root).unwrap();+ assert!(source_ready_at(root));+ assert!(source_dir(root).join("tsr/utils.py").is_file());+ assert!(!source_dir(root).join("examples").exists());+ }++ #[test]+ fn installed_is_engine_source_and_weights_and_remove_takes_the_weights() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ assert!(!installed_at(root));+ assert_eq!(bytes_to_fetch(root), WEIGHTS_BYTES + SOURCE_BYTES + ENGINE_INSTALL_BYTES);+ let dir = weights_dir(root);+ for f in weight_files() {+ put(dir.join(f.path), f.remote.size);+ }+ assert!(!weights_complete(&dir), "no manifest, no model: a stopped download looks the same");+ std::fs::write(dir.join(MANIFEST), serde_json::to_string(&this_manifest()).unwrap()).unwrap();+ assert!(weights_complete(&dir));+ put(dir.join("config.yaml"), 986);+ assert!(!weights_complete(&dir), "a file of the wrong size");+ put(dir.join("config.yaml"), CONFIG_BYTES);+ let old = Manifest { revision: "0".repeat(40), dino_revision: DINO_REVISION.to_string() };+ std::fs::write(dir.join(MANIFEST), serde_json::to_string(&old).unwrap()).unwrap();+ assert!(!weights_complete(&dir), "another revision");+ std::fs::write(dir.join(MANIFEST), serde_json::to_string(&this_manifest()).unwrap()).unwrap();++ put(venv_python(&venv_dir(root)), 1);+ std::fs::write(stamp_file(&venv_dir(root)), stamp()).unwrap();+ assert!(!installed_at(root), "no source");+ put(source_dir(root).join("tsr").join("system.py"), 3);+ std::fs::write(source_dir(root).join(SOURCE_MARKER), SOURCE_SHA256).unwrap();+ assert!(installed_at(root));+ assert_eq!(bytes_to_fetch(root), 0);++ delete_at(root).unwrap();+ assert!(!dir.exists());+ assert!(engine_ready_at(&venv_dir(root)) && source_ready_at(root), "engine and source stay");+ assert!(!installed_at(root));+ assert!(delete_at(root).unwrap_err().contains("not installed"));+ }++ #[test]+ fn the_grid_the_name_and_the_file_of_a_run() {+ assert_eq!(resolution_for(None), 256);+ assert_eq!(resolution_for(Some(128)), 128);+ assert_eq!(resolution_for(Some(10)), 64);+ assert_eq!(resolution_for(Some(5000)), 384);+ assert_eq!(resolution_for(Some(200)), 192);+ assert_eq!(run_file_stem("mesh3d-1731500000-1"), Some("mesh3d-1731500000-1"));+ for bad in ["", "../x", "a/b", "a b", "a.glb", &"x".repeat(81)] {+ assert_eq!(run_file_stem(bad), None, "{bad}");+ }+ let tmp = tempfile::tempdir().unwrap();+ let job = "0123456789abcdef";+ assert_eq!(output_for(tmp.path(), "r1", job), tmp.path().join("r1.glb"));+ std::fs::write(tmp.path().join("r1.glb"), b"x").unwrap();+ assert_eq!(output_for(tmp.path(), "r1", job), tmp.path().join("r1-01234567.glb"), "never over a model that is there");+ }++ #[test]+ fn a_picture_with_transparent_pixels_is_not_cut_again() {+ let tmp = tempfile::tempdir().unwrap();+ let cut = tmp.path().join("cut.png");+ let mut rgba = image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]));+ rgba.put_pixel(0, 0, image::Rgba([0, 0, 0, 0]));+ rgba.save(&cut).unwrap();+ assert!(has_transparency(&cut));+ assert_eq!(cut_out_for_run(&cut, tmp.path()).unwrap(), cut);+ let opaque = tmp.path().join("photo.png");+ image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).save(&opaque).unwrap();+ assert!(!has_transparency(&opaque));+ assert!(!has_transparency(&tmp.path().join("missing.png")));+ }++ #[test]+ fn the_job_carries_what_the_runner_reads() {+ let root = Path::new("/data/mesh3d");+ let job = job_json(root, Path::new("/s/start-images/a.png"), 256, Path::new("/data/mesh3d/work/jobs/j1"), Path::new("/c/3d/r1.glb"));+ for key in ["image", "source", "weights", "config", "dino_config", "resolution", "threshold", "chunk", "foreground_ratio", "work", "output"] {+ assert!(RUNNER.contains(&format!("job[\"{key}\"]")), "the runner does not read {key}");+ assert!(!job[key].is_null(), "{key}");+ }+ assert_eq!(job["threshold"], 25.0);+ assert_eq!(job["chunk"], 8192);+ assert!(job["source"].as_str().unwrap().ends_with(SOURCE_COMMIT));+ assert!(job["dino_config"].as_str().unwrap().ends_with("config.json"));+ }++ #[test]+ fn the_runner_replaces_what_a_mac_cannot_install_and_stays_offline() {+ for needed in [+ "sys.modules[\"torchmcubes\"]",+ "sys.modules[\"rembg\"]",+ "from skimage import measure",+ "tokenizer.hf_hub_download = local_config",+ "weights_only=True",+ "file_type=\"glb\"",+ "torch.backends.mps.is_available()",+ "PREFIX = \"LU-MESH3D \"",+ "JOB_FLAG = \"--lu-mesh3d-job\"",+ ] {+ assert!(RUNNER.contains(needed), "{needed}");+ }+ for never in ["rembg.new_session()", "import xatlas", "import moderngl", "bake_texture", "snapshot_download", "requests.get", "urllib"] {+ assert!(!RUNNER.contains(never), "{never}");+ }+ assert!(RUNNER.contains(&format!("DINO_REPO = \"{DINO_REPO}\"")));+ }++ #[test]+ fn the_command_line_runs_isolated_offline_and_with_the_mps_fallback() {+ let root = Path::new("/data/mesh3d");+ let cmd = run_command(root, Path::new("/data/mesh3d/runner/run_triposr.py"), Path::new("/data/mesh3d/work/jobs/j1/job.json"));+ assert_eq!(cmd.get_program(), venv_python(&venv_dir(root)).as_os_str());+ let args = args_of(&cmd);+ assert_eq!(args, ["-I", "-u", "/data/mesh3d/runner/run_triposr.py", JOB_FLAG, "/data/mesh3d/work/jobs/j1/job.json"]);+ assert_eq!(cmd.get_current_dir(), Some(work_dir(root).as_path()));+ assert_eq!(env_of(&cmd, "PYTORCH_ENABLE_MPS_FALLBACK").as_deref(), Some("1"));+ assert_eq!(env_of(&cmd, "HF_HUB_OFFLINE").as_deref(), Some("1"));+ assert_eq!(env_of(&cmd, "TRANSFORMERS_OFFLINE").as_deref(), Some("1"));+ }++ #[test]+ fn a_mac_with_too_little_memory_is_told_before_anything_loads() {+ const GIB: u64 = 1_073_741_824;+ assert!(memory_refusal(8 * GIB).unwrap().contains("needs a Mac with 16 GB"));+ assert_eq!(memory_refusal(16 * GIB), None);+ assert_eq!(memory_refusal(0), None);+ }++ #[test]+ fn the_lines_of_a_run_move_its_progress() {+ let runs = Runs::new();+ let _claim = runs.claim("r1", "j1").unwrap();+ assert_eq!(runs.view().status, "running");+ assert_eq!(runs.view().run.as_deref(), Some("r1"));+ runs.set_phase("cutout", 2);+ assert_eq!(runs.view().phase, "cutout");+ runs.note("LU-MESH3D {\"phase\": \"load\"}");+ assert_eq!({ let v = runs.view(); (v.phase.clone(), v.percent) }, ("load".to_string(), 8));+ runs.note("LU-MESH3D {\"phase\": \"note\", \"note\": \"device mps\", \"device\": \"mps\"}");+ assert_eq!(runs.view().device.as_deref(), Some("mps"));+ runs.note("LU-MESH3D {\"phase\": \"shape\", \"fraction\": 0.5}");+ assert_eq!(runs.view().percent, 48);+ runs.note("LU-MESH3D {\"phase\": \"shape\", \"fraction\": 0.1}");+ assert_eq!(runs.view().percent, 48, "never backwards");+ runs.note("LU-MESH3D {\"phase\": \"paint\"}");+ runs.note("LU-MESH3D {\"phase\": \"save\"}");+ assert_eq!({ let v = runs.view(); (v.phase.clone(), v.percent) }, ("save".to_string(), 92));+ runs.note("LU-MESH3D {\"phase\": \"done\", \"triangles\": 123, \"vertices\": 64, \"device\": \"mps\"}");+ assert_eq!({ let v = runs.view(); (v.triangles, v.vertices, v.percent) }, (Some(123), Some(64), 100));+ for i in 0..60 {+ runs.note(&format!("line {i}"));+ }+ assert_eq!(runs.view().logs.len(), 40);+ runs.conclude(&Ok(()));+ assert_eq!(runs.view().status, "complete");+ }++ #[test]+ fn one_run_at_a_time_and_a_cancel_names_its_run() {+ let runs = Runs::new();+ let claim = runs.claim("a", "j1").unwrap();+ assert!(runs.busy());+ assert!(runs.claim("b", "j2").is_none());+ assert!(!runs.stop_run(Some("b")), "a Cancel for another run");+ assert!(runs.stop_run(Some("a")));+ assert_eq!(start(&runs, Command::new("true"), None).unwrap_err(), STOPPED, "stopped during the cutout: no process");+ drop(claim);+ assert!(!runs.busy());+ assert!(!runs.stop());+ }++ #[cfg(unix)]+ fn shell(script: &str) -> Command {+ let mut cmd = Command::new("/bin/sh");+ cmd.arg("-c").arg(script);+ cmd+ }++ #[cfg(unix)]+ #[test]+ fn a_run_that_writes_its_model_is_complete() {+ let tmp = tempfile::tempdir().unwrap();+ let out = tmp.path().join("m.glb");+ let pid_file = tmp.path().join("run.pid");+ let runs = Runs::new();+ let _claim = runs.claim("r", "j1").unwrap();+ let script = format!(+ "echo 'LU-MESH3D {{\"phase\": \"load\"}}'; echo glTF > '{}'; echo 'LU-MESH3D {{\"phase\": \"done\", \"triangles\": 9}}'",+ out.display()+ );+ let child = start(&runs, shell(&script), Some(&pid_file)).unwrap();+ assert!(pid_file.is_file());+ assert_eq!(finish(&runs, child, &out, Some(&pid_file), Duration::from_secs(30), Duration::from_secs(30)), Ok(()));+ assert!(!pid_file.exists());+ assert_eq!(runs.view().triangles, Some(9));+ assert!(runs.pid().is_none());+ }++ #[cfg(unix)]+ #[test]+ fn a_picture_without_an_object_is_said_in_the_words_of_create() {+ let tmp = tempfile::tempdir().unwrap();+ let out = tmp.path().join("m.glb");+ let runs = Runs::new();+ let _claim = runs.claim("r", "j1").unwrap();+ let script = format!("echo half > '{}'; echo 'LU-MESH3D {{\"phase\": \"error\", \"error\": \"no object\", \"code\": \"no_object\"}}'; exit 6", out.display());+ let child = start(&runs, shell(&script), None).unwrap();+ let verdict = finish(&runs, child, &out, None, Duration::from_secs(30), Duration::from_secs(30));+ assert_eq!(verdict.clone().unwrap_err(), NO_OBJECT);+ assert!(!out.exists(), "half a model is no model");+ runs.conclude(&verdict);+ assert_eq!(runs.view().error_code.as_deref(), Some("no_object"));+ }++ #[cfg(unix)]+ #[test]+ fn cancel_ends_the_process_and_a_hung_run_is_ended_by_the_watch() {+ let tmp = tempfile::tempdir().unwrap();+ let out = tmp.path().join("m.glb");+ let runs = Runs::new();+ let claim = runs.claim("r", "j1").unwrap();+ let child = start(&runs, shell("sleep 30"), None).unwrap();+ let started = Instant::now();+ std::thread::scope(|s| {+ s.spawn(|| {+ std::thread::sleep(Duration::from_millis(300));+ assert!(runs.stop_run(Some("r")));+ });+ assert_eq!(finish(&runs, child, &out, None, Duration::from_secs(60), Duration::from_secs(60)).unwrap_err(), STOPPED);+ });+ assert!(started.elapsed() < Duration::from_secs(10));+ runs.conclude(&Err(STOPPED.to_string()));+ assert_eq!(runs.view().status, "cancelled");+ drop(claim);++ let _claim = runs.claim("r2", "j2").unwrap();+ let child = start(&runs, shell("sleep 30"), None).unwrap();+ let started = Instant::now();+ assert_eq!(finish(&runs, child, &out, None, Duration::from_secs(60), Duration::from_millis(400)).unwrap_err(), HUNG);+ assert!(started.elapsed() < Duration::from_secs(10));+ }++ #[test]+ fn how_a_run_ended_in_words() {+ #[cfg(unix)]+ {+ use std::os::unix::process::ExitStatusExt;+ let ok = std::process::ExitStatus::from_raw(0);+ let code5 = std::process::ExitStatus::from_raw(5 << 8);+ let killed = std::process::ExitStatus::from_raw(9);+ assert_eq!(outcome(Some(&ok), true, None, None, false), Ok(()));+ assert!(outcome(Some(&ok), false, None, None, false).unwrap_err().contains("without writing a model"));+ assert_eq!(outcome(Some(&ok), true, None, None, true).unwrap_err(), STOPPED);+ assert!(outcome(Some(&code5), false, None, None, false).unwrap_err().contains("exit code 5"));+ assert!(outcome(Some(&code5), false, Some("boom"), None, false).unwrap_err().contains("boom"));+ assert!(outcome(Some(&killed), false, None, None, false).unwrap_err().contains("ended by macOS"));+ }+ assert_eq!(outcome(None, false, Some(HUNG), None, false).unwrap_err(), HUNG);+ }++ #[test]+ fn a_run_of_ours_whose_app_is_gone_is_told_from_any_other_process() {+ let work = Path::new("/data/mesh3d/work");+ let row = |parent: Option<u32>, cmd: &[&str]| Leftover { parent, cmd: cmd.iter().map(|s| s.to_string()).collect() };+ let ours = ["/data/mesh3d/venv/bin/python", "-I", "-u", "/data/mesh3d/runner/run_triposr.py", JOB_FLAG, "/data/mesh3d/work/jobs/j1/job.json"];+ assert!(is_orphaned_run(&row(Some(1), &ours), work));+ assert!(!is_orphaned_run(&row(Some(4242), &ours), work));+ assert!(!is_orphaned_run(&row(Some(1), &["python", JOB_FLAG, "/elsewhere/job.json"]), work));+ assert!(!is_orphaned_run(&row(Some(1), &["python", "--lu-acestep-job", "/data/mesh3d/work/j.json"]), work));+ }++ #[test]+ fn a_run_takes_only_a_staged_picture_and_waits_for_the_other_engines() {+ let src = production_source();+ let generate = &src[src.find("pub async fn mesh3d_generate(").unwrap()..src.find("pub fn mesh3d_progress(").unwrap()];+ let staged = generate.find("mlx_cutout::staged_input(").expect("a picture from anywhere on the disk");+ let installed = generate.find("if !installed_at(&root)").unwrap();+ let memory = generate.find("memory_refusal(").unwrap();+ let train = generate.find("train::refusal()").unwrap();+ let image = generate.find("image_engine_busy()").unwrap();+ let video = generate.find("state.video_process()").unwrap();+ let music = generate.find("music::busy()").unwrap();+ let claimed = generate.find("RUNS\n .claim(").unwrap();+ let unload = generate.find("mlx_unload(").unwrap();+ let started = generate.find("start(&RUNS, run_command(").unwrap();+ assert!(staged < installed && installed < memory && memory < train && train < image && image < video && video < music && music < claimed && claimed < unload && unload < started);+ // The other engines wait for a 3D run in turn.+ for (file, src) in [+ ("mlx.rs", include_str!("mlx.rs")),+ ("video.rs", include_str!("video.rs")),+ ("music.rs", include_str!("music.rs")),+ ("mlx_train.rs", include_str!("mlx_train.rs")),+ ] {+ assert!(src.contains("crate::commands::mesh3d::refusal()"), "{file} starts beside a 3D run");+ }+ }+}diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex b1d1c982..386f98da 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -2551,6 +2551,9 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {if let Some(why) = train::refusal() {return Err(crate::commands::bad_request(why));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(crate::commands::bad_request(why));+ }if let Some(too_big) = memory_verdict(entry.name, entry.min_ram_gb, total_memory_bytes()) {return Err(crate::commands::bad_request(too_big));}@@ -3000,6 +3003,9 @@ pub async fn mlx_upscale(_state: &AppState, args: &Value) -> CmdResult {if let Some(why) = train::refusal() {return Err(crate::commands::bad_request(why));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(crate::commands::bad_request(why));+ }if let Some(too_big) = memory_verdict(entry.name, entry.min_ram_gb, total_memory_bytes()) {return Err(crate::commands::bad_request(too_big));}diff --git a/src-tauri/src/commands/mlx_cutout.rs b/src-tauri/src/commands/mlx_cutout.rsindex 32ee7f24..872b98e9 100644--- a/src-tauri/src/commands/mlx_cutout.rs+++ b/src-tauri/src/commands/mlx_cutout.rs@@ -27,21 +27,21 @@ use serde_json::Value;use crate::commands::CmdResult;use crate::state::AppState;-const NO_IMAGE: &str = "Add an image to remove its background.";+pub(crate) const NO_IMAGE: &str = "Add an image to remove its background.";const GONE: &str = "The image to cut out is no longer on disk. Add it again.";-const NO_SUBJECT: &str =+pub(crate) const NO_SUBJECT: &str ="No subject was found in this image, so there is nothing to cut out. Try a picture with a clear main subject.";#[cfg(not(target_os = "macos"))]const MAC_ONLY: &str = "This Remove Background runs on a Mac only. Here it runs through ComfyUI.";/// The folder Create stages an image in before a run reads it/// (`video_stage_start_image`). A cutout takes its image from there alone.-fn staged_images_dir() -> PathBuf {+pub(crate) fn staged_images_dir() -> PathBuf {crate::commands::video::outputs_root().join("start-images")}/// The image of a cutout as it may be read, or the sentence for the user.-fn staged_input(asked: &str, staged: &Path) -> Result<PathBuf, String> {+pub(crate) fn staged_input(asked: &str, staged: &Path) -> Result<PathBuf, String> {if asked.trim().is_empty() {return Err(NO_IMAGE.to_string());}@@ -108,7 +108,7 @@ fn read_upright(path: &Path) -> Result<(image::DynamicImage, bool), String> {/// Cut the subject out of the image at `input` and write the PNG into/// `out_dir`. Answers with the file and its size.#[cfg(target_os = "macos")]-fn cut_out(input: &Path, out_dir: &Path) -> Result<(PathBuf, u32, u32), String> {+pub(crate) fn cut_out(input: &Path, out_dir: &Path) -> Result<(PathBuf, u32, u32), String> {let (picture, turned) = read_upright(input)?;// Vision reads the file as it is stored and the mask has to fit the// pixels read above. A picture that had to be turned is handed overdiff --git a/src-tauri/src/commands/mlx_enhancer.rs b/src-tauri/src/commands/mlx_enhancer.rsindex 2d413b5a..a6062722 100644--- a/src-tauri/src/commands/mlx_enhancer.rs+++ b/src-tauri/src/commands/mlx_enhancer.rs@@ -503,6 +503,9 @@ pub(super) async fn enhance(state: &AppState, args: &Value) -> CmdResult {if let Some(why) = super::train::refusal() {return Err(crate::commands::bad_request(why));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(crate::commands::bad_request(why));+ }if !usable(e) {return Err(crate::commands::bad_request(format!("{} is not installed. Install it in the Model Manager first.", e.name)));}diff --git a/src-tauri/src/commands/mlx_outputs.rs b/src-tauri/src/commands/mlx_outputs.rsindex 5bd57464..e955db17 100644--- a/src-tauri/src/commands/mlx_outputs.rs+++ b/src-tauri/src/commands/mlx_outputs.rs@@ -21,15 +21,21 @@ use crate::commands::CmdResult;use crate::state::AppState;/// What the Mac's engines write: PNG stills (`mlx.rs`, `image_mflux.rs`),-/// MP4 clips (`video.rs`) and WAV tracks (`music.rs`). The other endings are-/// what a later engine may write. Nothing else in these folders is a render.-const MEDIA_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "mp4", "mov", "webm", "wav"];+/// MP4 clips (`video.rs`), WAV tracks (`music.rs`) and GLB models+/// (`mesh3d.rs`). The other endings are what a later engine may write.+/// Nothing else in these folders is a render.+const MEDIA_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "mp4", "mov", "webm", "wav", "glb"];const NOT_OURS: &str = "That gallery entry does not name a file in LU's output folders.";/// The folders a gallery entry of the Mac may name a file in.pub(crate) fn output_roots() -> Vec<PathBuf> {- vec![crate::commands::mlx::images_root(), crate::commands::video::outputs_root(), crate::commands::music::outputs_root()]+ vec![+ crate::commands::mlx::images_root(),+ crate::commands::video::outputs_root(),+ crate::commands::music::outputs_root(),+ crate::commands::mesh3d::outputs_root(),+ ]}/// The file behind a path the interface sent.@@ -135,7 +141,12 @@ mod tests {fn the_folders_are_the_ones_the_engines_write_to_and_playback_reads_from() {assert_eq!(output_roots(),- vec![crate::commands::mlx::images_root(), crate::commands::video::outputs_root(), crate::commands::music::outputs_root()]+ vec![+ crate::commands::mlx::images_root(),+ crate::commands::video::outputs_root(),+ crate::commands::music::outputs_root(),+ crate::commands::mesh3d::outputs_root(),+ ]);// The same three folders `read_media_file` serves: what the gallery// can show is what it can delete.@@ -145,7 +156,8 @@ mod tests {assert!(allowed.contains("crate::commands::video::outputs_root()"));assert!(allowed.contains("crate::commands::mlx::images_root()"));assert!(allowed.contains("crate::commands::music::outputs_root()"));- assert_eq!(allowed.matches("crate::commands::").count(), 3, "read_media_file serves a folder that Delete does not know");+ assert!(allowed.contains("crate::commands::mesh3d::outputs_root()"));+ assert_eq!(allowed.matches("crate::commands::").count(), 4, "read_media_file serves a folder that Delete does not know");}#[test]@@ -160,6 +172,19 @@ mod tests {assert!(resolve(&roots, &s(&music.join("job.json"))).is_err(), "not a render");}+ #[test]+ fn a_model_of_the_3d_engine_resolves_like_a_clip() {+ let tmp = tempfile::tempdir().unwrap();+ let models = tmp.path().join("3d");+ std::fs::create_dir_all(&models).unwrap();+ std::fs::write(models.join("mesh3d-run1.glb"), b"glTF").unwrap();+ std::fs::write(models.join("input.png"), b"png").unwrap();+ std::fs::write(models.join("mesh.obj"), b"v").unwrap();+ let roots = vec![models.clone()];+ assert_eq!(resolve(&roots, &s(&models.join("mesh3d-run1.glb"))).unwrap(), Some(models.canonicalize().unwrap().join("mesh3d-run1.glb")));+ assert!(resolve(&roots, &s(&models.join("mesh.obj"))).is_err(), "not a render of this app");+ }+#[test]fn a_render_in_an_output_folder_resolves_and_nothing_else_does() {let (dir, roots) = layout("mlx-outputs-resolve");diff --git a/src-tauri/src/commands/mlx_train.rs b/src-tauri/src/commands/mlx_train.rsindex a83c6bc8..40f6f50e 100644--- a/src-tauri/src/commands/mlx_train.rs+++ b/src-tauri/src/commands/mlx_train.rs@@ -720,6 +720,9 @@ pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {if crate::commands::music::busy() {return Err(bad_request("A track is being made on this Mac. Wait for it to finish, then train."));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(bad_request(why));+ }if state.video_process().lock().map(|p| p.is_some()).unwrap_or(true) {return Err(bad_request("A video is being generated on this Mac. Wait for it to finish, then train."));}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 35864880..518b48fe 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -58,6 +58,8 @@ pub mod local_api;pub mod local_api_engine;pub mod logging;pub mod media_cmds;+// The local 3D engine of the Mac (TripoSR), see mesh3d.rs.+pub mod mesh3d;pub mod mlx;pub mod mlx_cutout;pub mod mlx_loras;diff --git a/src-tauri/src/commands/music.rs b/src-tauri/src/commands/music.rsindex f6522faa..64f4c9a0 100644--- a/src-tauri/src/commands/music.rs+++ b/src-tauri/src/commands/music.rs@@ -1181,6 +1181,9 @@ pub async fn music_generate(state: &AppState, args: &Value) -> CmdResult {if crate::commands::mlx::image_engine_busy() {return Err(bad_request("An image is being generated on this Mac. Wait for it to finish, then make the track."));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(bad_request(why));+ }if state.video_process().lock().map(|p| p.is_some()).unwrap_or(true) {return Err(bad_request("A video is being generated on this Mac. Wait for it to finish, then make the track."));}diff --git a/src-tauri/src/commands/real_run_mac.rs b/src-tauri/src/commands/real_run_mac.rsindex f43327ca..991ebd5e 100644--- a/src-tauri/src/commands/real_run_mac.rs+++ b/src-tauri/src/commands/real_run_mac.rs@@ -42,10 +42,13 @@//! of a Talking Character run, which makes it the engine's `a2v`),//! `LU_REAL_CANCEL_AFTER` (seconds into an install or a video),//! `LU_REAL_CANCEL_AT_STEP` (an image), `LU_REAL_NAME` (the name the result is-//! kept under), `LU_REAL_OUT` (the folder for results and the record) and-//! `LU_REAL_ANY_POWER` (`1`: do not wait for mains).+//! kept under), `LU_REAL_OUT` (the folder for results and the record),+//! `LU_REAL_ANY_POWER` (`1`: do not wait for mains) and `LU_REAL_RUN_HOME`+//! (an absolute folder the run takes as the app's data, config and cache+//! folders, so the real app's folders on this Mac stay untouched; the 3D+//! runs use it, see `mesh_install`).-use super::{media_cmds, mlx, music, video, CmdResult};+use super::{media_cmds, mesh3d, mlx, music, video, CmdResult};use crate::state::AppState;use serde_json::{json, Value};use std::path::{Path, PathBuf};@@ -63,11 +66,19 @@ fn on() -> bool {return false;}let data = crate::os_paths::data_dir();- assert!(- data.ends_with("Library/Application Support/lu-labs"),- "the real run is not looking at the app's data folder: {}",- data.display()- );+ match crate::os_paths::test_storage::real_run_home() {+ // `LU_REAL_RUN_HOME`: a test folder of its own, never the app's.+ Some(home) => assert!(+ data.starts_with(&home) && !data.to_string_lossy().contains("Library/Application Support"),+ "the real run is not looking at its own folder: {}",+ data.display()+ ),+ None => assert!(+ data.ends_with("Library/Application Support/lu-labs"),+ "the real run is not looking at the app's data folder: {}",+ data.display()+ ),+ }// What the app does at its start: the models an earlier build left in// the cache folder move to the data folder, unless something is at work// on them (a running app's download shows on its command line).@@ -386,6 +397,17 @@ fn music_lane() -> Lane {}}+/// The 3D lane installs its engine, its source and its weights on one slot.+fn mesh_lane() -> Lane {+ Lane {+ name: "mesh3d",+ install: mesh3d::mesh3d_install,+ status: mesh3d::mesh3d_install_status,+ cancel: mesh3d::mesh3d_cancel_install,+ weights: crate::os_paths::data_dir().join("mesh3d").join("weights"),+ }+}+fn video_lane() -> Lane {Lane {name: "video",@@ -1232,3 +1254,138 @@ fn train_run() {assert_eq!(last["status"], "complete", "the training did not complete: {}", last["error"]);}}++// ── 3D ────────────────────────────────────────────────────────────────++/// The 3D runs write only below `LU_REAL_RUN_HOME`: they are not to touch+/// the app's own folders on this Mac.+fn own_folder_only() -> bool {+ if crate::os_paths::test_storage::real_run_home().is_none() {+ eprintln!("the 3D real run needs LU_REAL_RUN_HOME, an absolute folder of its own");+ return false;+ }+ true+}++/// The install of the 3D lane: LU's Python, the venv, the TripoSR source and+/// the weights. `LU_REAL_MODEL` is `triposr`, the one entry.+///+/// ```sh+/// LU_REAL_RUN=1 LU_REAL_RUN_HOME=/path/to/test LU_REAL_MODEL=triposr \+/// cargo test real_run_mac::mesh_install -- --ignored --nocapture --test-threads=1+/// ```+#[test]+#[ignore = "the real run: needs LU_REAL_RUN=1"]+fn mesh_install() {+ if on() && own_folder_only() {+ install_model(mesh_lane());+ let root = mesh3d::real_run_root();+ record("mesh3d folders", json!({ "venvGB": dir_gb(&root.join("venv")), "weightsGB": dir_gb(&root.join("weights")), "sourceGB": dir_gb(&root.join("source")) }));+ }+}++/// One model from one picture, as Create makes it: the picture of+/// `LU_REAL_IMAGES` staged, then `mlx_mesh3d_generate` with the argument+/// object of `generateMesh3d` in `src/api/mlx-3d.ts`, then the progress every+/// second until it is through. `LU_REAL_RESOLUTION` is the grid,+/// `LU_REAL_CANCEL_AFTER` stops it on the way and then looks that no process+/// of the run is left.+#[test]+#[ignore = "the real run: needs LU_REAL_RUN=1"]+fn mesh_run() {+ if !on() || !own_folder_only() {+ return;+ }+ let state = state();+ let none = json!({});+ let name = var("LU_REAL_NAME").unwrap_or_else(|| "mesh-run".to_string());+ wait_for_mains();+ let status = mesh3d::mesh3d_status(state, &none).expect("mlx_mesh3d_status");+ assert_eq!(status["installed"], true, "the 3D model is not installed: {status}");+ let picture = var("LU_REAL_IMAGES").expect("LU_REAL_IMAGES names the picture");+ let staged = stage(&picture);+ let run = format!("real-run-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));+ let mut args = json!({ "run": run, "imagePath": staged });+ if let Some(resolution) = number::<u32>("LU_REAL_RESOLUTION") {+ args["resolution"] = json!(resolution);+ }+ println!("mlx_mesh3d_generate {args}");+ let available_before = available_memory_gb();+ let started = Instant::now();+ let answer = runtime().block_on(mesh3d::mesh3d_generate(state, &args));+ let Ok(job) = answer else {+ record(&format!("mesh3d {name}"), json!({ "args": args, "error": answer.unwrap_err() }));+ panic!("mlx_mesh3d_generate refused");+ };+ let sampler = sample_memory(move || mesh3d::mesh3d_progress(state, &json!({})).ok().and_then(|p| p["pid"].as_u64()).map(|p| p as u32));+ let cancel_after = number::<u64>("LU_REAL_CANCEL_AFTER");+ let mut stop = Value::Null;+ let mut printed = String::new();+ let mut seen_pid = None::<u32>;+ let last = loop {+ let p = mesh3d::mesh3d_progress(state, &none).expect("mlx_mesh3d_progress");+ if let Some(pid) = p["pid"].as_u64() {+ seen_pid = Some(pid as u32);+ }+ let line = format!("{} {}% {} {}", p["phase"], p["percent"], p["detail"], p["device"]);+ if line != printed {+ println!("[{:>6.1}s] {line}", seconds(started));+ printed = line;+ }+ if p["running"] != true {+ break p;+ }+ if stop.is_null() && cancel_after.is_some_and(|after| started.elapsed() >= Duration::from_secs(after)) {+ let children = descendants();+ let at = Instant::now();+ let answer = mesh3d::mesh3d_cancel(state, &json!({ "run": run })).unwrap_or_else(|e| json!({ "ERROR": e }));+ let mut gone = None::<u64>;+ while at.elapsed() < Duration::from_secs(30) && gone.is_none() {+ if children.iter().all(|(pid, _)| !alive(*pid)) {+ gone = Some(ms(at));+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ stop = json!({+ "afterSeconds": cancel_after,+ "phaseAtStop": p["phase"],+ "cancelAnswer": answer,+ "children": children.iter().map(|(pid, command)| format!("{pid} {}", shorten(command))).collect::<Vec<_>>(),+ "processesGoneMs": gone,+ "survivors": children.iter().filter(|(pid, _)| alive(*pid)).map(|(pid, _)| *pid).collect::<Vec<_>>(),+ });+ }+ std::thread::sleep(Duration::from_secs(1));+ };+ let memory = sampler.finish();+ let output = job["output"].as_str().unwrap_or("").to_string();+ let left = descendants();+ let mut result = json!({+ "args": args,+ "job": job,+ "seconds": seconds(started),+ "progress": last,+ "view": mesh3d::real_run_view(),+ "memory": memory,+ "availableBeforeGB": available_before,+ "availableAfterGB": available_memory_gb(),+ "stop": stop,+ "pid": seen_pid,+ "processesLeft": left.iter().map(|(pid, command)| format!("{pid} {}", shorten(command))).collect::<Vec<_>>(),+ "outputBytes": std::fs::metadata(&output).map(|m| m.len()).ok(),+ });+ if Path::new(&output).is_file() {+ let kept = out_dir().join(format!("{name}.glb"));+ std::fs::copy(&output, &kept).expect("keep the model");+ result["kept"] = json!(kept);+ }+ record(&format!("mesh3d {name}"), result);+ assert!(seen_pid.is_none_or(|pid| !alive(pid)), "the engine's process outlived the run");+ if cancel_after.is_some() {+ assert_eq!(last["status"], "cancelled", "the run was not cancelled: {}", last["error"]);+ assert!(!Path::new(&output).is_file(), "a cancelled run left a model behind");+ assert!(left.is_empty(), "a process of the run is left: {left:?}");+ } else {+ assert_eq!(last["status"], "complete", "the model did not complete: {}", last["error"]);+ }+}diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rsindex 1daacdb5..0d91dc58 100644--- a/src-tauri/src/commands/video.rs+++ b/src-tauri/src/commands/video.rs@@ -2208,6 +2208,9 @@ pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {if let Some(why) = crate::commands::mlx::train::refusal() {return Err(bad_request(why));}+ if let Some(why) = crate::commands::mesh3d::refusal() {+ return Err(bad_request(why));+ }let a: GenerateArgs =serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;let entry = catalog_lookup(&a.id)diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e02067f3..0c7890ef 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1098,6 +1098,23 @@ pub fn run() {commands::media_cmds::mlx_music_progress,#[cfg(desktop)]commands::media_cmds::mlx_music_cancel,+ // The 3D engine of the Mac (TripoSR). See commands/mesh3d.rs.+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_status,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_install,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_install_status,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_cancel_install,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_delete,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_generate,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_progress,+ #[cfg(desktop)]+ commands::media_cmds::mlx_mesh3d_cancel,#[cfg(desktop)]commands::media_cmds::mlx_train_status,#[cfg(desktop)]@@ -1604,6 +1621,11 @@ pub fn run() {if let Some(pid) = commands::music::reap_orphaned_run() {tracing::warn!(target: "music", pid, "ended a track orphaned by a previous run");}+ // And a 3D model of the 3D engine, the same way.+ #[cfg(target_os = "macos")]+ if let Some(pid) = commands::mesh3d::reap_orphaned_run() {+ tracing::warn!(target: "mesh3d", pid, "ended a 3D run orphaned by a previous run");+ }// And a character training, the same way.#[cfg(target_os = "macos")]if let Some(pid) = commands::mlx::train::reap_orphaned_run() {diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rsindex a6844be2..512f1b40 100644--- a/src-tauri/src/os_paths.rs+++ b/src-tauri/src/os_paths.rs@@ -285,21 +285,40 @@ pub(crate) mod test_storage {})}+ /// A folder of its own for the real run instead of the app's folders on+ /// this Mac: `LU_REAL_RUN_HOME`, an absolute path. Read only in the real+ /// run, and only in a test build: a release build has no such switch.+ /// The data and the config folder are one there, as on a Mac, the cache+ /// is beside them.+ pub fn real_run_home() -> Option<PathBuf> {+ if !real_run() {+ return None;+ }+ std::env::var_os("LU_REAL_RUN_HOME").map(PathBuf::from).filter(|p| p.is_absolute())+ }+/// The three folders the media engines live in are the app's own in the- /// real run. Everything else (settings, stores, workspace) stays scratch.- fn real(dir: Option<PathBuf>) -> Option<PathBuf> {- if real_run() { dir.map(|d| d.join(APP_DIR)) } else { None }+ /// real run, or those under `LU_REAL_RUN_HOME` when it names one.+ /// Everything else (settings, stores, workspace) stays scratch.+ fn real(dir: Option<PathBuf>, kind: &str) -> Option<PathBuf> {+ if !real_run() {+ return None;+ }+ match real_run_home() {+ Some(home) => Some(home.join(kind).join(APP_DIR)),+ None => dir.map(|d| d.join(APP_DIR)),+ }}pub fn data_dir() -> PathBuf {- real(dirs::data_local_dir()).unwrap_or_else(|| root().join("local").join(APP_DIR))+ real(dirs::data_local_dir(), "support").unwrap_or_else(|| root().join("local").join(APP_DIR))}pub fn cache_dir() -> PathBuf {- real(dirs::cache_dir())+ real(dirs::cache_dir(), "cache").unwrap_or_else(|| root().join(if cfg!(windows) { "local" } else { "cache" }).join(APP_DIR))}pub fn config_root() -> PathBuf {- real(dirs::config_dir()).unwrap_or_else(|| config_base().join(APP_DIR))+ real(dirs::config_dir(), "support").unwrap_or_else(|| config_base().join(APP_DIR))}pub fn app_config_dir() -> PathBuf { config_base().join(APP_CONFIG_DIR) }pub fn tools_bin_dir() -> PathBuf { root().join("local").join(APP_CONFIG_DIR).join("bin") }@@ -317,6 +336,8 @@ pub(crate) mod test_storage {assert_eq!(data_dir(), std::thread::spawn(data_dir).join().unwrap());if cfg!(target_os = "macos") { assert_eq!(data_dir(), config_root()); }if cfg!(windows) { assert_eq!(data_dir(), cache_dir()); }+ // Outside the real run the switch of its own folder is not read.+ assert_eq!(real_run_home(), None);}#[test]diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 0b0e89d9..166c96e5 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -448,6 +448,9 @@ pub struct AppState {/// Install progress of the Mac's music engine and its weights/// (`commands::music`), one slot for both.pub install_music: crate::install_state::InstallSlot,+ /// Install progress of the Mac's 3D engine, its source and its weights+ /// (`commands::mesh3d`), one slot for all three.+ pub install_mesh3d: crate::install_state::InstallSlot,/// Live progress/log of the currently running (or last) video generation.pub video_progress: crate::install_state::InstallSlot,/// Handle to the running `mlx_video.*.generate` subprocess, if any. `Arc`-@@ -546,6 +549,7 @@ impl AppState {install_mlx_video: crate::install_state::InstallSlot::default(),install_video_model: crate::install_state::InstallSlot::default(),install_music: crate::install_state::InstallSlot::default(),+ install_mesh3d: crate::install_state::InstallSlot::default(),video_progress: crate::install_state::InstallSlot::default(),video_process: Arc::new(Mutex::new(None)),}@@ -572,6 +576,9 @@ impl AppState {pub fn install_music(&self) -> crate::install_state::InstallSlot {self.install_music.clone()}+ pub fn install_mesh3d(&self) -> crate::install_state::InstallSlot {+ self.install_mesh3d.clone()+ }pub fn video_progress(&self) -> crate::install_state::InstallSlot {self.video_progress.clone()}@@ -608,6 +615,7 @@ impl AppState {&self.install_mlx_video,&self.install_video_model,&self.install_music,+ &self.install_mesh3d,].into_iter().filter(|slot| slot.cancel())@@ -752,6 +760,8 @@ impl AppState {// A track holds its models as a process of its own, like an image of// the second engine.crate::commands::music::stop();+ // And a 3D model of the Mac's 3D engine, the same way.+ crate::commands::mesh3d::stop();// And a character training, the same way.crate::commands::mlx::train::stop();// Only a sidecar of THIS app (its server.py, started by this processdiff --git a/src/api/backend.ts b/src/api/backend.tsindex 98af7ffb..67bf0cb5 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -592,6 +592,16 @@ export async function backendCall<T = unknown>(mlx_music_generate: { path: "/local-api/mlx-music-generate", method: "POST" },mlx_music_progress: { path: "/local-api/mlx-music-progress" },mlx_music_cancel: { path: "/local-api/mlx-music-cancel", method: "POST" },+ // The 3D engine of the Mac (commands/mesh3d.rs, 3.1.0), desktop only:+ // the dev server answers 501 (mlx-media-stubs.ts).+ mlx_mesh3d_status: { path: "/local-api/mlx-mesh3d-status" },+ mlx_mesh3d_install: { path: "/local-api/mlx-mesh3d-install", method: "POST" },+ mlx_mesh3d_install_status: { path: "/local-api/mlx-mesh3d-install-status" },+ mlx_mesh3d_cancel_install: { path: "/local-api/mlx-mesh3d-cancel-install", method: "POST" },+ mlx_mesh3d_delete: { path: "/local-api/mlx-mesh3d-delete", method: "POST" },+ mlx_mesh3d_generate: { path: "/local-api/mlx-mesh3d-generate", method: "POST" },+ mlx_mesh3d_progress: { path: "/local-api/mlx-mesh3d-progress" },+ mlx_mesh3d_cancel: { path: "/local-api/mlx-mesh3d-cancel", method: "POST" },mlx_train_status: { path: "/local-api/mlx-train-status" },mlx_train_stage: { path: "/local-api/mlx-train-stage", method: "POST" },mlx_train_clear: { path: "/local-api/mlx-train-clear", method: "POST" },diff --git a/src/api/mlx-3d.ts b/src/api/mlx-3d.tsnew file mode 100644index 00000000..de02336d--- /dev/null+++ b/src/api/mlx-3d.ts@@ -0,0 +1,218 @@+/**+ * The 3D engine of the Mac: TripoSR, run by Rust as a Python process of its+ * own per model (`src-tauri/src/commands/mesh3d.rs`). One picture of one+ * object in, one GLB with colours per vertex out, written to `<outputs>/3d`.+ *+ * Public API, for `useCreate.ts`:+ *+ * getMesh3dStatus() -> Mesh3dStatus installed, running, model card+ * installMesh3d() -> starts engine + source + weights, one slot+ * getMesh3dInstallStatus() -> MlxInstallStatus (poll like the music install)+ * cancelMesh3dInstall() -> stops it; what was fetched stays+ * deleteMesh3dModel() -> removes the weights, the engine stays+ * generateMesh3d({ run, imagePath, resolution?, cutout? }) -> Mesh3dStarted+ * getMesh3dProgress() -> Mesh3dProgress (phase, percent, error, ...)+ * cancelMesh3d(run) -> ends that run and its process+ *+ * runMacMesh3d({ imagePath, resolution?, cutout? }, { signal?, onProgress? })+ * -> Promise<{ path, bytes, triangles?, seconds }>+ * Starts a run, polls until it is through, rejects with+ * `Mesh3dRunCancelled` when `signal` aborts (Rust ends the process) and+ * with an Error in the user's words otherwise. A picture without an+ * object rejects with `Mesh3dNoObject`.+ *+ * mesh3dRunLine(progress, elapsedSec) -> the line under the progress bar+ *+ * `imagePath` must be a picture staged by Create (`video_stage_start_image`,+ * the `start-images` folder): Rust takes no other path. `cutout` (default+ * true) cuts the object out with Vision first; a transparent picture is+ * never cut again. `resolution` is the grid side (see `mac3dResolution`).+ * The GLB is served by `read_media_file` and moved to the Trash by+ * `mlx_output_trash` like every other render of the Mac.+ */+import { invokeMedia } from './mlx-invoke'+import type { MlxInstallStatus } from './mlx-image'+import { MESH3D_NO_OBJECT, mesh3dRunLine } from '../lib/mac-3d'++export { MAC_3D_MODEL_ID, MAC_3D_MODEL_NAME, MAC_3D_RESOLUTION, MESH3D_PHASE_TEXT, mac3dResolution, mesh3dRunLine } from '../lib/mac-3d'+export type { Mac3dDetail, Mesh3dPhase } from '../lib/mac-3d'++/** The one catalogue entry, in the fields `mesh3d_status` sends. */+export interface Mesh3dModel {+ id: string+ name: string+ repo: string+ sizeGB: number+ minRamGB: number+ unfiltered: boolean+ description: string+ installed: boolean+}++export interface Mesh3dStatus {+ available: boolean+ appleSilicon: boolean+ engineInstalled: boolean+ engineCommit: string+ /** Engine, source and weights. */+ installed: boolean+ running: boolean+ outputsRoot: string+ model: Mesh3dModel+}++export interface Mesh3dProgress {+ job: string | null+ run: string | null+ status: 'idle' | 'running' | 'complete' | 'error' | 'cancelled'+ /** load, cutout, shape, paint or save. */+ phase: string+ detail: string+ percent: number+ error: string | null+ /** 'no_object' when no object was found in the picture. */+ errorCode: string | null+ output: string | null+ triangles: number | null+ vertices: number | null+ /** 'mps' or 'cpu'. */+ device: string | null+ logs: string[]+ running: boolean+ pid: number | null+ /** Size of the GLB, once the run is complete. */+ bytes?: number+}++export interface Mesh3dRequest {+ /** A picture staged by Create. */+ imagePath: string+ resolution?: number+ cutout?: boolean+}++export interface Mesh3dStarted {+ ok: boolean+ jobId: string+ run: string+ output: string+ resolution: number+ cutout: boolean+}++export async function getMesh3dStatus(): Promise<Mesh3dStatus> {+ return invokeMedia<Mesh3dStatus>('mlx_mesh3d_status')+}++export async function installMesh3d(): Promise<{ ok: boolean; status: string; id?: string }> {+ return invokeMedia('mlx_mesh3d_install')+}++export async function getMesh3dInstallStatus(): Promise<MlxInstallStatus> {+ return invokeMedia<MlxInstallStatus>('mlx_mesh3d_install_status')+}++export async function cancelMesh3dInstall(): Promise<{ ok: boolean; cancelled: boolean }> {+ return invokeMedia('mlx_mesh3d_cancel_install')+}++export async function deleteMesh3dModel(): Promise<{ ok: boolean; id: string }> {+ return invokeMedia('mlx_mesh3d_delete')+}++export async function generateMesh3d(request: Mesh3dRequest & { run: string }): Promise<Mesh3dStarted> {+ const args: Record<string, unknown> = { run: request.run, imagePath: request.imagePath }+ if (request.resolution !== undefined) args.resolution = request.resolution+ if (request.cutout !== undefined) args.cutout = request.cutout+ return invokeMedia<Mesh3dStarted>('mlx_mesh3d_generate', args)+}++export async function getMesh3dProgress(): Promise<Mesh3dProgress> {+ return invokeMedia<Mesh3dProgress>('mlx_mesh3d_progress')+}++export async function cancelMesh3d(run: string): Promise<{ ok: boolean; stopped: boolean }> {+ return invokeMedia('mlx_mesh3d_cancel', { run })+}++/** A run that was stopped by the user. Not an error to show. */+export class Mesh3dRunCancelled extends Error {+ constructor() {+ super('Cancelled')+ this.name = 'Mesh3dRunCancelled'+ }+}++/** No object was found in the picture. The message is the app's sentence. */+export class Mesh3dNoObject extends Error {+ constructor() {+ super(MESH3D_NO_OBJECT)+ this.name = 'Mesh3dNoObject'+ }+}++export interface Mesh3dResult {+ /** The GLB on disk, for `read_media_file` and the gallery. */+ path: string+ bytes: number+ triangles?: number+ seconds: number+}++const POLL_MS = 1000++let runs = 0++async function pause(ms: number, signal?: AbortSignal): Promise<boolean> {+ if (signal?.aborted) return false+ return new Promise<boolean>((resolve) => {+ const done = (ok: boolean) => {+ clearTimeout(timer)+ signal?.removeEventListener('abort', aborted)+ resolve(ok)+ }+ const aborted = () => done(false)+ const timer = setTimeout(() => done(true), ms)+ signal?.addEventListener('abort', aborted, { once: true })+ })+}++/**+ * Make one model and wait for it. `signal` stops the run: Rust ends the+ * engine's process, and this rejects with `Mesh3dRunCancelled`.+ */+export async function runMacMesh3d(+ request: Mesh3dRequest,+ watch: { signal?: AbortSignal; onProgress?: (percent: number, text: string) => void; now?: () => number } = {},+): Promise<Mesh3dResult> {+ const now = watch.now ?? Date.now+ const run = `mesh3d-${now()}-${++runs}`+ const started = now()+ const job = await generateMesh3d({ ...request, run })+ const stop = async (): Promise<never> => {+ try { await cancelMesh3d(run) } catch { /* already over */ }+ throw new Mesh3dRunCancelled()+ }+ if (watch.signal?.aborted) return stop()+ for (;;) {+ if (!(await pause(POLL_MS, watch.signal))) return stop()+ const p = await getMesh3dProgress()+ const seconds = Math.round((now() - started) / 1000)+ // A poll may still see the run before this one.+ if (p.job && p.job !== job.jobId) continue+ watch.onProgress?.(Math.min(99, p.percent), mesh3dRunLine(p, seconds))+ if (p.status === 'complete') {+ return {+ path: p.output || job.output,+ bytes: p.bytes ?? 0,+ triangles: p.triangles ?? undefined,+ seconds,+ }+ }+ if (p.status === 'cancelled') throw new Mesh3dRunCancelled()+ if (p.status === 'error') {+ if (p.errorCode === 'no_object') throw new Mesh3dNoObject()+ throw new Error(p.error || 'The 3D engine stopped without a model.')+ }+ }+}diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 5bbf445e..b4492533 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -1,7 +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 { MAC_3D_MODEL, 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'@@ -213,7 +213,7 @@ async function runLocalThreeD(state: CreateState, seed: number, abortRef: { currconst 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 },+ { imagePath: staged, resolution: api.mac3dResolution(state.threeDDetail), cutout: state.threeDCutout },{ signal: own.signal, onProgress: (percent, text) => onProgress(percent, text) },)if (own.signal.aborted) return@@ -236,7 +236,12 @@ async function runLocalThreeD(state: CreateState, seed: number, abortRef: { curruseCreateStore.getState().setProgressPhase('complete')setProgress(100, 'Complete!')} catch (e) {- if (!own.signal.aborted) {+ const name = e instanceof Error ? e.name : ''+ if (own.signal.aborted || name === 'Mesh3dRunCancelled') {+ // Stopped by the user: nothing to say.+ } else if (name === 'Mesh3dNoObject') {+ useCreateStore.getState().setError(THREE_D_TEXT.noObject)+ } else {useCreateStore.getState().setError(`3D failed: ${e instanceof Error ? e.message : String(e)}`)}} finally {diff --git a/src/lib/__tests__/mac-3d.test.ts b/src/lib/__tests__/mac-3d.test.tsnew file mode 100644index 00000000..e0db1f1e--- /dev/null+++ b/src/lib/__tests__/mac-3d.test.ts@@ -0,0 +1,177 @@+/**+ * One model of the Mac's 3D engine, as Create waits for it+ * (api/mlx-3d.ts runMacMesh3d over commands/mesh3d.rs), and the words of+ * its progress line (lib/mac-3d.ts).+ *+ * The commands are mocked: what is held here is what goes to Rust, how the+ * polls are read, and that a Stop reaches the run it was meant for.+ *+ * Run: npx vitest run src/lib/__tests__/mac-3d.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++const rust = vi.hoisted(() => ({+ calls: [] as { cmd: string; args?: Record<string, unknown> }[],+ polls: [] as Record<string, unknown>[],+}))+vi.mock('../../api/mlx-invoke', () => ({+ invokeMedia: vi.fn(async (cmd: string, args?: Record<string, unknown>) => {+ rust.calls.push({ cmd, args })+ if (cmd === 'mlx_mesh3d_generate') {+ return { ok: true, jobId: 'j1', run: args?.run, output: '/c/3d/r.glb', resolution: args?.resolution ?? 256, cutout: args?.cutout ?? true }+ }+ if (cmd === 'mlx_mesh3d_progress') return rust.polls.shift() ?? poll('running')+ if (cmd === 'mlx_mesh3d_cancel') return { ok: true, stopped: true }+ if (cmd.startsWith('mlx_mesh3d_')) return { ok: true }+ throw new Error(`unexpected ${cmd}`)+ }),+}))++import {+ runMacMesh3d,+ generateMesh3d,+ getMesh3dStatus,+ installMesh3d,+ getMesh3dInstallStatus,+ cancelMesh3dInstall,+ deleteMesh3dModel,+ cancelMesh3d,+ Mesh3dRunCancelled,+ Mesh3dNoObject,+} from '../../api/mlx-3d'+import { mesh3dRunLine, mac3dResolution, MESH3D_PHASE_TEXT, MAC_3D_MODEL_NAME, MESH3D_NO_OBJECT } from '../mac-3d'++function poll(status: string, extra: Record<string, unknown> = {}) {+ return { job: 'j1', run: 'r', status, phase: 'shape', detail: '', percent: 40, error: null, errorCode: null, output: '/c/3d/r.glb', triangles: null, vertices: null, device: 'mps', logs: [], running: status === 'running', pid: 7, ...extra }+}++beforeEach(() => {+ vi.useFakeTimers()+ rust.calls.length = 0+ rust.polls.length = 0+})+afterEach(() => {+ vi.useRealTimers()+})++async function settle<T>(p: Promise<T>): Promise<T> {+ const out = p.then((value) => ({ value }), (error: unknown) => ({ error }))+ for (let i = 0; i < 20; i++) await vi.advanceTimersByTimeAsync(1000)+ const r = await out+ if ('error' in r) throw r.error+ return r.value+}++describe('the progress line', () => {+ it('says each phase in the words of the plan', () => {+ expect(Object.values(MESH3D_PHASE_TEXT)).toEqual([+ 'Getting the model ready…',+ 'Cutting out your object…',+ 'Building the shape…',+ 'Painting the surface…',+ 'Saving your model…',+ ])+ expect(mesh3dRunLine({ phase: 'cutout' }, 3)).toBe('Cutting out your object… (3s)')+ expect(mesh3dRunLine({ phase: 'paint' }, 41.6)).toBe('Painting the surface… (42s)')+ expect(mesh3dRunLine({ phase: 'something new' }, 0)).toBe('Getting the model ready… (0s)')+ expect(mesh3dRunLine({ phase: null }, -2)).toBe('Getting the model ready… (0s)')+ })++ it('no text has a dash, a German word or a closing phrase', () => {+ for (const text of [...Object.values(MESH3D_PHASE_TEXT), MESH3D_NO_OBJECT]) {+ expect(text).not.toMatch(new RegExp(`[${String.fromCharCode(0x2013, 0x2014)}]| - `))+ expect(text).not.toMatch(/should work|hope|enjoy/i)+ }+ })++ it('maps Detail to the grid Rust takes', () => {+ expect(mac3dResolution('draft')).toBe(128)+ expect(mac3dResolution('standard')).toBe(256)+ expect(mac3dResolution('fine')).toBe(384)+ expect(mac3dResolution(undefined)).toBe(256)+ // Rust's bounds and steps (resolution_for in mesh3d.rs).+ const rs = readFileSync(join(__dirname, '../../../src-tauri/src/commands/mesh3d.rs'), 'utf8')+ expect(rs).toContain('const MIN_RESOLUTION: u32 = 64;')+ expect(rs).toContain('const MAX_RESOLUTION: u32 = 384;')+ expect(rs).toContain(`pub(crate) const MODEL_NAME: &str = "${MAC_3D_MODEL_NAME}";`)+ expect(rs).toContain(`const NO_OBJECT: &str = "${MESH3D_NO_OBJECT}";`)+ for (const phase of Object.keys(MESH3D_PHASE_TEXT)) expect(rs).toContain(`"${phase}"`)+ })+})++describe('the commands', () => {+ it('each wrapper calls its Rust command, and only those of media_cmds.rs', async () => {+ await getMesh3dStatus()+ await installMesh3d()+ await getMesh3dInstallStatus()+ await cancelMesh3dInstall()+ await deleteMesh3dModel()+ await cancelMesh3d('r9')+ const names = rust.calls.map((c) => c.cmd)+ expect(names).toEqual(['mlx_mesh3d_status', 'mlx_mesh3d_install', 'mlx_mesh3d_install_status', 'mlx_mesh3d_cancel_install', 'mlx_mesh3d_delete', 'mlx_mesh3d_cancel'])+ expect(rust.calls.at(-1)!.args).toEqual({ run: 'r9' })+ const media = readFileSync(join(__dirname, '../../../src-tauri/src/commands/media_cmds.rs'), 'utf8')+ const lib = readFileSync(join(__dirname, '../../../src-tauri/src/lib.rs'), 'utf8')+ for (const name of [...names, 'mlx_mesh3d_generate', 'mlx_mesh3d_progress']) {+ expect(media).toContain(`pub async fn ${name}(`)+ expect(lib).toContain(`commands::media_cmds::${name},`)+ }+ })++ it('generate sends the run, the staged picture, and the options only when set', async () => {+ await generateMesh3d({ run: 'r', imagePath: '/s/start-images/a.png' })+ expect(rust.calls[0].args).toEqual({ run: 'r', imagePath: '/s/start-images/a.png' })+ await generateMesh3d({ run: 'r', imagePath: '/s/a.png', resolution: 128, cutout: false })+ expect(rust.calls[1].args).toEqual({ run: 'r', imagePath: '/s/a.png', resolution: 128, cutout: false })+ })+})++describe('a run', () => {+ it('reports the phases and ends with the path, the size and the triangles', async () => {+ rust.polls.push(poll('running', { phase: 'cutout', percent: 2 }), poll('running', { phase: 'paint', percent: 82 }), poll('complete', { percent: 100, phase: 'save', bytes: 4096, triangles: 51234 }))+ const seen: [number, string][] = []+ const result = await settle(runMacMesh3d({ imagePath: '/s/a.png', resolution: 256 }, { onProgress: (p, t) => seen.push([p, t]) }))+ const start = rust.calls.find((c) => c.cmd === 'mlx_mesh3d_generate')!+ expect(String(start.args?.run)).toMatch(/^mesh3d-\d+-\d+$/)+ expect(result).toEqual({ path: '/c/3d/r.glb', bytes: 4096, triangles: 51234, seconds: expect.any(Number) })+ expect(seen[0][1]).toMatch(/^Cutting out your object… \(\d+s\)$/)+ expect(seen[1][1]).toMatch(/^Painting the surface…/)+ expect(seen.every(([p]) => p <= 99)).toBe(true)+ })++ it('a poll of the run before this one is not this one', async () => {+ rust.polls.push(poll('complete', { job: 'older' }), poll('complete', { bytes: 1 }))+ const result = await settle(runMacMesh3d({ imagePath: '/s/a.png' }))+ expect(result.bytes).toBe(1)+ expect(rust.calls.filter((c) => c.cmd === 'mlx_mesh3d_progress')).toHaveLength(2)+ })++ it('a picture without an object rejects in the words of Create', async () => {+ rust.polls.push(poll('error', { error: MESH3D_NO_OBJECT, errorCode: 'no_object' }))+ await expect(settle(runMacMesh3d({ imagePath: '/s/a.png' }))).rejects.toBeInstanceOf(Mesh3dNoObject)+ })++ it('any other failure says why', async () => {+ rust.polls.push(poll('error', { error: 'The 3D engine stopped: out of memory' }))+ await expect(settle(runMacMesh3d({ imagePath: '/s/a.png' }))).rejects.toThrow('out of memory')+ })++ it('a Stop ends the run it was meant for and rejects as cancelled', async () => {+ const stop = new AbortController()+ const running = runMacMesh3d({ imagePath: '/s/a.png' }, { signal: stop.signal })+ const outcome = running.then(() => 'done', (e: unknown) => e)+ await vi.advanceTimersByTimeAsync(1000)+ stop.abort()+ await vi.advanceTimersByTimeAsync(10)+ expect(await outcome).toBeInstanceOf(Mesh3dRunCancelled)+ const run = rust.calls.find((c) => c.cmd === 'mlx_mesh3d_generate')!.args!.run+ expect(rust.calls.find((c) => c.cmd === 'mlx_mesh3d_cancel')!.args).toEqual({ run })+ })++ it('a run Rust reports as cancelled rejects as cancelled', async () => {+ rust.polls.push(poll('cancelled'))+ await expect(settle(runMacMesh3d({ imagePath: '/s/a.png' }))).rejects.toBeInstanceOf(Mesh3dRunCancelled)+ })+})diff --git a/src/lib/__tests__/mac-engine-pins.test.ts b/src/lib/__tests__/mac-engine-pins.test.tsindex af4b426a..fac21a4b 100644--- a/src/lib/__tests__/mac-engine-pins.test.ts+++ b/src/lib/__tests__/mac-engine-pins.test.ts@@ -1,15 +1,15 @@/**- * The pins of the four Mac media engines have one home each.+ * The pins of the five Mac media engines have one home each.** `macos-gate` in ci.yml asks pip whether the engines' packages still* resolve (`scripts/mac-engine-pins-dry-run.sh`). The lists it asks about* are read by `scripts/mac-engine-pins.mjs` from the places the app itself- * installs from: three Rust files and one requirements file. Nothing is+ * installs from: four Rust files and one requirements file. Nothing is* copied, so nothing can drift between a copy and its original. What CAN* happen is that a Rust file changes shape and the reader reads less than* is there, or nothing. This file holds that the reader then stops:*- * 1. against the working tree it finds all four engines, every entry an+ * 1. against the working tree it finds all five engines, every entry an* exact pin or a pinned archive, and the lists are what the Rust code* builds (array lengths, the archive addresses);* 2. it refuses a source whose shape it does not know: a missing constant,@@ -40,8 +40,8 @@ const engines = readEnginePins()const byId = (id: string) => engines.find((e) => e.id === id)!describe('the working tree', () => {- it('yields the four engines, in a fixed order', () => {- expect(engines.map((e) => e.id)).toEqual(['image', 'mflux', 'mlx-video', 'ltx-2-mlx'])+ it('yields the five engines, in a fixed order', () => {+ expect(engines.map((e) => e.id)).toEqual(['image', 'mflux', 'mlx-video', 'ltx-2-mlx', 'mesh3d'])for (const engine of engines) expect(engine.source).toBe(SOURCES[engine.id])})@@ -93,6 +93,19 @@ describe('the working tree', () => {expect(source).toContain(`format!("${LTX_SPEC_TEMPLATE}")`)})+ it('reads the 3D engine as exactly the PINNED array of mesh3d.rs, wheels only', () => {+ const source = read(SOURCES.mesh3d)+ const declared = Number(source.match(/const PINNED: \[&str; (\d+)\]/)![1])+ const specs = byId('mesh3d').specs+ expect(specs).toHaveLength(declared)+ // Every entry is name==version: the second pass of the dry run checks all+ // of them for wheels on the oldest macOS.+ expect(specs.every((s) => !s.includes(' @ '))).toBe(true)+ // torch is the one the music engine installs, so the wheel is fetched once.+ expect(specs).toContain('torch==2.10.0')+ expect(specs.some((s) => s.startsWith('torchmcubes') || s.startsWith('rembg'))).toBe(false)+ })+it('takes the Python line from python.json', () => {expect(pythonLine()).toMatch(/^3\.\d+$/)expect(JSON.parse(read('src-tauri/resources/voice_loop/python.json')).version.startsWith(pythonLine() + '.')).toBe(true)@@ -104,6 +117,11 @@ describe('a source that changed shape stops the reader', () => {const withFile = (rel: string, change: (text: string) => string) => (path: string) =>path === rel ? change(real(path)) : real(path)+ it('a 3D engine whose list lost its declared length', () => {+ const reader = withFile(SOURCES.mesh3d, (t) => t.replace(/const PINNED: \[&str; \d+\]/, 'const PINNED: [&str; 3]'))+ expect(() => readEnginePins(reader)).toThrow(/mesh3d\.rs.*declares 3 entries/)+ })+it('a renamed constant', () => {const reader = withFile(SOURCES.mflux, (t) => t.replace('const PINNED:', 'const PINS:'))expect(() => readEnginePins(reader)).toThrow(/image_mflux\.rs.*PINNED/)diff --git a/src/lib/mac-3d.ts b/src/lib/mac-3d.tsnew file mode 100644index 00000000..ec1a103a--- /dev/null+++ b/src/lib/mac-3d.ts@@ -0,0 +1,43 @@+// The 3D lane on a Mac, as Create sees it: one model of the 3D engine+// (TripoSR, src-tauri/src/commands/mesh3d.rs). Kept free of imports, so the+// store, the intent rules and the stage can read it without pulling the+// engine's commands along (api/mlx-3d.ts has those).++/** The name the picker and the gallery give the one model (`MODEL_NAME`). */+export const MAC_3D_MODEL_NAME = 'TripoSR'++/** The id of the one model (`MODEL_ID`). */+export const MAC_3D_MODEL_ID = 'triposr'++/** The grid side per step of Detail. Rust takes 64 to 384 on steps of 32+ * (`resolution_for` in mesh3d.rs); 256 is TripoSR's own default. */+export const MAC_3D_RESOLUTION = { draft: 128, standard: 256, fine: 384 } as const++export type Mac3dDetail = keyof typeof MAC_3D_RESOLUTION++export function mac3dResolution(detail: Mac3dDetail | undefined): number {+ return MAC_3D_RESOLUTION[detail ?? 'standard'] ?? MAC_3D_RESOLUTION.standard+}++/** The phases Rust reports (`View.phase`), in the order a run goes through them. */+export type Mesh3dPhase = 'load' | 'cutout' | 'shape' | 'paint' | 'save'++/** What the progress line says for each phase (plan 1.8). */+export const MESH3D_PHASE_TEXT: Record<Mesh3dPhase, string> = {+ load: 'Getting the model ready…',+ cutout: 'Cutting out your object…',+ shape: 'Building the shape…',+ paint: 'Painting the surface…',+ save: 'Saving your model…',+}++/** The line under the progress bar: the phase in the app's words, and the+ * seconds so far. An unknown phase reads as the first one. */+export function mesh3dRunLine(progress: { phase?: string | null }, elapsedSec: number): string {+ const phase = (progress.phase ?? '') as Mesh3dPhase+ const text = MESH3D_PHASE_TEXT[phase] ?? MESH3D_PHASE_TEXT.load+ return `${text} (${Math.max(0, Math.round(elapsedSec))}s)`+}++/** The words for a picture in which no object was found (`NO_OBJECT`). */+export const MESH3D_NO_OBJECT = 'LU could not find a clear object in this picture. Try one with a plain background.'diff --git a/src/lib/three/__tests__/three-d-logic.test.ts b/src/lib/three/__tests__/three-d-logic.test.tsindex f35be3d3..6ad29ebc 100644--- a/src/lib/three/__tests__/three-d-logic.test.ts+++ b/src/lib/three/__tests__/three-d-logic.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, beforeEach } from 'vitest'import { checkPromptSafety } from '../../render/safety'-import { threeDProvenance, threeDPicturePrompt, threeDGalleryItem, MAC_DETAIL_RESOLUTION } from '../run-local-3d'+import { threeDProvenance, threeDPicturePrompt, threeDGalleryItem } from '../run-local-3d'+import { mac3dResolution } from '../../mac-3d'import { studioIntentOf, intentRoles } from '../../render/create-studio'import { intentToJob, quotaCostKind } from '../../render/cloud-jobs'import { evenPick } from '../../../components/create/experimental/ThreeDControls'@@ -67,8 +68,8 @@ describe('3D helpers', () => {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)+ expect(mac3dResolution('draft')).toBeLessThan(mac3dResolution('standard'))+ expect(mac3dResolution('standard')).toBeLessThan(mac3dResolution('fine'))})})diff --git a/src/lib/three/run-local-3d.ts b/src/lib/three/run-local-3d.tsindex d01853ed..15da6e7f 100644--- a/src/lib/three/run-local-3d.ts+++ b/src/lib/three/run-local-3d.ts@@ -8,7 +8,7 @@//// 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 type { GalleryItem, ImageRef, ThreeDWay } from '../../stores/createStore'import { THREE_D_TEXT } from './three-d-text'export const MAC_3D_MODEL = 'TripoSR'@@ -54,7 +54,3 @@ export function threeDGalleryItem(args: {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 }