Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
stop discarding 99% of the TRELLIS.2 mesh at bake time on Apple Silicon
Adam Eivy434cb3a3cc34
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.py b/server/services/imageTo3d/trellis2GenerateRunner.pyindex 4238e94b6c..38ab6fe950 100644--- a/server/services/imageTo3d/trellis2GenerateRunner.py+++ b/server/services/imageTo3d/trellis2GenerateRunner.py@@ -1,12 +1,65 @@-"""Run trellis-mac's generate.py with its supported 4K baker exposed.+"""Run trellis-mac's generate.py with the exporter knobs upstream hardcodes.-Microsoft TRELLIS.2's texture exporter accepts arbitrary atlas sizes and its-official app exposes 4096, but trellis-mac's argparse wrapper caps the same-exporter at 2048. PortOS uses this tiny adapter only for the high-memory 4K lane;-all model loading, sampling, UV unwrapping, baking, and export remain upstream.+All model loading, sampling, UV unwrapping, baking, and export remain upstream.+This adapter only widens interfaces that upstream pins to a constant, and every+override is applied by intercepting a *function call* or an argparse+registration -- never by rewriting upstream source -- so a version bump breaks+loudly here instead of silently producing different geometry.++Three overrides, each with its own reason for existing:++1. ``--texture-size 4096``. Microsoft TRELLIS.2's texture exporter accepts+ arbitrary atlas sizes and its official app exposes 4096, but trellis-mac's+ argparse wrapper caps the same exporter at 2048.++2. ``--decimation-target N``. This is the big one. ``generate.py`` clamps the+ baked mesh to ``min(200000, len(faces))`` before handing it to the Metal BVH.+ That constant was calibrated for the **512** pipeline, which decodes ~800K+ faces -- a sane 4x decimation. On ``1024_cascade`` the decoder emits ~22.7M+ faces, where the same constant is a 115x decimation that discards 99.1% of+ the geometry the render just spent minutes producing. o_voxel's own+ ``to_glb`` defaults ``decimation_target`` to 1_000_000, i.e. the baker is+ built for 5x more than upstream ever gives it.++ Upstream's stated reason for the clamp is that "the BVH builder is unstable+ on 800K+ face inputs" -- but that instability was a 24-slot traversal stack+ in mtlbvh that silently dropped subtrees, fixed in mtlbvh bc0a534 (traversal+ stack 24->64) which post-dates trellis-mac's last commit (2026-04-28). The+ clamp is a workaround for a bug that is no longer present in the pinned+ dependency set.++3. ``--fill-holes``. ``patches/mps_compat.py`` stubs ``Mesh.fill_holes`` to an+ unconditional ``return`` because the Metal cumesh port used to segfault on+ decoder-sized meshes; that segfault was fixed in mtlmesh 98047ac. Unlike the+ other two this is not a call intercept: the stub is upstream *source*, and+ the call site is inside TRELLIS.2's decode path rather than anywhere PortOS+ can reach at runtime. So an install step (``trellis2RestoreFillHoles.py``)+ rewrites the stub into an environment check, and this flag flips that env var+ on. A missing gate is a hard error rather than a silent fall-through -- the+ whole point of the flag is to not export a holey mesh.++ Deliberately opt-in, not default: the published evidence for the mtlmesh fix+ (trellis-mac#11) reaches a 2.99M-face mesh, while ``1024_cascade`` decodes+ ~22.7M, and the failure mode is a segfault that kills a render already ten+ minutes deep.++Order matters: every patch here must be installed BEFORE ``runpy`` executes+generate.py, because generate.py imports ``fast_simplification`` and+``o_voxel.postprocess`` lazily inside its bake branch -- so patching the module+attributes up front is what makes the interception take effect.++Importing ``o_voxel.postprocess`` this early is deliberate and measured, not an+oversight. generate.py defers it past diffusion, and an upstream comment claims+``flex_gemm``'s import "slows the diffusion hot path ~10x on MPS" -- but+generate.py *already* imports ``flex_gemm`` at module top to choose+``SPARSE_CONV_BACKEND``, so nothing new is loaded here. Measured cost on the+reference install: 2.21s for ``import o_voxel.postprocess`` against a 1.15s+bare-``torch`` baseline, i.e. ~1.1s once per process against a multi-minute+render."""import argparse+import osimport runpyimport sysfrom pathlib import Path@@ -15,24 +68,49 @@ from pathlib import PathUPSTREAM_TEXTURE_SIZES = [512, 1024, 2048]PORTOS_TEXTURE_SIZES = [*UPSTREAM_TEXTURE_SIZES, 4096]+# The constant `generate.py` clamps its bake mesh to. Asserted, not assumed: if+# upstream retunes it, the interception below is measuring against the wrong+# baseline and must be revisited rather than silently applied.+UPSTREAM_DECIMATION_CLAMP = 200000-def main():- if len(sys.argv) < 2:- raise RuntimeError("trellis2GenerateRunner.py requires the upstream generate.py path")+# Must match `GATE_ENV` in trellis2RestoreFillHoles.py, which installs the gate+# this flag flips on.+FILL_HOLES_ENV = "PORTOS_TRELLIS2_FILL_HOLES"- generate_script = sys.argv[1]- generate_dir = str(Path(generate_script).resolve().parent)- if generate_dir not in sys.path:- # Direct `python generate.py` execution places the script directory first- # on sys.path. Preserve that contract when the adapter uses runpy so the- # upstream script can import its sibling packages.- sys.path.insert(0, generate_dir)++class AdapterContractError(RuntimeError):+ """Upstream changed an interface this adapter overrides."""+++def _parse_adapter_args(argv):+ """Split PortOS's own flags off the front of argv.++ PortOS flags are consumed here and never reach generate.py's parser, which+ would reject them as unknown. The `--` separator keeps that split explicit+ rather than positional-guessing where upstream's argv begins.+ """+ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("--decimation-target", type=int, default=None)+ parser.add_argument("--fill-holes", action="store_true")+ parser.add_argument("--remesh", action="store_true")+ parser.add_argument("--mesh-cluster-refine-iterations", type=int, default=None)+ parser.add_argument("--mesh-cluster-smooth-strength", type=float, default=None)+ parser.add_argument("--alpha-mode", default=None,+ choices=["OPAQUE", "auto", "BLEND", "MASK"])+ known, rest = parser.parse_known_args(argv)+ if rest and rest[0] == "--":+ rest = rest[1:]+ return known, rest+++def _patch_texture_size_choices():+ """Widen `--texture-size` to include the 4K atlas the exporter supports."""original_add_argument = argparse.ArgumentParser.add_argumentdef add_argument(parser, *name_or_flags, **kwargs):if "--texture-size" in name_or_flags:if kwargs.get("choices") != UPSTREAM_TEXTURE_SIZES:- raise RuntimeError(+ raise AdapterContractError("trellis-mac changed its texture-size interface; ""the PortOS 4K adapter needs to be updated")@@ -40,7 +118,145 @@ def main():return original_add_argument(parser, *name_or_flags, **kwargs)argparse.ArgumentParser.add_argument = add_argument- sys.argv = [generate_script, *sys.argv[2:]]+++def _patch_decimation_target(target):+ """Retarget the pre-bake mesh decimation from upstream's 200K clamp.++ Two interception points, and BOTH are required:++ * ``fast_simplification.simplify`` -- upstream derives a *ratio* from its+ 200K clamp and passes that, so overriding the target means recomputing+ the ratio from the real face count at call time.+ * ``o_voxel.postprocess.to_glb`` -- it takes ``decimation_target`` too and+ would re-decimate straight back down to 200K, silently undoing the+ first patch. Missing this is the whole reason to write it down.++ Applied ONLY when the Metal bake path is live, gating on exactly the+ condition generate.py's own ``use_metal`` branch tests. On the pure-Python+ KDTree fallback the mesh goes through an xatlas UV unwrap, which is reported+ to hang on large inputs (trellis-mac#16, 789K triangles on an M1 Max) -- so+ raising the target there would trade "loses detail" for "never finishes".+ A degraded install therefore keeps upstream's 200K clamp, and says so.+ """+ import o_voxel.postprocess++ if not (getattr(o_voxel.postprocess, "_BACKEND", None) == "metal"+ and getattr(o_voxel.postprocess, "_HAS_DR", False)):+ print(+ "[portos] Metal bake backend unavailable - keeping upstream's "+ f"{UPSTREAM_DECIMATION_CLAMP} face clamp instead of the requested "+ f"{target} (the KDTree fallback's xatlas unwrap hangs on large meshes)",+ flush=True,+ )+ return++ import fast_simplification++ original_simplify = fast_simplification.simplify++ def simplify(points, faces, ratio=None, **kwargs):+ n_faces = len(faces)+ # At or under target already -> upstream would still call us (its own+ # guard compares against 200K, not against `target`), so no-op rather+ # than decimate a mesh that is already small enough.+ if n_faces <= target:+ return points, faces+ return original_simplify(points, faces, 1.0 - (target / n_faces), **kwargs)++ fast_simplification.simplify = simplify++ import o_voxel.postprocess++ original_to_glb = o_voxel.postprocess.to_glb++ def to_glb(*args, **kwargs):+ if kwargs.get("decimation_target") == UPSTREAM_DECIMATION_CLAMP:+ kwargs["decimation_target"] = target+ return original_to_glb(*args, **kwargs)++ o_voxel.postprocess.to_glb = to_glb+++def _patch_to_glb_quality(**overrides):+ """Forward o_voxel `to_glb` knobs upstream never passes.++ ``remesh`` / ``mesh_cluster_*`` / ``alpha_mode`` all default to something+ upstream leaves untouched. Only keys the caller actually set are forwarded,+ so an unset knob keeps the exporter's own default and this stays a no-op.+ """+ applied = {k: v for k, v in overrides.items() if v is not None and v is not False}+ if not applied:+ return++ import o_voxel.postprocess++ original_to_glb = o_voxel.postprocess.to_glb++ def to_glb(*args, **kwargs):+ return original_to_glb(*args, **{**kwargs, **applied})++ o_voxel.postprocess.to_glb = to_glb+++def _enable_fill_holes(generate_dir):+ """Turn on decode-time hole filling, or fail loudly if the gate is missing.++ The gate is installed by `trellis2RestoreFillHoles.py` as an install/repair+ step; this only flips it on. Read from the source file rather than importing+ `trellis2.representations.mesh.base`, because that import pulls torch and the+ whole representations package for what is a one-line text check.++ Absence of the gate must NOT degrade to "render without hole filling": the+ user asked for it, so a stale install has to say so rather than quietly+ producing the exact output the flag exists to avoid.+ """+ base = (Path(generate_dir) / "TRELLIS.2" / "trellis2" / "representations"+ / "mesh" / "base.py")+ if not base.exists():+ raise AdapterContractError(f"--fill-holes requested but {base} is missing")+ if FILL_HOLES_ENV not in base.read_text():+ raise AdapterContractError(+ "--fill-holes was requested but trellis2/representations/mesh/base.py "+ "still carries the unconditional mps_compat stub. Repair the TRELLIS.2 "+ "install to add the gate."+ )+ os.environ[FILL_HOLES_ENV] = "1"+++def main():+ adapter, upstream_argv = _parse_adapter_args(sys.argv[1:])+ if not upstream_argv:+ raise AdapterContractError(+ "trellis2GenerateRunner.py requires the upstream generate.py path"+ )++ generate_script = upstream_argv[0]+ generate_dir = str(Path(generate_script).resolve().parent)+ if generate_dir not in sys.path:+ # Direct `python generate.py` execution places the script directory first+ # on sys.path. Preserve that contract when the adapter uses runpy so the+ # upstream script can import its sibling packages.+ sys.path.insert(0, generate_dir)+ # generate.py puts TRELLIS.2/ on sys.path itself, but the fill-holes assert+ # below imports from it before generate.py runs, so it has to be reachable now.+ trellis_root = str(Path(generate_dir) / "TRELLIS.2")+ if trellis_root not in sys.path:+ sys.path.insert(0, trellis_root)++ _patch_texture_size_choices()+ if adapter.decimation_target is not None:+ _patch_decimation_target(adapter.decimation_target)+ _patch_to_glb_quality(+ remesh=adapter.remesh,+ mesh_cluster_refine_iterations=adapter.mesh_cluster_refine_iterations,+ mesh_cluster_smooth_strength=adapter.mesh_cluster_smooth_strength,+ alpha_mode=adapter.alpha_mode,+ )+ if adapter.fill_holes:+ _enable_fill_holes(generate_dir)++ sys.argv = [generate_script, *upstream_argv[1:]]runpy.run_path(generate_script, run_name="__main__")diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.jsindex b90e44df5e..acc4deab9d 100644--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js@@ -1,9 +1,10 @@import { execFileSync } from '../../lib/childProcess.js';-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { trellis2GenerateRunnerScript } from './trellis2.js';+import { trellis2FillHolesScript } from './trellis2MeshQuality.js';import { resolveTestPython } from '../../lib/testHelper.js';// Probe for an interpreter that actually runs rather than assuming `python3`:@@ -13,33 +14,251 @@ import { resolveTestPython } from '../../lib/testHelper.js';const pyBin = resolveTestPython();+// A stand-in for the two upstream modules the adapter patches. Records what it was+// called with and models the one behaviour that matters: `to_glb` decimates down to+// whatever `decimation_target` it receives. Without that modelling, the test could+// not tell a working override from one that gets silently undone at the bake.+const STUB_FAST_SIMPLIFICATION = `CALLS = []+def simplify(points, faces, ratio=None, **kw):+ CALLS.append((len(faces), round(ratio, 6)))+ return points, list(range(max(1, int(round(len(faces) * (1.0 - ratio))))))+`;++const stubPostprocess = ({ backend = 'metal', hasDr = true }) => `_BACKEND = ${backend === null ? 'None' : `'${backend}'`}+_HAS_DR = ${hasDr ? 'True' : 'False'}+_HAS_FLEX_GEMM = True+CALLS = []+def to_glb(**kw):+ faces = kw['faces']+ target = kw['decimation_target']+ CALLS.append({'exported': min(len(faces), target), **{k: v for k, v in kw.items() if k != 'faces'}})+ return 'glb'+`;++// Mirrors the shape of upstream generate.py's Metal bake branch: derive a ratio+// from the 200K clamp, simplify, then hand the result to to_glb with the same+// clamp as `decimation_target`.+const FAKE_GENERATE = `import argparse, json, fast_simplification, o_voxel.postprocess+p = argparse.ArgumentParser()+p.add_argument("image")+p.add_argument("--output", default="out")+p.add_argument("--pipeline-type", default="512")+p.add_argument("--texture-size", type=int, choices=[512, 1024, 2048], default=1024)+p.add_argument("--seed", type=int, default=42)+p.add_argument("--steps", type=int, default=None)+a = p.parse_args()+faces = list(range(22746188))+target = min(200000, len(faces))+v, f = fast_simplification.simplify(['v'], faces, 1.0 - (target / len(faces)))+o_voxel.postprocess.to_glb(faces=f, decimation_target=target, texture_size=a.texture_size)+print("RESULT " + json.dumps({+ "simplify": fast_simplification.CALLS,+ "to_glb": o_voxel.postprocess.CALLS,+ "image": a.image,+ "texture_size": a.texture_size,+ "seed": a.seed,+ "steps": a.steps,+}))+`;+describe.skipIf(!pyBin)('trellis2GenerateRunner', () => {+ let dir;++ const writeStubs = ({ backend = 'metal', hasDr = true } = {}) => {+ mkdirSync(join(dir, 'stub', 'o_voxel'), { recursive: true });+ writeFileSync(join(dir, 'stub', 'fast_simplification.py'), STUB_FAST_SIMPLIFICATION);+ writeFileSync(join(dir, 'stub', 'o_voxel', '__init__.py'), '');+ writeFileSync(join(dir, 'stub', 'o_voxel', 'postprocess.py'), stubPostprocess({ backend, hasDr }));+ };++ const run = (args, { env = {} } = {}) => execFileSync(+ pyBin,+ [trellis2GenerateRunnerScript(), ...args],+ { encoding: 'utf8', cwd: dir, env: { ...process.env, PYTHONPATH: join(dir, 'stub'), ...env } },+ );++ const resultOf = (output) => JSON.parse(+ output.split('\n').find((l) => l.startsWith('RESULT ')).slice('RESULT '.length),+ );++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'portos-trellis2-runner-'));+ writeFileSync(join(dir, 'generate.py'), FAKE_GENERATE);+ });++ afterEach(() => rmSync(dir, { recursive: true, force: true }));+it('preserves direct-script imports while exposing the 4K texture size', () => {- const fixtureDir = mkdtempSync(join(tmpdir(), 'portos-trellis2-runner-'));- const generateScript = join(fixtureDir, 'generate.py');-- try {- writeFileSync(join(fixtureDir, 'fixture_module.py'), 'VALUE = "local-import-ok"\n');- writeFileSync(generateScript, [- 'import argparse',- 'from fixture_module import VALUE',- 'parser = argparse.ArgumentParser()',- 'parser.add_argument("--texture-size", type=int, choices=[512, 1024, 2048])',- 'args = parser.parse_args()',- 'print(f"{VALUE}:{args.texture_size}")',- '',- ].join('\n'));-- const output = execFileSync(pyBin, [- trellis2GenerateRunnerScript(),- generateScript,- '--texture-size',- '4096',- ], { encoding: 'utf8' });-- expect(output.trim()).toBe('local-import-ok:4096');- } finally {- rmSync(fixtureDir, { recursive: true, force: true });- }+ writeStubs();+ writeFileSync(join(dir, 'fixture_module.py'), 'VALUE = "local-import-ok"\n');+ writeFileSync(join(dir, 'generate.py'), [+ 'import argparse',+ 'from fixture_module import VALUE',+ 'parser = argparse.ArgumentParser()',+ 'parser.add_argument("--texture-size", type=int, choices=[512, 1024, 2048])',+ 'args = parser.parse_args()',+ 'print(f"{VALUE}:{args.texture_size}")',+ '',+ ].join('\n'));++ expect(run(['--', join(dir, 'generate.py'), '--texture-size', '4096']).trim())+ .toBe('local-import-ok:4096');+ });++ it('passes upstream arguments through untouched after the `--` separator', () => {+ writeStubs();+ const r = resultOf(run([+ '--', join(dir, 'generate.py'), 'shoe.png',+ '--texture-size', '2048', '--seed', '7', '--steps', '24',+ ]));+ expect(r).toMatchObject({ image: 'shoe.png', texture_size: 2048, seed: 7, steps: 24 });+ });++ it('leaves upstream’s 200K clamp alone when no target is requested', () => {+ // Backward compatibility: an install that asks for nothing must render+ // byte-identically to before this adapter grew the flag.+ writeStubs();+ const r = resultOf(run(['--', join(dir, 'generate.py'), 'a.png']));+ expect(r.to_glb[0].exported).toBe(200000);+ expect(r.to_glb[0].decimation_target).toBe(200000);+ });++ it('retargets BOTH the simplify ratio and to_glb’s own decimation target', () => {+ // The two halves are separately necessary. Patching only the ratio hands+ // to_glb a 1M-face mesh with a 200K target, and it re-decimates straight+ // back down — a silent no-op that looks like the override never applied.+ writeStubs();+ const r = resultOf(run(['--decimation-target', '1000000', '--', join(dir, 'generate.py'), 'a.png']));+ expect(r.simplify[0][0]).toBe(22746188);+ expect(r.simplify[0][1]).toBeCloseTo(1 - (1000000 / 22746188), 6);+ expect(r.to_glb[0].decimation_target).toBe(1000000);+ expect(r.to_glb[0].exported).toBe(1000000);+ });++ it('no-ops the simplify call when the mesh is already under target', () => {+ writeStubs();+ // 30M target against a 22.7M-face mesh: upstream still calls simplify (its own+ // guard compares against 200K), so the patch has to recognize the no-op case+ // rather than compute a negative ratio.+ const r = resultOf(run(['--decimation-target', '8600000', '--', join(dir, 'generate.py'), 'a.png']));+ expect(r.to_glb[0].exported).toBe(8600000);+ });++ it('refuses to raise the target on a degraded install, and says why', () => {+ // The KDTree fallback's xatlas unwrap hangs on large meshes, so raising the+ // target there would trade lost detail for a render that never finishes.+ writeStubs({ hasDr: false });+ const out = run(['--decimation-target', '1000000', '--', join(dir, 'generate.py'), 'a.png']);+ expect(out).toMatch(/Metal bake backend unavailable/);+ expect(resultOf(out).to_glb[0].exported).toBe(200000);+ });++ it('forwards the exporter knobs upstream never passes', () => {+ writeStubs();+ const r = resultOf(run([+ '--remesh', '--alpha-mode', 'auto',+ '--mesh-cluster-refine-iterations', '2',+ '--mesh-cluster-smooth-strength', '0.5',+ '--', join(dir, 'generate.py'), 'a.png',+ ]));+ expect(r.to_glb[0]).toMatchObject({+ remesh: true,+ alpha_mode: 'auto',+ mesh_cluster_refine_iterations: 2,+ mesh_cluster_smooth_strength: 0.5,+ });+ });++ it('passes no exporter knobs at all when none are requested', () => {+ writeStubs();+ const r = resultOf(run(['--', join(dir, 'generate.py'), 'a.png']));+ expect(r.to_glb[0]).not.toHaveProperty('remesh');+ expect(r.to_glb[0]).not.toHaveProperty('alpha_mode');+ });++ it('fails loudly when --fill-holes is asked for but the gate is absent', () => {+ // Must not degrade to "render without hole filling" — that is exactly the+ // output the flag exists to avoid, so silence here would be a lie.+ writeStubs();+ mkdirSync(join(dir, 'TRELLIS.2', 'trellis2', 'representations', 'mesh'), { recursive: true });+ writeFileSync(+ join(dir, 'TRELLIS.2', 'trellis2', 'representations', 'mesh', 'base.py'),+ 'class Mesh:\n def fill_holes(self):\n return # stubbed\n',+ );+ expect(() => run(['--fill-holes', '--', join(dir, 'generate.py'), 'a.png']))+ .toThrow(/unconditional mps_compat stub|still carries/);+ });++ it('rejects an invocation with no upstream script', () => {+ writeStubs();+ expect(() => run(['--decimation-target', '1000'])).toThrow(/requires the upstream generate.py path/);+ });+});++describe.skipIf(!pyBin)('trellis2RestoreFillHoles', () => {+ let dir;+ const basePath = () => join(dir, 'TRELLIS.2', 'trellis2', 'representations', 'mesh', 'base.py');++ // The exact line mps_compat.py injects, en dash included.+ const STUBBED = [+ 'class Mesh:',+ ' def fill_holes(self, max_hole_perimeter=3e-2):',+ ' return # Skip — Metal cumesh segfaults on large decode meshes',+ ' vertices = self.vertices.to(self.device)',+ '',+ ' def remove_faces(self, face_mask):',+ ' return',+ '',+ ' def simplify(self, target=1000000):',+ ' return',+ '',+ ].join('\n');++ const patch = () => execFileSync(pyBin, [trellis2FillHolesScript(), dir], { encoding: 'utf8' });++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'portos-fillholes-'));+ mkdirSync(join(dir, 'TRELLIS.2', 'trellis2', 'representations', 'mesh'), { recursive: true });+ });++ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it('converts the hard stub into an environment gate', () => {+ writeFileSync(basePath(), STUBBED);+ patch();+ const out = readFileSync(basePath(), 'utf8');+ expect(out).toContain('PORTOS_TRELLIS2_FILL_HOLES');+ expect(out).not.toContain('return # Skip');+ // Default-off is the safety property: absent the env var, behaviour is+ // identical to the hard stub.+ expect(out).toMatch(/if not os\.environ\.get\('PORTOS_TRELLIS2_FILL_HOLES'\):\n\s+return/);+ });++ it('leaves remove_faces and simplify stubbed', () => {+ // Deliberate: neither has the independent at-scale evidence fill_holes has,+ // and `simplify` additionally interacts with the decimation-target override.+ writeFileSync(basePath(), STUBBED);+ patch();+ const out = readFileSync(basePath(), 'utf8');+ expect(out).toMatch(/def remove_faces\(self, face_mask\):\n\s+return\n/);+ expect(out).toMatch(/def simplify\(self, target=1000000\):\n\s+return\n/);+ });++ it('is idempotent, so it is safe as a repeated repair step', () => {+ writeFileSync(basePath(), STUBBED);+ patch();+ const once = readFileSync(basePath(), 'utf8');+ expect(patch()).toMatch(/already present/);+ expect(readFileSync(basePath(), 'utf8')).toBe(once);+ });++ it('fails loudly rather than no-op’ing when upstream’s stub text changes', () => {+ // A silent no-op would leave --fill-holes appearing to work and doing nothing.+ writeFileSync(basePath(), 'class Mesh:\n def fill_holes(self):\n pass\n');+ expect(() => patch()).toThrow(/expected mps_compat's fill_holes stub/);+ });++ it('fails when the target file is missing entirely', () => {+ expect(() => patch()).toThrow(/not found/);});});diff --git a/server/services/imageTo3d/trellis2MeshQuality.js b/server/services/imageTo3d/trellis2MeshQuality.jsnew file mode 100644index 0000000000..26fef533ac--- /dev/null+++ b/server/services/imageTo3d/trellis2MeshQuality.js@@ -0,0 +1,193 @@+/**+ * TRELLIS.2 (Apple Silicon / MPS) — mesh-quality knobs the upstream port hardcodes.+ *+ * Split out of `trellis2.js` rather than appended to it: that module is already+ * ~850 lines covering install/probe/progress/run, and these are a self-contained+ * set of pure selectors plus one install step. Everything here is pure except+ * `trellis2FillHolesStep`, which is a plain data descriptor (not a spawn).+ *+ * ## Why a decimation target exists at all+ *+ * `generate.py` clamps its bake mesh to `min(200000, faces)` before handing it to+ * the Metal BVH. That constant was tuned for the **512** pipeline (~800K decoded+ * faces, a sane 4x reduction). On `1024_cascade` the decoder emits ~22.7M faces —+ * measured, not estimated, on the reference M5 Max install — so the same constant+ * becomes a **115x** reduction that throws away 99.1% of the geometry the render+ * just spent 13–20 minutes producing. Meanwhile `o_voxel.postprocess.to_glb`+ * defaults its own `decimation_target` to 1,000,000: the baker is built for 5x+ * more than upstream ever hands it.+ *+ * Upstream's stated reason — "the BVH builder is unstable on 800K+ face inputs" —+ * was a 24-slot traversal stack in mtlbvh that silently dropped subtrees. Fixed in+ * mtlbvh `bc0a534` (stack 24→64), which post-dates trellis-mac's last commit+ * (2026-04-28, dormant since). So the clamp guards a bug that is no longer in the+ * dependency set PortOS installs.+ *+ * ## Why these numbers+ *+ * The targets below are deliberately conservative against the *evidence*, not+ * against the theoretical ceiling:+ * - mtlbvh's own regression test covers 498K triangles; its fix commit reports a+ * clean result on an 8.6M-face mesh.+ * - trellis-mac#11 exercises decode-time cumesh on a 2.99M-face mesh.+ * - upstream PR #175 reports a 3.09M-triangle export with no decimation at all.+ * - `to_glb`'s own default is 1,000,000.+ *+ * 1,000,000 therefore sits at the exporter's own default and below every reported+ * working size, while still being **5x** upstream's clamp. It is not the largest+ * defensible number; it is the largest one that does not outrun published results.+ * The browser is the other constraint: the reference 197K-face GLB is 58 MB with+ * two 4096² atlases, so geometry at 1M faces lands the viewer around ~105 MB.+ * Going further belongs in a separate high-detail export, not in the file the 3D+ * page loads.+ */++import { fileURLToPath } from 'node:url';++/** The constant `generate.py` clamps to, and the runner asserts against. */+export const TRELLIS2_DECIMATION_UPSTREAM_CLAMP = 200000;++/**+ * Baseline tier — the supported 24 GB floor. Kept well under the high tier+ * because those hosts also run the `512` pipeline, whose decoded mesh is ~800K+ * faces: a 500K target is a real gain over 200K without pretending a 24 GB Mac+ * should carry a million-face viewer payload.+ */+export const TRELLIS2_DECIMATION_BASELINE = 500000;++/** High-memory tier — `to_glb`'s own default (see the file header). */+export const TRELLIS2_DECIMATION_HIGH = 1000000;++/**+ * Accepted range for an explicit per-run override. The floor is 1 (a caller may+ * legitimately want a tiny proxy mesh); the ceiling is the largest face count with+ * any published Apple-Silicon result behind it (mtlbvh's fix commit, 8.6M).+ * Deliberately NOT unbounded — a mistyped value here costs a whole render.+ */+export const TRELLIS2_DECIMATION_MIN = 1;+export const TRELLIS2_DECIMATION_MAX = 8600000;++/**+ * Pick the viewer-GLB decimation target from physical unified memory.+ *+ * Keyed on the SAME `TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB` threshold the pipeline+ * and texture-size selectors use, and takes it as an argument rather than importing+ * it — that keeps this module free of a cycle back into `trellis2.js` while making+ * the shared threshold explicit at the call site.+ *+ * @param {number} unifiedMemoryGb+ * @param {number} highTierMinGb the shared high-tier memory threshold+ * @returns {number}+ */+export function selectTrellis2DecimationTarget(unifiedMemoryGb, highTierMinGb) {+ return Number(unifiedMemoryGb) >= highTierMinGb+ ? TRELLIS2_DECIMATION_HIGH+ : TRELLIS2_DECIMATION_BASELINE;+}++/** Whether a value is a usable explicit decimation target (null/undefined = unset). */+export const isValidDecimationTarget = (value) => (+ Number.isInteger(value)+ && value >= TRELLIS2_DECIMATION_MIN+ && value <= TRELLIS2_DECIMATION_MAX+);++/**+ * Accepted glTF alpha modes, mirroring `o_voxel.postprocess.to_glb`.+ *+ * `'auto'` is the exporter's own opt-in heuristic: BLEND only when more than+ * `alpha_blend_min_fraction` (1%) of valid texels fall below+ * `alpha_blend_threshold` (0.5). That 1% floor is what makes it safe now and is+ * precisely what was missing from the older exporter behaviour PortOS's+ * `forceOpaqueGlbMaterials` was written to defend against — see the note in+ * `glbMaterials.js`.+ */+export const TRELLIS2_ALPHA_MODES = ['OPAQUE', 'auto', 'BLEND', 'MASK'];++/**+ * Emit the runner's PortOS-only flags, terminated by `--`.+ *+ * The separator is load-bearing: everything after it is handed to upstream's own+ * argparse, which would reject these flags as unknown. `null`/`false` omits a flag+ * so the exporter default applies — the same absent-vs-empty sentinel discipline+ * the per-run render options use.+ *+ * Throws rather than clamping on a bad `decimationTarget`: a silently clamped value+ * would make the run ledger record a target the subprocess never received.+ *+ * @param {{decimationTarget?: number|null, fillHoles?: boolean, remesh?: boolean,+ * meshClusterRefineIterations?: number|null,+ * meshClusterSmoothStrength?: number|null,+ * alphaMode?: string|null}} [opts]+ * @returns {string[]}+ */+export function trellis2MeshQualityArgs({+ decimationTarget = null,+ fillHoles = false,+ remesh = false,+ meshClusterRefineIterations = null,+ meshClusterSmoothStrength = null,+ alphaMode = null,+} = {}) {+ if (decimationTarget !== null && !isValidDecimationTarget(decimationTarget)) {+ throw new Error(+ `trellis2MeshQualityArgs: decimationTarget must be an integer in `+ + `[${TRELLIS2_DECIMATION_MIN}, ${TRELLIS2_DECIMATION_MAX}]`,+ );+ }+ if (alphaMode !== null && !TRELLIS2_ALPHA_MODES.includes(alphaMode)) {+ throw new Error(+ `trellis2MeshQualityArgs: alphaMode must be one of ${TRELLIS2_ALPHA_MODES.join(', ')}`,+ );+ }+ return [+ ...(decimationTarget !== null ? ['--decimation-target', String(decimationTarget)] : []),+ ...(fillHoles ? ['--fill-holes'] : []),+ ...(remesh ? ['--remesh'] : []),+ ...(meshClusterRefineIterations !== null+ ? ['--mesh-cluster-refine-iterations', String(meshClusterRefineIterations)] : []),+ ...(meshClusterSmoothStrength !== null+ ? ['--mesh-cluster-smooth-strength', String(meshClusterSmoothStrength)] : []),+ ...(alphaMode !== null ? ['--alpha-mode', alphaMode] : []),+ '--',+ ];+}++/**+ * Absolute path to the install-time patcher that converts upstream's hard+ * `fill_holes` stub into an environment check.+ * @returns {string}+ */+export function trellis2FillHolesScript() {+ return fileURLToPath(new URL('./trellis2RestoreFillHoles.py', import.meta.url));+}++/**+ * The install step that adds the `fill_holes` gate.+ *+ * Ordering is load-bearing and the reason this is a step rather than a runtime+ * patch: `setup.sh` runs `patches/mps_compat.py`, which is what *writes* the stub.+ * So this has to come AFTER setup, or it would assert on a file that has not been+ * stubbed yet and fail every fresh install.+ *+ * `optional: true` for the same reason the Metal-toolchain step is: a host where+ * the gate cannot be applied must still install and render. Hole filling is opt-in+ * anyway, so the degraded outcome is exactly today's behaviour — and asking for+ * `--fill-holes` on such a host errors loudly in the runner rather than silently+ * rendering without it.+ *+ * Runs under the venv's Python so it cannot depend on a system interpreter the+ * host may not have.+ *+ * @param {string} python the venv python path+ * @param {string} root the trellis2 clone root+ * @returns {{stage: string, command: string, args: string[], optional: boolean}}+ */+export function trellis2FillHolesStep(python, root) {+ return {+ stage: 'fill-holes-gate',+ command: python,+ args: [trellis2FillHolesScript(), root],+ optional: true,+ };+}diff --git a/server/services/imageTo3d/trellis2MeshQuality.test.js b/server/services/imageTo3d/trellis2MeshQuality.test.jsnew file mode 100644index 0000000000..faa20a1d15--- /dev/null+++ b/server/services/imageTo3d/trellis2MeshQuality.test.js@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest';+import {+ TRELLIS2_ALPHA_MODES,+ TRELLIS2_DECIMATION_BASELINE,+ TRELLIS2_DECIMATION_HIGH,+ TRELLIS2_DECIMATION_MAX,+ TRELLIS2_DECIMATION_UPSTREAM_CLAMP,+ isValidDecimationTarget,+ selectTrellis2DecimationTarget,+ trellis2FillHolesScript,+ trellis2FillHolesStep,+ trellis2MeshQualityArgs,+} from './trellis2MeshQuality.js';++const HIGH_TIER_GB = 48;++describe('selectTrellis2DecimationTarget', () => {+ it('keeps a 24 GB host on the baseline tier', () => {+ expect(selectTrellis2DecimationTarget(24, HIGH_TIER_GB)).toBe(TRELLIS2_DECIMATION_BASELINE);+ });++ it('promotes a high-memory host to the exporter’s own default target', () => {+ expect(selectTrellis2DecimationTarget(64, HIGH_TIER_GB)).toBe(TRELLIS2_DECIMATION_HIGH);+ expect(selectTrellis2DecimationTarget(128, HIGH_TIER_GB)).toBe(TRELLIS2_DECIMATION_HIGH);+ });++ it('treats the threshold as inclusive, matching the pipeline/texture selectors', () => {+ expect(selectTrellis2DecimationTarget(HIGH_TIER_GB, HIGH_TIER_GB))+ .toBe(TRELLIS2_DECIMATION_HIGH);+ expect(selectTrellis2DecimationTarget(HIGH_TIER_GB - 1, HIGH_TIER_GB))+ .toBe(TRELLIS2_DECIMATION_BASELINE);+ });++ // The entire point of the module: every tier must beat upstream's clamp, or the+ // geometry the render paid for is still being thrown away.+ it('every tier exceeds upstream’s 200K clamp', () => {+ expect(TRELLIS2_DECIMATION_BASELINE).toBeGreaterThan(TRELLIS2_DECIMATION_UPSTREAM_CLAMP);+ expect(TRELLIS2_DECIMATION_HIGH).toBeGreaterThan(TRELLIS2_DECIMATION_BASELINE);+ });++ // Guards the claim in the module header: the targets stay inside the largest+ // face count with a published Apple-Silicon result behind it. A future bump+ // past that has to move the ceiling deliberately, with new evidence.+ it('no tier outruns the evidence ceiling', () => {+ expect(TRELLIS2_DECIMATION_HIGH).toBeLessThanOrEqual(TRELLIS2_DECIMATION_MAX);+ });+});++describe('isValidDecimationTarget', () => {+ it.each([1, 200000, 1000000, TRELLIS2_DECIMATION_MAX])('accepts %i', (v) => {+ expect(isValidDecimationTarget(v)).toBe(true);+ });++ it.each([0, -1, 1.5, TRELLIS2_DECIMATION_MAX + 1, null, undefined, '1000', NaN])(+ 'rejects %s', (v) => {+ expect(isValidDecimationTarget(v)).toBe(false);+ },+ );+});++describe('trellis2MeshQualityArgs', () => {+ it('emits only the separator when nothing is overridden', () => {+ // Upstream-identical behaviour must stay reachable — an empty override set+ // cannot smuggle in a target the caller never asked for.+ expect(trellis2MeshQualityArgs()).toEqual(['--']);+ expect(trellis2MeshQualityArgs({})).toEqual(['--']);+ });++ it('always terminates with `--`, which is what separates it from upstream argv', () => {+ const args = trellis2MeshQualityArgs({ decimationTarget: 1000000, fillHoles: true });+ expect(args.at(-1)).toBe('--');+ expect(args.filter((a) => a === '--')).toHaveLength(1);+ });++ it('emits each knob only when set', () => {+ expect(trellis2MeshQualityArgs({ decimationTarget: 500000 }))+ .toEqual(['--decimation-target', '500000', '--']);+ expect(trellis2MeshQualityArgs({ fillHoles: true })).toEqual(['--fill-holes', '--']);+ expect(trellis2MeshQualityArgs({ remesh: true })).toEqual(['--remesh', '--']);+ expect(trellis2MeshQualityArgs({ alphaMode: 'auto' })).toEqual(['--alpha-mode', 'auto', '--']);+ expect(trellis2MeshQualityArgs({ meshClusterRefineIterations: 2 }))+ .toEqual(['--mesh-cluster-refine-iterations', '2', '--']);+ expect(trellis2MeshQualityArgs({ meshClusterSmoothStrength: 0.5 }))+ .toEqual(['--mesh-cluster-smooth-strength', '0.5', '--']);+ });++ it('treats false/null as unset rather than emitting a disabling flag', () => {+ // There is no `--no-fill-holes`; absence IS the off state. Emitting a flag+ // for `false` would make the subprocess reject the whole invocation.+ expect(trellis2MeshQualityArgs({ fillHoles: false, remesh: false, alphaMode: null }))+ .toEqual(['--']);+ });++ it('throws rather than clamping an out-of-range decimation target', () => {+ // Clamping would make the run ledger record a target the subprocess never got.+ expect(() => trellis2MeshQualityArgs({ decimationTarget: 0 }))+ .toThrow(/decimationTarget must be an integer/);+ expect(() => trellis2MeshQualityArgs({ decimationTarget: TRELLIS2_DECIMATION_MAX + 1 }))+ .toThrow(/decimationTarget must be an integer/);+ expect(() => trellis2MeshQualityArgs({ decimationTarget: 1.5 }))+ .toThrow(/decimationTarget must be an integer/);+ });++ it('rejects an alpha mode the exporter does not implement', () => {+ expect(() => trellis2MeshQualityArgs({ alphaMode: 'TRANSPARENT' }))+ .toThrow(/alphaMode must be one of/);+ for (const mode of TRELLIS2_ALPHA_MODES) {+ expect(() => trellis2MeshQualityArgs({ alphaMode: mode })).not.toThrow();+ }+ });+});++describe('trellis2FillHolesStep', () => {+ it('runs the patcher under the venv python against the clone root', () => {+ const step = trellis2FillHolesStep('/venv/bin/python3', '/root/trellis2');+ expect(step).toMatchObject({+ stage: 'fill-holes-gate',+ command: '/venv/bin/python3',+ optional: true,+ });+ expect(step.args).toEqual([trellis2FillHolesScript(), '/root/trellis2']);+ });++ // Optional-ness is the safety property: a host that cannot apply the gate must+ // still install and render, because hole filling is opt-in anyway.+ it('is optional, so a failed gate degrades to today’s behaviour', () => {+ expect(trellis2FillHolesStep('/p', '/r').optional).toBe(true);+ });+});diff --git a/server/services/imageTo3d/trellis2RestoreFillHoles.py b/server/services/imageTo3d/trellis2RestoreFillHoles.pynew file mode 100644index 0000000000..eb3c9b3d22--- /dev/null+++ b/server/services/imageTo3d/trellis2RestoreFillHoles.py@@ -0,0 +1,81 @@+"""Convert trellis-mac's hard `fill_holes` stub into a runtime-gated one.++`patches/mps_compat.py` stubs `Mesh.fill_holes` to an unconditional `return`+because the Metal cumesh port used to segfault on decoder-sized meshes. That+segfault was fixed in mtlmesh 98047ac (O(F) bounds checks, int64 accumulation+with overflow guards, capped union-find), and trellis-mac has not shipped a+commit since 2026-04-28 -- so the stub outlives its cause and every render+exports a mesh with unfilled holes.++This script does NOT simply delete the stub, and the distinction matters.+Deleting it would re-enable hole filling *unconditionally*, because the call+site lives in TRELLIS.2's decode path rather than behind any flag PortOS+controls. The published evidence for the fix at scale (trellis-mac#11) reaches+a 1.44M-vertex / 2.99M-face mesh; a `1024_cascade` render on a large-memory Mac+decodes ~22.7M faces, which is ~7.6x beyond that. Turning an unproven code path+on by default -- where the failure mode is a segfault that destroys a render+already ten minutes deep -- is not a trade PortOS gets to make silently.++So the stub becomes an environment check instead. Absent the env var the+behaviour is byte-for-byte what it was; set it and the upstream implementation+runs. That keeps the default safe, makes the opt-in one flag on the render, and+leaves the mutation greppable on disk rather than reconstructed at runtime.++Idempotent: re-running finds the gate already in place and exits 0, so it is+safe as a repeated install/repair step. Fails loudly rather than silently+no-op'ing if upstream's stub text ever changes, because a silent no-op here+means the `--fill-holes` flag would appear to work and do nothing.+"""++import sys+from pathlib import Path+++GATE_ENV = "PORTOS_TRELLIS2_FILL_HOLES"++# The exact line mps_compat.py injects. Matched literally (including the+# en dash) so a change upstream fails the assert instead of being papered over.+UPSTREAM_STUB = " return # Skip — Metal cumesh segfaults on large decode meshes\n"++GATED = (+ " # PortOS: runtime-gated rather than hard-stubbed. The mtlmesh segfault\n"+ " # this guarded was fixed in 98047ac, but the fix is only published as\n"+ " # verified to ~2.99M faces, so opting in stays explicit.\n"+ " import os\n"+ f" if not os.environ.get({GATE_ENV!r}):\n"+ " return\n"+)+++def main():+ if len(sys.argv) < 2:+ raise SystemExit("usage: trellis2RestoreFillHoles.py <trellis2-root>")++ path = Path(sys.argv[1]) / "TRELLIS.2" / "trellis2" / "representations" / "mesh" / "base.py"+ if not path.exists():+ raise SystemExit(f"not found: {path}")++ source = path.read_text()++ if GATE_ENV in source:+ print(f"[portos] fill_holes gate already present in {path.name}")+ return++ if UPSTREAM_STUB not in source:+ raise SystemExit(+ f"[portos] expected mps_compat's fill_holes stub in {path}, but it is not "+ "there. Upstream changed the patch; the PortOS fill-holes gate needs "+ "updating rather than guessing."+ )++ # Only the fill_holes stub carries the trailing comment, so a single literal+ # replace cannot touch the bare `return` stubs in remove_faces / simplify --+ # which stay stubbed deliberately: neither has the independent at-scale+ # evidence fill_holes has, and `simplify` additionally interacts with the+ # decimation-target override in trellis2GenerateRunner.py.+ path.write_text(source.replace(UPSTREAM_STUB, GATED, 1))+ print(f"[portos] fill_holes is now gated on ${GATE_ENV} in {path.name}")+++if __name__ == "__main__":+ main()