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
fix([issue-2952]): detect the silent Metal-bake failure that made TRELLIS.2 meshes render as confetti
[._.]/ Adam Eivy77ab3ec87860
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 44b008ebe3..c51b532e54 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## 3D+- **[issue-2952] The 3D page now catches the install problem that made meshes come out as colorful static** — a TRELLIS.2 render could produce a perfectly accurate 3D shape wrapped in a scrambled, speckled surface, with nothing anywhere saying why. The cause is an install that only *looked* finished: TRELLIS.2's setup builds its high-quality texture painter from Metal source, and on a Mac without Apple's Xcode Metal Toolchain that build quietly fails, the setup still reports success, and every later render silently falls back to a low-resolution painter that can't cover a detailed mesh — so the shape is right and the paint job is confetti. PortOS now checks for the Metal Toolchain **before** you commit to the multi-hour install and warns you if it's missing, verifies after installing whether the good texture painter actually landed, and shows any already-installed copy as **Ready · degraded textures** with a plain explanation and a one-click **Repair install** that rebuilds just the missing piece (your downloaded models are kept). Renders also now bake textures at the highest resolution TRELLIS.2 offers, so surfaces hold more detail either way.- **[issue-3032] The 3D page now uses the Hugging Face token you already saved — and lets you add one right there** — if you'd already given PortOS a Hugging Face token (for gated image models or local model downloads), the 3D page ignored it: it never handed the token to the render, so TRELLIS.2's first run still failed on the two gated models it downloads, and the page kept telling you to go authenticate in a terminal. Your saved token now travels into the render, and the notice reads your actual setup: with a token in place it collapses to a one-line confirmation telling you where that token came from, and with none it offers a paste-and-save field instead of terminal instructions. Either way the two gated models stay linked, since their terms still have to be accepted on your Hugging Face account — a token alone doesn't grant access.- **[issue-2981] Generate a 3D mesh from the 3D page — with a heads-up about Hugging Face access** — the **Generate 3D** button on the 3D page is now live: pick a source image, click Generate, watch on-device progress, and the finished `.glb` renders right there in the interactive viewer (its URL is shareable and reload-safe). If a render fails, the reason now shows inline — including the exact steps when TRELLIS.2 needs Hugging Face access. And before you ever hit that wall, the page and installer now tell you up front that TRELLIS.2 downloads two **gated** Hugging Face models on first render (DINOv3 and RMBG-2.0) and links you to accept their terms and sign in (`huggingface-cli login` or an `HF_TOKEN`).- **[issue-2952] Turn a rendered image into a downloadable 3D mesh (create/render backend)** — once TRELLIS.2 is installed, PortOS can now take one of your gallery images and render it into a real 3D model (a `.glb` mesh with PBR textures) entirely on-device. Each render is saved as its own record you can list, re-render, download, or delete, and it tracks live status (generating → ready, with progress) and its render history — the backend "create a 3D model" path the 3D page's UI drives. The render only ever runs when you ask for it (never in the background), and is refused with a clear reason if the model isn't installed or your hardware can't run it.diff --git a/client/src/components/install/RuntimeInstallModal.jsx b/client/src/components/install/RuntimeInstallModal.jsxindex 2f39f63bd6..3278319268 100644--- a/client/src/components/install/RuntimeInstallModal.jsx+++ b/client/src/components/install/RuntimeInstallModal.jsx@@ -22,9 +22,14 @@ export default function RuntimeInstallModal({onComplete,installUrlBase = '/api/video-gen/setup/runtime-install',description = 'Cloning repo and installing python packages (large download on first run)...',+ // Extra query params for installers that support modes beyond a first-time run+ // (e.g. TRELLIS.2's `repair=1`, which re-runs setup.sh over an existing install+ // to rebuild backends that failed to compile the first time — #2952).+ params,}) {const [confirmingCancel, setConfirmingCancel] = useState(false);- const url = open && runtime ? `${installUrlBase}?runtime=${encodeURIComponent(runtime)}` : null;+ const query = new URLSearchParams({ runtime: runtime ?? '', ...(params || {}) });+ const url = open && runtime ? `${installUrlBase}?${query}` : null;const { logs, done, error, streamStarted, logsEndRef, close } = useInstallStream(url,{ enabled: open && !!runtime, onComplete, maxLogLines: MAX_LOG_LINES, flushMs: 100 },diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex cbb24c4fdf..151e0c1363 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -105,6 +105,17 @@ function StatusBadge({ target }) {);}if (target.installed) {+ // An installed target whose Metal texture bake is missing still renders — the+ // geometry is fine — but the surface comes out scrambled, so "Ready" alone+ // would be a lie. `quality:'unknown'` (the probe couldn't run) stays Ready+ // rather than crying wolf about an install that is probably fine.+ if (target.textureBake?.quality === 'fallback') {+ return (+ <span className="inline-flex items-center gap-1.5 text-xs font-medium text-port-warning">+ <AlertTriangle className="w-3.5 h-3.5" /> Ready · degraded textures+ </span>+ );+ }return (<span className="inline-flex items-center gap-1.5 text-xs font-medium text-port-success"><CheckCircle2 className="w-3.5 h-3.5" /> Ready@@ -118,6 +129,9 @@ function TargetCard({ target, onInstall }) {// Install only applies to targets with a local install concept (installed is a// boolean); hosted targets report installed:null and are Ready when available.const canInstall = target.available && target.installed === false;+ // Re-running Install is the documented repair for a degraded bake, so offer it on+ // an already-installed target too when the probe says the Metal backends are gone.+ const degradedBake = target.textureBake?.quality === 'fallback';return (<div className="rounded-lg border border-port-border bg-port-card p-4">@@ -153,16 +167,21 @@ function TargetCard({ target, onInstall }) {</div><div className="flex shrink-0 flex-col items-end gap-2"><StatusBadge target={target} />- {canInstall && (+ {(canInstall || degradedBake) && (<buttononClick={() => onInstall(target)}className="inline-flex items-center gap-1.5 rounded-md bg-port-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-600">- <Download className="w-3.5 h-3.5" /> Install+ <Download className="w-3.5 h-3.5" /> {canInstall ? 'Install' : 'Repair install'}</button>)}</div></div>+ {degradedBake && target.textureBake?.help && (+ <p className="mt-3 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-[11px] leading-relaxed text-port-warning">+ {target.textureBake.help}+ </p>+ )}</div>);}@@ -505,7 +524,13 @@ export default function Media3D() {runtime={installTarget?.id}label={installTarget?.label}installUrlBase="/api/image-to-3d/trellis2/install"- description="Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). It also pulls two gated Hugging Face models on first render — accept their terms and add a Hugging Face token above (see the note on the 3D page)."+ // Repairing an already-installed target must re-run setup.sh rather than+ // short-circuit on "already installed" — that re-run is what rebuilds the+ // Metal texture-baking backends once the Metal Toolchain is present (#2952).+ params={installTarget?.textureBake?.quality === 'fallback' ? { repair: '1' } : undefined}+ description={installTarget?.textureBake?.quality === 'fallback'+ ? 'Re-running the TRELLIS.2 setup to rebuild its Metal texture-baking backends. Already-downloaded weights are kept. This only succeeds once the Xcode Metal Toolchain is installed (`xcodebuild -downloadComponent MetalToolchain`).'+ : 'Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). It also pulls two gated Hugging Face models on first render — accept their terms and add a Hugging Face token above (see the note on the 3D page).'}onClose={() => setInstallTarget(null)}onComplete={() => { setInstallTarget(null); load(); }}/>diff --git a/client/src/pages/Media3D.test.jsx b/client/src/pages/Media3D.test.jsxindex 5b17327826..e62a81c898 100644--- a/client/src/pages/Media3D.test.jsx+++ b/client/src/pages/Media3D.test.jsx@@ -88,6 +88,33 @@ describe('Media3D — models & install', () => {expect(screen.queryByRole('button', { name: /install/i })).toBeNull();});+ // #2952: `setup.sh` exits 0 even when its Metal texture-baking backends failed to+ // build, and such an install renders correct geometry with a scrambled surface —+ // so a flat "Ready" would be a lie, and re-running Install is the repair.+ it('flags a degraded texture bake and offers Repair install', async () => {+ getImageTo3dTargets.mockResolvedValue({+ targets: [target({+ installed: true,+ textureBake: { quality: 'fallback', missing: ['mtldiffrast'], help: 'Install the Metal Toolchain.' },+ })],+ });+ renderAt();+ expect(await screen.findByText(/degraded textures/i)).toBeInTheDocument();+ expect(screen.getByText('Install the Metal Toolchain.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /repair install/i })).toBeInTheDocument();+ });++ it('stays plain Ready when the bake probe could not determine anything', async () => {+ // A probe that failed must not cry wolf about an install that is probably fine.+ getImageTo3dTargets.mockResolvedValue({+ targets: [target({ installed: true, textureBake: { quality: 'unknown', missing: [] } })],+ });+ renderAt();+ expect(await screen.findByText(/ready/i)).toBeInTheDocument();+ expect(screen.queryByText(/degraded textures/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /install/i })).toBeNull();+ });+it('shows the unsupported reason and no Install button when the host cannot run it', async () => {getImageTo3dTargets.mockResolvedValue({targets: [target({ available: false, unavailableReason: 'requires-apple-silicon' })],diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 6784e3efd7..cd9f780729 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -10,7 +10,13 @@ import {unavailableReason,IMAGE_TO_3D_TARGET_IDS,} from '../services/imageTo3d/targets.js';-import { isTrellis2Installed, installTrellis2, trellis2Root } from '../services/imageTo3d/trellis2.js';+import {+ isTrellis2Installed,+ installTrellis2,+ trellis2Root,+ probeTrellis2TextureBake,+ probeMetalToolchain,+} from '../services/imageTo3d/trellis2.js';import {listModels,getModel,@@ -61,6 +67,13 @@ router.get('/targets', asyncHandler(async (_req, res) => {...target,installed: targetInstalled(target.id),}));+ // An installed TRELLIS.2 can still be silently degraded: `setup.sh` swallows a+ // failed Metal-backend build and exits 0, after which every render bakes a+ // scrambled surface. Surface that here so the target card can warn instead of+ // reporting a flat "Ready" (#2952). Skipped when it isn't installed — there is+ // nothing to probe, and the venv Python doesn't exist yet.+ const trellis2 = targets.find((t) => t.id === 'trellis2');+ if (trellis2?.installed) trellis2.textureBake = await probeTrellis2TextureBake();res.json({ capabilities, targets });}));@@ -75,8 +88,22 @@ router.get('/targets', asyncHandler(async (_req, res) => {router.get('/trellis2/install', asyncHandler(async (req, res) => {const { send, safeEnd } = openSseStream(res);- if (isTrellis2Installed()) {+ // `repair=1` re-runs `setup.sh` over an existing install. That is the documented+ // fix for a degraded Metal texture bake: the clone step self-skips (the repo is+ // present) and setup.sh's pip installs re-attempt the Metal packages that failed+ // to compile the first time, while its `if [ ! -d ]` guards keep the ~15 GB of+ // already-downloaded weights. Without this the "Repair install" button would hit+ // the already-installed short-circuit below and do nothing (#2952).+ const repair = req.query.repair === '1';++ if (isTrellis2Installed() && !repair) {send({ type: 'stage', stage: 'verify', message: 'TRELLIS.2 already installed.' });+ // "Installed" is not the same as "installed well" — tell the user when this one+ // needs repairing rather than a bare "nothing to do".+ const bake = await probeTrellis2TextureBake();+ if (bake.quality === 'fallback') {+ send({ type: 'log', stage: 'verify', message: `⚠️ ${bake.help}` });+ }send({ type: 'complete', message: 'Already installed — nothing to do.' });return safeEnd();}@@ -101,6 +128,16 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {const emit = (event) => { installLog.onEvent(event); send(event); };installLog.start();+ // Pre-flight the Metal Toolchain. `setup.sh` builds its Metal texture-baking+ // backends from `.metal` sources but swallows each failure and still exits 0, so+ // without this the user waits ~15 GB and an hour-long render to discover the+ // surface is scrambled. Warn only — the install is still worth running (geometry+ // is unaffected) and the toolchain can be added and the install re-run to repair.+ const toolchain = await probeMetalToolchain();+ if (toolchain.available === false) {+ emit({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });+ }+// Disconnect bookkeeping wired BEFORE the token-resolution await below (the// same hazard `lib/sseDownload.js` documents): that await does a settings read// plus a token-file read, and a client closing during it would otherwise land@@ -143,6 +180,8 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {currentKill = kill;trellis2InstallInFlight = promise;promise+ // `installTrellis2` emits its own post-install `verify` frame (Metal bake+ // present or degraded) before the terminal `complete` — see #2952..then(() => installLog.success()).catch((err) => {// A transient network drop that survived the in-install retries: the partialdiff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex f7c872aeb7..989945ccd4 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -33,6 +33,13 @@ vi.mock('../services/imageTo3d/trellis2.js', () => ({onEvent({ type: 'complete', message: 'TRELLIS.2 installed.' });return { promise: Promise.resolve({ ok: true }), kill: vi.fn() };}),+ // Both probes shell out (venv python / `xcrun metal`). Mocked to the healthy+ // result so the suite never touches the host toolchain; individual tests below+ // override them to drive the degraded-install branches (#2952).+ probeTrellis2TextureBake: vi.fn(async () => ({+ quality: 'metal', modules: {}, missing: [], degradedQuality: [],+ })),+ probeMetalToolchain: vi.fn(async () => ({ available: true })),}));// The install route resolves the central HF token into the child env (#3032).@@ -79,6 +86,26 @@ describe('image-to-3d routes', () => {expect(Array.isArray(res.body.targets)).toBe(true);expect(res.body.targets[0]).toMatchObject({ id: 'trellis2', available: true, installed: false });});++ // #2952: an installed TRELLIS.2 whose Metal bake is missing still renders, but+ // the surface comes out scrambled — the client needs that distinction to avoid+ // showing a flat "Ready".+ it('GET /targets annotates an installed trellis2 with its texture-bake quality', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'fix it',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].textureBake).toMatchObject({ quality: 'fallback', help: 'fix it' });+ });++ it('GET /targets skips the bake probe entirely when trellis2 is not installed', async () => {+ trellis2.probeTrellis2TextureBake.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].textureBake).toBeUndefined();+ expect(trellis2.probeTrellis2TextureBake).not.toHaveBeenCalled();+ });});describe('GET /trellis2/install (SSE)', () => {@@ -92,6 +119,50 @@ describe('GET /trellis2/install (SSE)', () => {expect(trellis2.installTrellis2).toHaveBeenCalled();});+ // Without this the user waits out a ~15 GB install and an hour-long render before+ // discovering the Metal backends could never have built on this host (#2952).+ it('pre-flights the Xcode Metal Toolchain and warns before starting the install', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ targets.isTargetAvailable.mockReturnValueOnce(true);+ trellis2.probeMetalToolchain.mockResolvedValueOnce({ available: false, hint: 'download it' });+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const frames = sseFrames(res.text);+ const warnIdx = frames.findIndex((f) => f.stage === 'preflight');+ expect(warnIdx).toBeGreaterThan(-1);+ expect(frames[warnIdx].message).toContain('download it');+ // A warning, not a refusal — the install still runs (geometry is unaffected).+ expect(trellis2.installTrellis2).toHaveBeenCalled();+ });++ it('does not warn about the toolchain when it is present', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ targets.isTargetAvailable.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ expect(sseFrames(res.text).find((f) => f.stage === 'preflight')).toBeUndefined();+ });++ it('re-runs setup.sh on ?repair=1 instead of short-circuiting on "already installed"', async () => {+ // The Repair install button's whole purpose: rebuild the Metal backends over an+ // existing install once the Metal Toolchain is present (#2952).+ trellis2.installTrellis2.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ targets.isTargetAvailable.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install?repair=1');+ expect(trellis2.installTrellis2).toHaveBeenCalled();+ expect(sseFrames(res.text).at(-1)).toMatchObject({ type: 'complete' });+ });++ it('reports a degraded bake on an already-installed host instead of a bare "nothing to do"', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'repair me',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const frames = sseFrames(res.text);+ expect(frames.find((f) => f.stage === 'verify' && f.type === 'log')?.message).toContain('repair me');+ expect(frames.at(-1)).toMatchObject({ type: 'complete' });+ });+it('hands the resolved HF token env to the install child', async () => {// #3032: the install must carry the CENTRAL token (settings-stored included),// not just whatever the server process happened to be launched with.diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex f720039b0e..3ff95544f8 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -21,7 +21,7 @@import { existsSync } from 'node:fs';import { homedir, platform } from 'node:os';import { join } from 'node:path';-import { spawn } from 'node:child_process';+import { spawn, execFile } from 'node:child_process';import { killWithEscalation } from '../../lib/killWithEscalation.js';const HOME = homedir();@@ -83,6 +83,131 @@ export function isTrellis2Installed({ base, exists = existsSync } = {}) {return exists(trellis2VenvPython(base)) && exists(trellis2GenerateScript(base));}+/**+ * The Python modules `generate.py`'s Metal texture-baking path needs. It gates the+ * high-quality bake on `o_voxel.postprocess._BACKEND === 'metal' && _HAS_DR`, which+ * in turn requires `mtldiffrast` (the Metal rasterizer) and `mtlbvh` to have built.+ * When ANY is missing it silently falls back to a pure-Python KDTree/xatlas baker —+ * see `TRELLIS2_FALLBACK_BAKE_HELP` for why that fallback is unusable.+ */+export const TRELLIS2_METAL_BAKE_MODULES = ['o_voxel', 'mtldiffrast', 'mtlbvh'];++/**+ * `flex_gemm` (from `mtlgemm`) is not required for the Metal bake, but the baker+ * prefers its sparse grid-sample over a `torch.nn.functional` fallback — upstream+ * notes the fallback produces concentric ring artifacts on curved surfaces. Absent+ * ⇒ the bake still runs, just a notch lower quality.+ */+export const TRELLIS2_BAKE_QUALITY_MODULES = ['flex_gemm'];++/**+ * Why a degraded install matters, in the user's terms. `setup.sh` installs the four+ * Metal packages with `|| echo "… continuing without …"` and still exits 0, so a+ * host missing the Xcode **Metal Toolchain** (the packages compile `.metal` sources)+ * completes the install "successfully" and every later render silently takes the+ * KDTree/xatlas fallback baker.+ *+ * That fallback is not merely lower quality — it is unusable on TRELLIS.2 output. It+ * UV-unwraps the mesh *after* decimating to 200k triangles, into a 1024² atlas: a+ * median of **~1.9 texels per triangle**, with a quarter of all triangles landing on+ * less than a single texel (measured on the #2952 reference render). Its hole-fill+ * then blurs unfilled black texels back over every chart edge. The geometry comes out+ * correct; the surface comes out as dark colored confetti.+ */+export const TRELLIS2_FALLBACK_BAKE_HELP = 'TRELLIS.2 is installed, but its Metal '+ + 'texture-baking backend is missing, so renders fall back to a low-resolution '+ + 'baker that produces correct geometry with a scrambled, speckled surface. Install '+ + 'the Xcode Metal Toolchain (`xcodebuild -downloadComponent MetalToolchain`), then '+ + 're-run the TRELLIS.2 install to rebuild the Metal backends.';++/** The shell probe that reports which bake modules resolve inside the venv. */+const BAKE_PROBE_SOURCE = 'import importlib.util as u,json,sys;'+ + 'print(json.dumps({m: u.find_spec(m) is not None for m in sys.argv[1:]}))';++/**+ * Probe whether the venv can take `generate.py`'s Metal texture-baking path.+ *+ * Uses `importlib.util.find_spec`, which resolves a module WITHOUT importing it — so+ * the probe costs ~20 ms and never pulls in torch. That is cheap enough to run on+ * every `/targets` request, and it keys on exactly the modules the `use_metal` gate+ * needs, so it cannot drift from what `generate.py` actually checks.+ *+ * Returns `quality: 'metal'` (good), `'fallback'` (installed but will produce the+ * confetti surface described in `TRELLIS2_FALLBACK_BAKE_HELP`), or `'unknown'` when+ * the probe itself could not run — deliberately distinct from `'fallback'` so a+ * broken probe never renders a scary warning about a possibly-fine install+ * (CLAUDE.md sentinel rule: "failed to determine" ≠ "determined to be bad").+ *+ * @param {{base?: string, execFileImpl?: Function, exists?: (p: string) => boolean}} [opts]+ * @returns {Promise<{quality: 'metal'|'fallback'|'unknown', modules: Record<string, boolean>,+ * missing: string[], degradedQuality: string[], help?: string}>}+ */+export async function probeTrellis2TextureBake({+ base,+ execFileImpl = execFile,+ exists = existsSync,+} = {}) {+ const python = trellis2VenvPython(base);+ if (!exists(python)) {+ return { quality: 'unknown', modules: {}, missing: [], degradedQuality: [] };+ }+ const probed = [...TRELLIS2_METAL_BAKE_MODULES, ...TRELLIS2_BAKE_QUALITY_MODULES];+ // Subprocess boundary outside the request lifecycle — a probe failure must degrade+ // to 'unknown', never reject into the route (CLAUDE.md child-process exception).+ const modules = await new Promise((resolve) => {+ execFileImpl(python, ['-c', BAKE_PROBE_SOURCE, ...probed], { timeout: 15000 }, (err, stdout) => {+ if (err) return resolve(null);+ const parsed = JSON.parse(String(stdout || '').trim() || 'null');+ resolve(parsed && typeof parsed === 'object' ? parsed : null);+ });+ }).catch(() => null);++ if (!modules) return { quality: 'unknown', modules: {}, missing: [], degradedQuality: [] };++ const missing = TRELLIS2_METAL_BAKE_MODULES.filter((m) => !modules[m]);+ const degradedQuality = TRELLIS2_BAKE_QUALITY_MODULES.filter((m) => !modules[m]);+ return {+ quality: missing.length ? 'fallback' : 'metal',+ modules,+ missing,+ degradedQuality,+ ...(missing.length ? { help: TRELLIS2_FALLBACK_BAKE_HELP } : {}),+ };+}++/**+ * Whether the Xcode Metal Toolchain is present — the prerequisite `setup.sh`+ * documents for building `mtldiffrast`/`mtlbvh`/`mtlgemm`. Checked BEFORE a ~15 GB+ * install so the user can fix it first, instead of discovering an hour later that+ * every render bakes garbage. Absent ⇒ the install still works, it just degrades.+ *+ * Non-macOS hosts report `available: null` (the check does not apply) rather than+ * `false`, so a Linux/Windows caller never sees a macOS-only warning.+ *+ * @param {{execFileImpl?: Function, platformImpl?: () => string}} [opts]+ * @returns {Promise<{available: boolean|null, hint?: string}>}+ */+export async function probeMetalToolchain({+ execFileImpl = execFile,+ platformImpl = platform,+} = {}) {+ if (platformImpl() !== 'darwin') return { available: null };+ const available = await new Promise((resolve) => {+ execFileImpl('xcrun', ['-sdk', 'macosx', 'metal', '--version'], { timeout: 15000 }, (err) => {+ resolve(!err);+ });+ }).catch(() => false);+ return available+ ? { available: true }+ : { available: false, hint: TRELLIS2_METAL_TOOLCHAIN_HINT };+}++/** Actionable one-liner for a missing Metal Toolchain. */+export const TRELLIS2_METAL_TOOLCHAIN_HINT = 'The Xcode Metal Toolchain is not '+ + 'installed, so TRELLIS.2\'s Metal texture-baking backends cannot build and renders '+ + 'will produce a scrambled surface. Run `xcodebuild -downloadComponent '+ + 'MetalToolchain` (a one-time ~2 GB download) before installing.';+/*** The install as an ordered list of `{stage, command, args, cwd?}` steps: shallow-* clone the port, then run its `setup.sh` (which builds the venv + fetches weights).@@ -123,17 +248,49 @@ export function trellis2OutputStem(outputPath) {}/**- * The generate invocation: `<venv-python> generate.py <image> [--output <stem>]`.+ * `generate.py --texture-size` accepts only these three values (an argparse+ * `choices=` list) — anything else aborts the render before it starts.+ */+export const TRELLIS2_TEXTURE_SIZES = [512, 1024, 2048];++/**+ * PortOS asks for the largest atlas the port offers, overriding `generate.py`'s+ * 1024 default. The bake UV-unwraps a 200k-triangle mesh into a single atlas, so+ * texel budget per triangle is the binding constraint on surface quality: at 1024²+ * that is a median ~1.9 texels/triangle, and 2048² quadruples it. This matters most+ * on the KDTree fallback baker (see `TRELLIS2_FALLBACK_BAKE_HELP`) but helps the+ * Metal path too, and costs only bake time plus a larger texture in the GLB.+ */+export const TRELLIS2_DEFAULT_TEXTURE_SIZE = 2048;++/**+ * The generate invocation:+ * `<venv-python> generate.py <image> [--output <stem>] --texture-size <n>`.+ ** Pure. Throws when no source image is given (a render with no input is a bug, not- * an empty run). `outputPath` is the desired `.glb` disk path; it is reduced to the- * stem the port expects (see `trellis2OutputStem`).- * @param {{imagePath: string, outputPath?: string, base?: string}} opts+ * an empty run), and when `textureSize` is not one of the port's accepted `choices`+ * — better to fail here than to have argparse abort a job we already queued.+ * `outputPath` is the desired `.glb` disk path; it is reduced to the stem the port+ * expects (see `trellis2OutputStem`).+ *+ * @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number}} opts* @returns {{command: string, args: string[]}}*/-export function buildGenerateArgs({ imagePath, outputPath, base } = {}) {+export function buildGenerateArgs({+ imagePath,+ outputPath,+ base,+ textureSize = TRELLIS2_DEFAULT_TEXTURE_SIZE,+} = {}) {if (!imagePath) throw new Error('buildGenerateArgs: imagePath is required');+ if (!TRELLIS2_TEXTURE_SIZES.includes(textureSize)) {+ throw new Error(+ `buildGenerateArgs: textureSize must be one of ${TRELLIS2_TEXTURE_SIZES.join(', ')}`,+ );+ }const args = [trellis2GenerateScript(base), imagePath];if (outputPath) args.push('--output', trellis2OutputStem(outputPath));+ args.push('--texture-size', String(textureSize));return { command: trellis2VenvPython(base), args };}@@ -253,9 +410,16 @@ export const isTransientInstallError = textMatcher([* settings reaches the child, not just one exported into the server's own env).* Omitted → the child inherits `process.env` as before.*+ * **Post-install verification.** After the last step the install probes whether the+ * Metal texture-baking backends actually built (`probeBake`, injectable) and emits a+ * `verify` log frame before the terminal `complete`. This is load-bearing, not+ * cosmetic: `setup.sh` installs those packages with `|| echo "… continuing without …"`+ * and still exits 0, so without it a host lacking the Xcode Metal Toolchain gets a+ * clean "installed" and every later render bakes a scrambled surface (#2952).+ ** @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function,* maxRetries?: number, sleep?: (ms: number) => Promise<void>,- * env?: NodeJS.ProcessEnv}} [opts]+ * env?: NodeJS.ProcessEnv, probeBake?: Function}} [opts]* @returns {{promise: Promise<{ok: true}>, kill: () => void}}*/export function installTrellis2({@@ -266,6 +430,7 @@ export function installTrellis2({sleep = (ms) => new Promise((r) => setTimeout(r, ms)),exists = existsSync,env,+ probeBake = probeTrellis2TextureBake,} = {}) {// `exists` lets the clone step be skipped when the repo is already on disk (resume// after a setup-stage failure) — see buildInstallSteps.@@ -343,6 +508,16 @@ export function installTrellis2({}await runStepWithRetry(step);}+ // `setup.sh` exits 0 even when its Metal texture-baking backends failed to+ // build, so a bare success would report an install that silently renders+ // scrambled surfaces (#2952). Verify what actually landed and say so — BEFORE+ // the terminal `complete` frame, which closes the client's EventSource.+ const bake = await probeBake({ base });+ if (bake.quality === 'fallback') {+ onEvent({ type: 'log', stage: 'verify', message: `⚠️ ${bake.help}` });+ } else if (bake.quality === 'metal') {+ onEvent({ type: 'log', stage: 'verify', message: '✅ Metal texture baking is available.' });+ }onEvent({ type: 'complete', message: 'TRELLIS.2 installed.' });return { ok: true };})();@@ -409,7 +584,7 @@ const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from* it in — this function stays synchronous so its `{ promise, kill }` contract holds.* Omitted → the child inherits `process.env` as before.*- * @param {{imagePath: string, outputPath?: string, base?: string,+ * @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,* onProgress?: (frame: object) => void,* spawnImpl?: Function, exists?: (p: string) => boolean,* env?: NodeJS.ProcessEnv}} opts@@ -419,6 +594,7 @@ export function runTrellis2Generate({imagePath,outputPath,base,+ textureSize,onProgress,spawnImpl = spawn,exists = existsSync,@@ -429,7 +605,7 @@ export function runTrellis2Generate({err.code = 'TRELLIS2_NOT_INSTALLED';return { promise: Promise.reject(err), kill: () => {} };}- const { command, args } = buildGenerateArgs({ imagePath, outputPath, base });+ const { command, args } = buildGenerateArgs({ imagePath, outputPath, base, textureSize });// Child-process boundary — errors surface via the 'error'/'close' events, not a// throw into the request lifecycle (CLAUDE.md child-process exception).const child = spawnImpl(command, args, { cwd: trellis2Root(base), ...(env ? { env } : {}) });diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex a27b04ca71..e212189629 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -14,6 +14,14 @@ import {installTrellis2,isTransientInstallError,isHfAuthError,+ probeTrellis2TextureBake,+ probeMetalToolchain,+ TRELLIS2_METAL_BAKE_MODULES,+ TRELLIS2_BAKE_QUALITY_MODULES,+ TRELLIS2_FALLBACK_BAKE_HELP,+ TRELLIS2_METAL_TOOLCHAIN_HINT,+ TRELLIS2_DEFAULT_TEXTURE_SIZE,+ TRELLIS2_TEXTURE_SIZES,} from './trellis2.js';const flush = () => new Promise((resolve) => setTimeout(resolve, 0));@@ -86,15 +94,33 @@ describe('trellis2OutputStem', () => {});describe('buildGenerateArgs', () => {- it('invokes the venv python with generate.py and the image', () => {+ it('invokes the venv python with generate.py, the image, and the default texture size', () => {const { command, args } = buildGenerateArgs({ imagePath: '/data/images/x.png', base: BASE });expect(command).toBe(trellis2VenvPython(BASE));- expect(args).toEqual([trellis2GenerateScript(BASE), '/data/images/x.png']);+ expect(args).toEqual([+ trellis2GenerateScript(BASE), '/data/images/x.png',+ '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),+ ]);});it('passes --output as a STEM — the port appends .glb, so a full path would double it', () => {const { args } = buildGenerateArgs({ imagePath: 'in.png', outputPath: '/out/model.glb', base: BASE });- expect(args).toEqual([trellis2GenerateScript(BASE), 'in.png', '--output', '/out/model']);+ expect(args.slice(0, 4)).toEqual([trellis2GenerateScript(BASE), 'in.png', '--output', '/out/model']);+ });++ it('defaults to the largest atlas the port offers (texel budget per triangle is the binding constraint)', () => {+ expect(TRELLIS2_DEFAULT_TEXTURE_SIZE).toBe(2048);+ expect(TRELLIS2_TEXTURE_SIZES).toContain(TRELLIS2_DEFAULT_TEXTURE_SIZE);+ });++ it('honors an explicit texture size', () => {+ const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 1024 });+ expect(args).toEqual([trellis2GenerateScript(BASE), 'in.png', '--texture-size', '1024']);+ });++ it('rejects a texture size outside the port\'s argparse choices instead of letting the render abort', () => {+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 4096 }))+ .toThrow(/textureSize must be one of/);});it('throws when no source image is given', () => {@@ -102,6 +128,86 @@ describe('buildGenerateArgs', () => {});});+describe('probeTrellis2TextureBake', () => {+ // The probe shells to the venv python with an importlib.util.find_spec one-liner.+ // Fake execFile lets us assert each outcome without a real venv.+ const fakeExec = (payload, err = null) => vi.fn((_cmd, _args, _opts, cb) => {+ cb(err, payload === null ? '' : JSON.stringify(payload), '');+ });+ const allPresent = Object.fromEntries(+ [...TRELLIS2_METAL_BAKE_MODULES, ...TRELLIS2_BAKE_QUALITY_MODULES].map((m) => [m, true]),+ );++ it('reports metal quality when every Metal bake module resolves', async () => {+ const result = await probeTrellis2TextureBake({+ base: BASE, exists: () => true, execFileImpl: fakeExec(allPresent),+ });+ expect(result.quality).toBe('metal');+ expect(result.missing).toEqual([]);+ expect(result.help).toBeUndefined();+ });++ it('reports fallback quality with actionable help when a Metal module is missing', async () => {+ // The real #2952 failure: setup.sh could not compile the Metal packages (no+ // Xcode Metal Toolchain) but swallowed each error and exited 0.+ const result = await probeTrellis2TextureBake({+ base: BASE,+ exists: () => true,+ execFileImpl: fakeExec({ ...allPresent, mtldiffrast: false, mtlbvh: false }),+ });+ expect(result.quality).toBe('fallback');+ expect(result.missing).toEqual(['mtldiffrast', 'mtlbvh']);+ expect(result.help).toBe(TRELLIS2_FALLBACK_BAKE_HELP);+ });++ it('treats a missing quality-only module as still metal-capable', () => expect(+ probeTrellis2TextureBake({+ base: BASE, exists: () => true, execFileImpl: fakeExec({ ...allPresent, flex_gemm: false }),+ }),+ ).resolves.toMatchObject({ quality: 'metal', degradedQuality: ['flex_gemm'] }));++ it('reports unknown — NOT fallback — when the probe itself fails', async () => {+ // A broken probe must never render a scary "degraded" warning about an install+ // that is probably fine (sentinel rule: could-not-determine ≠ determined-bad).+ const result = await probeTrellis2TextureBake({+ base: BASE, exists: () => true, execFileImpl: fakeExec(null, new Error('boom')),+ });+ expect(result.quality).toBe('unknown');+ expect(result.help).toBeUndefined();+ });++ it('reports unknown without spawning anything when the venv python is absent', async () => {+ const execFileImpl = fakeExec(allPresent);+ const result = await probeTrellis2TextureBake({ base: BASE, exists: () => false, execFileImpl });+ expect(result.quality).toBe('unknown');+ expect(execFileImpl).not.toHaveBeenCalled();+ });+});++describe('probeMetalToolchain', () => {+ it('is available when `xcrun metal --version` succeeds', () => expect(+ probeMetalToolchain({+ platformImpl: () => 'darwin',+ execFileImpl: vi.fn((_c, _a, _o, cb) => cb(null, '', '')),+ }),+ ).resolves.toEqual({ available: true }));++ it('is unavailable with a hint when the toolchain component is missing', async () => {+ const result = await probeMetalToolchain({+ platformImpl: () => 'darwin',+ execFileImpl: vi.fn((_c, _a, _o, cb) => cb(new Error('missing Metal Toolchain'))),+ });+ expect(result).toEqual({ available: false, hint: TRELLIS2_METAL_TOOLCHAIN_HINT });+ });++ it('does not apply off macOS — null, not false, so no macOS-only warning is shown', async () => {+ const execFileImpl = vi.fn();+ expect(await probeMetalToolchain({ platformImpl: () => 'linux', execFileImpl }))+ .toEqual({ available: null });+ expect(execFileImpl).not.toHaveBeenCalled();+ });+});+describe('parseGenerateProgress', () => {// The real generate.py banners (see the module's GENERATE_STAGE_SIGNATURES),// in the order the port prints them, and the monotonic percent each maps to.@@ -185,7 +291,7 @@ describe('runTrellis2Generate', () => {});expect(spawnImpl).toHaveBeenCalledWith(trellis2VenvPython(BASE),- [trellis2GenerateScript(BASE), 'a.png'],+ [trellis2GenerateScript(BASE), 'a.png', '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE)],{ cwd: trellis2Root(BASE) },);child.stdout.emit('data', 'Generating 3D model (pipeline=512, seed=42)...\n');@@ -278,7 +384,7 @@ describe('runTrellis2Generate', () => {const { promise } = runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: installed, spawnImpl, env });expect(spawnImpl).toHaveBeenCalledWith(trellis2VenvPython(BASE),- [trellis2GenerateScript(BASE), 'a.png'],+ [trellis2GenerateScript(BASE), 'a.png', '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE)],{ cwd: trellis2Root(BASE), env },);child.emit('close', null); // settle the run so its rejection isn't left dangling@@ -399,6 +505,45 @@ describe('installTrellis2', () => {expect(events.at(-1)).toMatchObject({ type: 'complete' });});+ // `setup.sh` swallows a failed Metal-backend build and still exits 0, so the+ // install must verify what landed and report it BEFORE the terminal `complete`+ // frame — which closes the client's EventSource (#2952).+ const runToCompletion = async (probeBake) => {+ const children = [makeChild(), makeChild()];+ let i = 0;+ const events = [];+ const { promise } = installTrellis2({+ base: BASE, spawnImpl: () => children[i++], onEvent: (e) => events.push(e), probeBake,+ });+ children[0].emit('close', 0);+ await flush();+ children[1].emit('close', 0);+ await promise;+ return events;+ };++ it('warns about a degraded Metal bake BEFORE the terminal complete frame', async () => {+ const events = await runToCompletion(async () => ({+ quality: 'fallback', missing: ['mtldiffrast'], help: TRELLIS2_FALLBACK_BAKE_HELP,+ }));+ const verifyIdx = events.findIndex((e) => e.stage === 'verify');+ const completeIdx = events.findIndex((e) => e.type === 'complete');+ expect(verifyIdx).toBeGreaterThan(-1);+ expect(verifyIdx).toBeLessThan(completeIdx);+ expect(events[verifyIdx].message).toContain(TRELLIS2_FALLBACK_BAKE_HELP);+ });++ it('confirms a healthy Metal bake on a good install', async () => {+ const events = await runToCompletion(async () => ({ quality: 'metal', missing: [] }));+ expect(events.find((e) => e.stage === 'verify')?.message).toMatch(/Metal texture baking is available/);+ });++ it('stays silent when the bake probe could not determine anything', async () => {+ const events = await runToCompletion(async () => ({ quality: 'unknown', missing: [] }));+ expect(events.find((e) => e.stage === 'verify')).toBeUndefined();+ expect(events.at(-1)).toMatchObject({ type: 'complete' });+ });+it('spawns install steps under the caller-supplied env, alongside each step cwd', async () => {const children = [makeChild(), makeChild()];let i = 0;