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
feat([issue-3041]): download the Xcode Metal Toolchain as part of the TRELLIS.2 install
[._.]/ Adam Eivy16677b831baf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a7d1ac6f1a..9afee5f85a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## 3D+- **[issue-3041] Installing TRELLIS.2 now fetches the Apple toolchain it needs, instead of telling you to run a command** — #2952 made the "correct shape, confetti surface" problem *visible*, but the fix was still a terminal command you had to copy out of a warning and run yourself — leaving every new install one manual step away from bad-looking renders. Installing (or repairing) TRELLIS.2 now downloads Apple's Xcode Metal Toolchain itself when it's missing, before the setup that needs it, so a fresh install produces properly textured meshes with nothing extra to do. No password is required and the download is skipped entirely when you already have it. **Repair install** on an existing degraded copy now genuinely fixes it rather than re-running the same broken setup. Two honest edge cases: if the download fails the install continues anyway (your geometry is unaffected, and the finished install tells you textures will be reduced), and on a Mac with only the Command Line Tools — where nothing PortOS runs can fetch the toolchain — you get a note naming Xcode as the prerequisite and no Repair button that would only fail.- **[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`).diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex 151e0c1363..b88069a00d 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -129,9 +129,12 @@ 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';+ // Repair install re-runs setup, which now downloads the Metal Toolchain itself+ // (#3041) — but only offer it when the server says it can actually fix this. On a+ // Command-Line-Tools-only host `repairable` is false and the remedy is installing+ // Xcode, so a Repair button would just fail the same way and read as broken.+ const canRepair = degradedBake && target.textureBake?.repairable !== false;return (<div className="rounded-lg border border-port-border bg-port-card p-4">@@ -167,7 +170,7 @@ function TargetCard({ target, onInstall }) {</div><div className="flex shrink-0 flex-col items-end gap-2"><StatusBadge target={target} />- {(canInstall || degradedBake) && (+ {(canInstall || canRepair) && (<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"@@ -529,8 +532,8 @@ export default function Media3D() {// 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).'}+ ? 'Downloading the Xcode Metal Toolchain if it\'s missing, then re-running the TRELLIS.2 setup to rebuild its Metal texture-baking backends. Your already-downloaded models are kept, and no password is required.'+ : 'Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). If the Xcode Metal Toolchain is missing it is downloaded first, so textures bake at full quality. 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 e62a81c898..bee3125de7 100644--- a/client/src/pages/Media3D.test.jsx+++ b/client/src/pages/Media3D.test.jsx@@ -104,6 +104,24 @@ describe('Media3D — models & install', () => {expect(screen.getByRole('button', { name: /repair install/i })).toBeInTheDocument();});+ // #3041: on a Command-Line-Tools-only host, Repair install would fail the same+ // way — so flag the problem but don't offer a button that can't fix it.+ it('flags a degraded bake but offers no Repair button when the server says it is not repairable', async () => {+ getImageTo3dTargets.mockResolvedValue({+ targets: [target({+ installed: true,+ textureBake: {+ quality: 'fallback', missing: ['mtldiffrast'], repairable: false,+ blocker: 'requires-xcode', help: 'Install Xcode from the App Store.',+ },+ })],+ });+ renderAt();+ expect(await screen.findByText(/degraded textures/i)).toBeInTheDocument();+ expect(screen.getByText('Install Xcode from the App Store.')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /install/i })).toBeNull();+ });+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({diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex cd9f780729..499e9654be 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -73,7 +73,18 @@ router.get('/targets', asyncHandler(async (_req, res) => {// 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();+ if (trellis2?.installed) {+ const bake = await probeTrellis2TextureBake();+ // A degraded bake has two very different remedies, and the card must not offer+ // the wrong one: when the Metal Toolchain is merely missing, Repair install+ // fetches it and rebuilds (#3041); when only the Command Line Tools are active+ // there is nothing PortOS can run, and the user has to install Xcode first.+ // Only probe the toolchain when degraded — a healthy install needs no remedy.+ const toolchain = bake.quality === 'fallback' ? await probeMetalToolchain() : null;+ trellis2.textureBake = toolchain?.blocker+ ? { ...bake, repairable: false, blocker: toolchain.blocker, help: toolchain.hint }+ : { ...bake, ...(bake.quality === 'fallback' ? { repairable: true } : {}) };+ }res.json({ capabilities, targets });}));@@ -128,14 +139,19 @@ 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.+ // Resolve the Metal Toolchain situation before spawning anything. `setup.sh`+ // compiles its texture-baking backends from `.metal` sources but swallows each+ // failure and still exits 0, so a host missing the toolchain would otherwise+ // finish "successfully" and render scrambled surfaces forever (#2952). When it's+ // missing but fetchable, the install downloads it as a leading optional step+ // (#3041); when only the Command Line Tools are active nothing we can run fixes+ // it, so warn and install anyway — geometry is unaffected and the `verify` step+ // reports the degraded bake.const toolchain = await probeMetalToolchain();- if (toolchain.available === false) {- emit({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });+ if (toolchain.blocker) emit({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });+ const installMetalToolchain = toolchain.available === false && toolchain.installable === true;+ if (installMetalToolchain) {+ emit({ type: 'log', stage: 'preflight', message: `ℹ️ ${toolchain.hint}` });}// Disconnect bookkeeping wired BEFORE the token-resolution await below (the@@ -176,6 +192,7 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {const { promise, kill } = installTrellis2({onEvent: emit,env: installEnv,+ installMetalToolchain,});currentKill = kill;trellis2InstallInFlight = promise;diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex 989945ccd4..290a641e1d 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -99,6 +99,41 @@ describe('image-to-3d routes', () => {expect(res.body.targets[0].textureBake).toMatchObject({ quality: 'fallback', help: 'fix it' });});+ // #3041: the card must offer the right remedy — Repair install fetches the+ // toolchain, but on a Command-Line-Tools-only host nothing PortOS runs can fix it.+ it('GET /targets marks a degraded bake repairable when the toolchain is merely missing', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'fix it',+ });+ trellis2.probeMetalToolchain.mockResolvedValueOnce({ available: false, installable: true });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].textureBake).toMatchObject({ repairable: true, help: 'fix it' });+ });++ it('GET /targets marks a degraded bake NOT repairable when only Command Line Tools are active', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'fix it',+ });+ trellis2.probeMetalToolchain.mockResolvedValueOnce({+ available: false, installable: false, blocker: 'requires-xcode', hint: 'install Xcode',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].textureBake).toMatchObject({+ repairable: false, blocker: 'requires-xcode', help: 'install Xcode',+ });+ });++ it('GET /targets does not probe the toolchain for a healthy bake', async () => {+ trellis2.probeMetalToolchain.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].textureBake).toMatchObject({ quality: 'metal' });+ expect(res.body.targets[0].textureBake.repairable).toBeUndefined();+ expect(trellis2.probeMetalToolchain).not.toHaveBeenCalled();+ });+it('GET /targets skips the bake probe entirely when trellis2 is not installed', async () => {trellis2.probeTrellis2TextureBake.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);@@ -119,26 +154,48 @@ describe('GET /trellis2/install (SSE)', () => {expect(trellis2.installTrellis2).toHaveBeenCalled();});+ // #3041: a missing-but-fetchable toolchain becomes a step of the install itself,+ // rather than a command printed for the user to run.+ it('tells the install to download the Metal Toolchain when it is missing but fetchable', async () => {+ trellis2.installTrellis2.mockClear();+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ targets.isTargetAvailable.mockReturnValueOnce(true);+ trellis2.probeMetalToolchain.mockResolvedValueOnce({+ available: false, installable: true, hint: 'it will be downloaded',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ expect(trellis2.installTrellis2).toHaveBeenCalledWith(+ expect.objectContaining({ installMetalToolchain: true }),+ );+ expect(sseFrames(res.text).find((f) => f.stage === 'preflight')?.message).toContain('it will be downloaded');+ });+// 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 () => {+ it('warns but still installs when the toolchain cannot be fetched (Command Line Tools only)', async () => {+ trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);targets.isTargetAvailable.mockReturnValueOnce(true);- trellis2.probeMetalToolchain.mockResolvedValueOnce({ available: false, hint: 'download it' });+ trellis2.probeMetalToolchain.mockResolvedValueOnce({+ available: false, installable: false, blocker: 'requires-xcode', hint: 'install Xcode',+ });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();+ expect(sseFrames(res.text).find((f) => f.stage === 'preflight')?.message).toContain('install Xcode');+ // A warning, not a refusal — geometry is unaffected — and no step that would fail.+ expect(trellis2.installTrellis2).toHaveBeenCalledWith(+ expect.objectContaining({ installMetalToolchain: false }),+ );});- it('does not warn about the toolchain when it is present', async () => {+ it('adds no toolchain step or warning when it is already present', async () => {+ trellis2.installTrellis2.mockClear();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();+ expect(trellis2.installTrellis2).toHaveBeenCalledWith(+ expect.objectContaining({ installMetalToolchain: false }),+ );});it('re-runs setup.sh on ?repair=1 instead of short-circuiting on "already installed"', async () => {diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex 3ff95544f8..fb974ef7c6 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -116,9 +116,9 @@ export const TRELLIS2_BAKE_QUALITY_MODULES = ['flex_gemm'];*/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.';+ + 'baker that produces correct geometry with a scrambled, speckled surface. Repair '+ + 'install downloads the Xcode Metal Toolchain and rebuilds the Metal backends — '+ + 'your downloaded models are kept.';/** The shell probe that reports which bake modules resolve inside the venv. */const BAKE_PROBE_SOURCE = 'import importlib.util as u,json,sys;'@@ -184,29 +184,76 @@ export async function probeTrellis2TextureBake({* 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.*+ * **Missing is not the same as unfixable.** `xcodebuild -downloadComponent` ships+ * with *full Xcode*; a host whose active developer dir is the Command Line Tools+ * has no `xcodebuild` to run it with. Those two cases get different answers —+ * `installable: true` means the install can just fetch it (see+ * `TRELLIS2_METAL_TOOLCHAIN_STEP`), while `blocker: 'requires-xcode'` means no+ * amount of retrying will help and the hint must name Xcode rather than a command+ * that is guaranteed to fail.+ ** @param {{execFileImpl?: Function, platformImpl?: () => string}} [opts]- * @returns {Promise<{available: boolean|null, hint?: string}>}+ * @returns {Promise<{available: boolean|null, installable?: boolean,+ * blocker?: 'requires-xcode', 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);+ // Subprocess boundary outside the request lifecycle — every outcome resolves,+ // nothing throws into the route (CLAUDE.md child-process exception).+ const run = (command, args) => new Promise((resolve) => {+ execFileImpl(command, args, { timeout: 15000 }, (err, stdout) => {+ resolve(err ? null : String(stdout ?? ''));});- }).catch(() => false);- return available- ? { available: true }- : { available: false, hint: TRELLIS2_METAL_TOOLCHAIN_HINT };+ }).catch(() => null);++ if (await run('xcrun', ['-sdk', 'macosx', 'metal', '--version']) !== null) {+ return { available: true };+ }+ // Only full Xcode carries `xcodebuild -downloadComponent`. `xcode-select -p`+ // under the Command Line Tools resolves to /Library/Developer/CommandLineTools.+ const developerDir = await run('xcode-select', ['-p']);+ const hasXcode = !!developerDir && /Xcode.*\.app/i.test(developerDir);+ return hasXcode+ ? { available: false, installable: true, hint: TRELLIS2_METAL_TOOLCHAIN_HINT }+ : { available: false, installable: false, blocker: 'requires-xcode', hint: TRELLIS2_REQUIRES_XCODE_HINT };}-/** Actionable one-liner for a missing Metal Toolchain. */+/** A missing-but-fetchable toolchain: the install can download it unattended. */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.';+ + 'would produce a scrambled surface. The install will download it automatically '+ + '(a one-time ~2 GB download, no password required).';++/**+ * A missing toolchain on a host with only the Command Line Tools. Nothing PortOS+ * can run fixes this, so the hint names the real prerequisite instead of a command+ * that would fail.+ */+export const TRELLIS2_REQUIRES_XCODE_HINT = 'The Xcode Metal Toolchain is not '+ + 'installed and cannot be downloaded, because only the Command Line Tools are '+ + 'active on this host. Install Xcode from the App Store and run `sudo xcode-select '+ + '--switch /Applications/Xcode.app`, then repair the TRELLIS.2 install. Until then '+ + 'renders will produce correct geometry with a scrambled surface.';++/**+ * The step that fetches the Metal Toolchain. Verified on-device during #3041: it+ * runs unattended — no sudo, no interactive prompt, exit 0 — and afterwards+ * `xcrun metal` resolves and the port's four Metal packages compile.+ *+ * Marked `optional` because a missing texture bake degrades output but does not+ * break it: geometry is unaffected, and the `verify` step reports the degraded+ * result. A host that cannot fetch the toolchain must still be able to install and+ * render, so this step warns and continues rather than aborting the install.+ */+export const TRELLIS2_METAL_TOOLCHAIN_STEP = Object.freeze({+ stage: 'metal-toolchain',+ command: 'xcodebuild',+ args: ['-downloadComponent', 'MetalToolchain'],+ optional: true,+});/*** The install as an ordered list of `{stage, command, args, cwd?}` steps: shallow-@@ -219,13 +266,27 @@ export const TRELLIS2_METAL_TOOLCHAIN_HINT = 'The Xcode Metal Toolchain is not '* re-running with an unconditional `git clone … <root>` would abort ("destination* path already exists and is not an empty directory") and never reach the idempotent* `setup.sh`. `exists` is injectable so the skip is deterministic in tests.+ *+ * **The Metal Toolchain step leads when `installMetalToolchain` is set.** Order is+ * load-bearing: `setup.sh` compiles the Metal texture-baking packages from `.metal`+ * sources, so the toolchain has to be on disk BEFORE it runs or those builds fail+ * (silently — `setup.sh` swallows them and still exits 0) and the install completes+ * with a bake that renders scrambled surfaces (#2952). The caller passes the flag+ * from `probeMetalToolchain()`; a host that already has it, can't have it (Command+ * Line Tools only), or isn't macOS gets no step.+ ** @param {string} [base]- * @param {{exists?: (p: string) => boolean}} [opts]- * @returns {Array<{stage: string, command: string, args: string[], cwd?: string}>}+ * @param {{exists?: (p: string) => boolean, installMetalToolchain?: boolean}} [opts]+ * @returns {Array<{stage: string, command: string, args: string[], cwd?: string, optional?: boolean}>}*/-export function buildInstallSteps(base, { exists = existsSync } = {}) {+export function buildInstallSteps(base, { exists = existsSync, installMetalToolchain = false } = {}) {const root = trellis2Root(base);const steps = [];+ // Copy `args` too — a spread alone would share the frozen template's array across+ // every call, so one caller mutating it would corrupt every later install plan.+ if (installMetalToolchain) {+ steps.push({ ...TRELLIS2_METAL_TOOLCHAIN_STEP, args: [...TRELLIS2_METAL_TOOLCHAIN_STEP.args] });+ }if (!exists(join(root, '.git'))) {steps.push({ stage: 'clone', command: 'git', args: ['clone', '--depth', '1', TRELLIS2_REPO, root] });}@@ -410,6 +471,14 @@ 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.*+ * **Metal Toolchain step.** `setup.sh` compiles the Metal texture-baking packages+ * from `.metal` sources, so when `installMetalToolchain` is set the install downloads+ * the toolchain FIRST (#3041). Verified on-device: that download runs unattended (no+ * sudo, no prompt), which is what makes auto-install viable instead of printing a+ * command for the user to run. The step is `optional` — see+ * `TRELLIS2_METAL_TOOLCHAIN_STEP`. The caller resolves the flag from+ * `probeMetalToolchain()` (the route does, so this stays synchronous).+ ** **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@@ -419,7 +488,7 @@ export const isTransientInstallError = textMatcher([** @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function,* maxRetries?: number, sleep?: (ms: number) => Promise<void>,- * env?: NodeJS.ProcessEnv, probeBake?: Function}} [opts]+ * env?: NodeJS.ProcessEnv, probeBake?: Function, installMetalToolchain?: boolean}} [opts]* @returns {{promise: Promise<{ok: true}>, kill: () => void}}*/export function installTrellis2({@@ -431,10 +500,13 @@ export function installTrellis2({exists = existsSync,env,probeBake = probeTrellis2TextureBake,+ installMetalToolchain = false,} = {}) {- // `exists` lets the clone step be skipped when the repo is already on disk (resume- // after a setup-stage failure) — see buildInstallSteps.- const steps = buildInstallSteps(base, { exists });+ // `exists` lets the clone step self-skip when the repo is already on disk (resume+ // after a setup-stage failure); `installMetalToolchain` is resolved by the CALLER+ // from `probeMetalToolchain()` and passed in as a plain boolean, so this function+ // keeps returning `{ promise, kill }` synchronously — see buildInstallSteps.+ const steps = buildInstallSteps(base, { exists, installMetalToolchain });let currentChild = null;let canceled = false;@@ -487,7 +559,23 @@ export function installTrellis2({} catch (err) {const canRetry = err?.code === 'TRELLIS2_INSTALL_FAILED'&& err.transient && attempt < maxRetries && !canceled;- if (!canRetry) throw err;+ if (!canRetry) {+ // An `optional` step degrades the install rather than breaking it (the+ // Metal Toolchain fetch: without it textures bake badly, but geometry+ // renders fine and the `verify` step reports the degraded outcome). Warn+ // and continue instead of aborting — checked AFTER the retry decision so+ // a transient failure still burns its retries first, and scoped to a step+ // failure so a cancel still propagates.+ if (step.optional && err?.code === 'TRELLIS2_INSTALL_FAILED') {+ onEvent({+ type: 'log',+ stage: step.stage,+ message: `⚠️ Optional step '${step.stage}' failed (${err.message}) — continuing; textures may bake at reduced quality.`,+ });+ return;+ }+ throw err;+ }const backoffMs = Math.min(30000, 2000 * 2 ** attempt);onEvent({type: 'log',diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex e212189629..5bff65c5c1 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -20,6 +20,7 @@ import {TRELLIS2_BAKE_QUALITY_MODULES,TRELLIS2_FALLBACK_BAKE_HELP,TRELLIS2_METAL_TOOLCHAIN_HINT,+ TRELLIS2_REQUIRES_XCODE_HINT,TRELLIS2_DEFAULT_TEXTURE_SIZE,TRELLIS2_TEXTURE_SIZES,} from './trellis2.js';@@ -67,6 +68,33 @@ describe('buildInstallSteps', () => {expect(steps[1]).toMatchObject({ command: 'bash', args: ['setup.sh'], cwd: trellis2Root(BASE) });});+ // #3041: setup.sh compiles the Metal packages from .metal sources, so the+ // toolchain must land BEFORE it runs or those builds fail silently.+ it('leads with the Metal Toolchain step when the toolchain is missing but fetchable', () => {+ const steps = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true });+ expect(steps.map((s) => s.stage)).toEqual(['metal-toolchain', 'clone', 'setup']);+ expect(steps[0]).toMatchObject({ command: 'xcodebuild', args: ['-downloadComponent', 'MetalToolchain'] });+ });++ it('marks the toolchain step optional — a missing bake degrades output, it does not break it', () => {+ const [toolchainStep] = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true });+ expect(toolchainStep.optional).toBe(true);+ // The required steps stay required, or a real failure would be swallowed.+ expect(buildInstallSteps(BASE, { exists: () => false }).every((s) => !s.optional)).toBe(true);+ });++ it('omits the toolchain step by default (already present / not macOS / not fetchable)', () => {+ expect(buildInstallSteps(BASE, { exists: () => false }).map((s) => s.stage))+ .toEqual(['clone', 'setup']);+ });++ it('does not let a caller mutate the shared toolchain step template', () => {+ const [step] = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true });+ step.args.push('--tampered');+ const [fresh] = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true });+ expect(fresh.args).toEqual(['-downloadComponent', 'MetalToolchain']);+ });+it('skips the clone step and resumes at setup.sh when the repo is already present', () => {// A prior install cloned the top-level repo but failed inside setup.sh (the// #2952 case). Re-cloning into the non-empty root would abort, so resume must@@ -185,19 +213,42 @@ describe('probeTrellis2TextureBake', () => {});describe('probeMetalToolchain', () => {+ // Dispatch on the probed command: `xcrun metal` reports presence, `xcode-select -p`+ // distinguishes full Xcode (can fetch the toolchain) from Command Line Tools only.+ const exec = ({ metal, developerDir }) => vi.fn((cmd, _args, _opts, cb) => {+ if (cmd === 'xcrun') return metal ? cb(null, 'Apple metal version 32023', '') : cb(new Error('missing Metal Toolchain'));+ return developerDir ? cb(null, developerDir, '') : cb(new Error('no developer dir'));+ });+it('is available when `xcrun metal --version` succeeds', () => expect(- probeMetalToolchain({- platformImpl: () => 'darwin',- execFileImpl: vi.fn((_c, _a, _o, cb) => cb(null, '', '')),- }),+ probeMetalToolchain({ platformImpl: () => 'darwin', execFileImpl: exec({ metal: true }) }),).resolves.toEqual({ available: true }));- it('is unavailable with a hint when the toolchain component is missing', async () => {+ it('is missing-but-installable on a host with full Xcode', async () => {const result = await probeMetalToolchain({platformImpl: () => 'darwin',- execFileImpl: vi.fn((_c, _a, _o, cb) => cb(new Error('missing Metal Toolchain'))),+ execFileImpl: exec({ metal: false, developerDir: '/Applications/Xcode.app/Contents/Developer\n' }),});- expect(result).toEqual({ available: false, hint: TRELLIS2_METAL_TOOLCHAIN_HINT });+ expect(result).toEqual({ available: false, installable: true, hint: TRELLIS2_METAL_TOOLCHAIN_HINT });+ });++ it('is blocked — not merely missing — when only the Command Line Tools are active', async () => {+ // `xcodebuild -downloadComponent` ships with full Xcode, so queueing the fetch+ // here would be a step guaranteed to fail; the hint must name Xcode instead.+ const result = await probeMetalToolchain({+ platformImpl: () => 'darwin',+ execFileImpl: exec({ metal: false, developerDir: '/Library/Developer/CommandLineTools\n' }),+ });+ expect(result).toMatchObject({ available: false, installable: false, blocker: 'requires-xcode' });+ expect(result.hint).toBe(TRELLIS2_REQUIRES_XCODE_HINT);+ });++ it('treats an unreadable developer dir as blocked rather than assuming Xcode', async () => {+ const result = await probeMetalToolchain({+ platformImpl: () => 'darwin',+ execFileImpl: exec({ metal: false, developerDir: null }),+ });+ expect(result).toMatchObject({ installable: false, blocker: 'requires-xcode' });});it('does not apply off macOS — null, not false, so no macOS-only warning is shown', async () => {@@ -522,6 +573,91 @@ describe('installTrellis2', () => {return events;};+ // #3041: the caller (the route) resolves the toolchain situation and passes a+ // plain boolean, so installTrellis2 keeps returning { promise, kill } synchronously.+ it('downloads the Metal Toolchain first when the caller says it is needed', async () => {+ const children = [makeChild(), makeChild(), makeChild()];+ let i = 0;+ const spawnImpl = vi.fn(() => children[i++]);+ const { promise } = installTrellis2({+ base: BASE,+ spawnImpl,+ installMetalToolchain: true,+ probeBake: async () => ({ quality: 'metal', missing: [] }),+ });+ expect(spawnImpl).toHaveBeenNthCalledWith(1, 'xcodebuild', ['-downloadComponent', 'MetalToolchain'], {});+ children[0].emit('close', 0);+ await flush();+ expect(spawnImpl).toHaveBeenNthCalledWith(2, 'git', expect.arrayContaining(['clone']), {});+ children[1].emit('close', 0);+ await flush();+ children[2].emit('close', 0);+ await expect(promise).resolves.toEqual({ ok: true });+ });++ it('continues the install when the optional toolchain step fails, and still verifies', async () => {+ // Geometry is unaffected by a missing bake, so a host that cannot fetch the+ // toolchain must still end up with a working (if degraded) install.+ const children = [makeChild(), makeChild(), makeChild()];+ let i = 0;+ const events = [];+ const { promise } = installTrellis2({+ base: BASE,+ spawnImpl: () => children[i++],+ onEvent: (e) => events.push(e),+ installMetalToolchain: true,+ probeBake: async () => ({ quality: 'fallback', missing: ['mtldiffrast'], help: 'degraded' }),+ });+ children[0].emit('close', 1); // toolchain download failed+ await flush();+ children[1].emit('close', 0);+ await flush();+ children[2].emit('close', 0);+ await expect(promise).resolves.toEqual({ ok: true });+ expect(events.find((e) => e.stage === 'metal-toolchain' && /Optional step/.test(e.message || ''))).toBeTruthy();+ expect(events.find((e) => e.stage === 'verify')?.message).toContain('degraded');+ });++ it('retries a TRANSIENT optional-step failure before giving up on it', async () => {+ // Optional-ness must not short-circuit the retry path — a dropped connection+ // during the toolchain download deserves the same retries as any other step.+ const children = [makeChild(), makeChild(), makeChild(), makeChild()];+ let i = 0;+ const spawnImpl = vi.fn(() => children[i++]);+ const { promise } = installTrellis2({+ base: BASE,+ spawnImpl,+ installMetalToolchain: true,+ maxRetries: 1,+ sleep: async () => {},+ probeBake: async () => ({ quality: 'fallback', missing: ['mtldiffrast'], help: 'degraded' }),+ });+ children[0].stderr.emit('data', 'fatal: early EOF');+ children[0].emit('close', 128);+ await flush();+ // Retried the toolchain step rather than moving straight on to the clone.+ expect(spawnImpl).toHaveBeenNthCalledWith(2, 'xcodebuild', ['-downloadComponent', 'MetalToolchain'], {});+ children[1].emit('close', 128); // retry exhausted → continue as optional+ await flush();+ expect(spawnImpl).toHaveBeenNthCalledWith(3, 'git', expect.arrayContaining(['clone']), {});+ children[2].emit('close', 0);+ await flush();+ children[3].emit('close', 0);+ await expect(promise).resolves.toEqual({ ok: true });+ });++ it('still aborts when a REQUIRED step fails, so optional-ness is not blanket', async () => {+ const children = [makeChild(), makeChild()];+ let i = 0;+ const { promise } = installTrellis2({+ base: BASE,+ spawnImpl: () => children[i++],+ maxRetries: 0,+ });+ children[0].emit('close', 1); // clone failed — not optional+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_INSTALL_FAILED', stage: 'clone' });+ });+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,