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-2954]): add a local-CUDA execution lane for image-to-3D
[._.]/ Adam Eivy60aef53c93f5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fb4c364d7a..9ec147ddc5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,13 @@# Unreleased+## Added++- **The 3D page can now generate on an NVIDIA GPU, not just on Apple Silicon.** Image-to-3D shipped with a single processing target — TRELLIS.2 running through the Apple Silicon (Metal) port — so a machine with a 24 GB NVIDIA card had nothing to select, even though the page had always described a CUDA lane as a thing it supported. There is now a second target, **TRELLIS.2 (CUDA)**, built on Microsoft's own upstream release: it installs the upstream repo and its GPU extensions, and renders a single image into the same PBR-textured GLB the Apple Silicon lane produces, with the same live progress and the same Install / Ready / cancel behaviour on the card. The export quality scales to the card rather than being fixed — a 24 GB GPU (the supported floor, and what upstream requires) renders at the proven settings, and a card with real headroom automatically gets the larger texture atlas and finer mesh that upstream's own reference settings use. Nothing about the Apple Silicon lane changes, and it remains the default, so an existing Mac install renders exactly as before.++ PortOS now actually looks at your GPU instead of assuming there isn't one: it reads the installed NVIDIA driver for each card and its memory, and that reading is what decides whether the CUDA target appears and which quality lane it uses. The check distinguishes three states rather than two, which is what keeps the card honest — "this machine has no NVIDIA GPU", "it has one, here's how much memory", and "the driver is installed but wouldn't answer" (a driver mid-update, most often). Only the first hides the target; the last says *"Could not detect this host's GPU"* rather than claiming you don't have one. On a machine with no NVIDIA hardware at all the CUDA target simply isn't listed, so a Mac's 3D page looks exactly as it does today rather than gaining a permanently-red card for hardware it will never have.++ Because upstream TRELLIS.2 builds its GPU extensions from source and supports Linux only, the target reports **"Requires a Linux host (use WSL2 on Windows)"** on a Windows machine that *does* have a qualifying card — a blocker worth naming, since it's one you can act on, unlike missing hardware. A Windows user reaches this lane by running PortOS inside WSL2, and a federated Linux + NVIDIA peer gets it directly. The same GPU reading also now drives the FLUX.2 image-gen installer's choice between the CUDA and CPU builds of PyTorch, so the two features can no longer disagree about what hardware is in the machine.+## Changed- **Quota Burn's per-family "Provider ID" and "Window scope" boxes are gone.** Both were free-text overrides for decisions the page already makes correctly on its own: the family match already prefers the watchable TUI provider over the headless CLI (a hand-typed id could only ever pick a worse one), and window targeting already reads *every* window on the card — the broadest one as the target the reset horizon and dispatch cap key on, the narrowest as the one that will refuse first, the tightest as the one the reserve guards. Scope was a free-text filter over that, so its realistic uses were "type the same thing the classifier already picked" or "type a word this provider doesn't publish and silently never burn." A job still carries its own optional `providerId`, which is the level where naming a specific provider actually means something. Configs written before this load unchanged — the normalizer drops both keys on the next save — and migration 221 no longer carries them over from the retired per-app shape.diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex 82a81baae9..40cf0fdc3b 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -71,6 +71,13 @@ const REASON_LABEL = {'requires-apple-silicon': 'Requires an Apple Silicon Mac','insufficient-memory': 'Needs 24 GB+ of unified memory','requires-cuda': 'Requires an NVIDIA CUDA GPU',+ 'insufficient-vram': 'Needs a 24 GB+ NVIDIA GPU',+ // Shown on a Windows host that HAS a qualifying card: upstream TRELLIS.2 builds+ // its CUDA extensions against a POSIX toolchain and is Linux-only, so WSL2 is the+ // supported route — name it, since this blocker is the one the user can act on.+ 'requires-linux-host': 'Requires a Linux host (use WSL2 on Windows)',+ // The probe itself failed — say so rather than claiming the GPU isn't there.+ 'cuda-probe-failed': 'Could not detect this host’s GPU','unknown-target': 'Unavailable',};diff --git a/server/lib/README.md b/server/lib/README.mdindex f14dfe4c63..c9ca533cea 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -278,6 +278,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |+| `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). || `db.js` | PostgreSQL connection pool. || `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. || `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.jsnew file mode 100644index 0000000000..78c11a855a--- /dev/null+++ b/server/lib/cudaCapability.js@@ -0,0 +1,175 @@+/**+ * NVIDIA CUDA host-capability probe.+ *+ * The single place PortOS asks "does this machine have a usable NVIDIA GPU, and+ * how much VRAM does its biggest card have?". Consumed by the image-to-3D target+ * registry (to gate the `local-cuda` execution lane) and by the FLUX.2 installer+ * (to decide between the CUDA and CPU torch wheels) — previously each had its own+ * `nvidia-smi` invocation and its own idea of what "no GPU" meant.+ *+ * **Three outcomes, never two.** Per the CLAUDE.md sentinel rule, "the probe could+ * not run" is NOT the same answer as "there is no GPU". The result carries a single+ * `status` (deliberately not a boolean, so there is no falsy value a caller can+ * accidentally read as "no GPU"):+ * - `'available'` — nvidia-smi listed at least one GPU.+ * - `'absent'` — no NVIDIA driver (`nvidia-smi` isn't on PATH), or it ran fine+ * and listed zero GPUs. A real, negative answer.+ * - `'unknown'` — nvidia-smi exists but failed or emitted something unparseable+ * (driver mismatch pending a reboot, a timeout, an ancient driver+ * without `--query-gpu`). Callers must say "couldn't detect"+ * rather than lying about the hardware.+ *+ * The probe is a subprocess boundary outside the request lifecycle, so every path+ * resolves — nothing throws into a route (CLAUDE.md child-process exception).+ */++import { execFile } from 'node:child_process';++/**+ * One CSV row per GPU: `<name>, <total VRAM in MiB>`. `nounits` strips the " MiB"+ * suffix so the column parses as a bare number. Verified against a real driver:+ * `0, NVIDIA GeForce RTX 3090, 24576, 596.36` for the fuller query — this narrower+ * one emits `NVIDIA GeForce RTX 3090, 24576`.+ */+export const NVIDIA_SMI_QUERY_ARGS = Object.freeze([+ '--query-gpu=name,memory.total',+ '--format=csv,noheader,nounits',+]);++/**+ * Parse `nvidia-smi --query-gpu=name,memory.total` CSV output into GPU descriptors.+ * Pure, so the format is covered deterministically instead of depending on whatever+ * card the test host happens to have.+ *+ * A row whose VRAM column doesn't parse (some vGPU/MIG configurations report `[N/A]`)+ * still counts as a GPU — it is present, we just can't size it — and carries+ * `vramGb: null`. Dropping it would under-report the host as having no GPU at all;+ * reporting `0` would look like a card that fails every memory floor. `null` is the+ * honest "present, size unknown", and callers gate on `Number.isFinite`.+ *+ * @param {string} stdout+ * @returns {Array<{name: string, vramMib: number|null, vramGb: number|null}>}+ */+export function parseNvidiaSmiGpus(stdout) {+ const gpus = [];+ for (const raw of String(stdout ?? '').split(/\r?\n/)) {+ const line = raw.trim();+ if (!line) continue;+ // Card names never contain a comma, so a plain split is enough; take the first+ // two columns and ignore any extra the query might grow.+ const [name, mib] = line.split(',').map((cell) => cell.trim());+ if (!name) continue;+ const vramMib = Number(mib);+ const sized = Number.isFinite(vramMib) && vramMib > 0;+ gpus.push({+ name,+ vramMib: sized ? vramMib : null,+ // Round to whole GB for the same reason unified memory is rounded: a "24 GB"+ // card reports a hair under 24 GiB and must not trip a 24 GB floor.+ vramGb: sized ? Math.round(vramMib / 1024) : null,+ });+ }+ return gpus;+}++/**+ * Probe this machine for NVIDIA GPUs. Always resolves — see the three outcomes in+ * the file header. `execFileImpl` is injectable so every branch is unit-testable+ * without an NVIDIA box (and without one being *absent* on a CI Mac either).+ *+ * @param {{execFileImpl?: Function, timeoutMs?: number}} [opts]+ * @returns {Promise<{status: 'available'|'absent'|'unknown',+ * gpus: Array<object>, maxVramGb: number|null, error: string|null}>}+ */+export async function detectCudaGpus({ execFileImpl = execFile, timeoutMs = 8000 } = {}) {+ const result = await new Promise((resolve) => {+ execFileImpl(+ 'nvidia-smi',+ [...NVIDIA_SMI_QUERY_ARGS],+ { timeout: timeoutMs, windowsHide: true },+ (err, stdout) => resolve({ err, stdout: String(stdout ?? '') }),+ );+ }).catch((err) => ({ err, stdout: '' }));++ if (result.err) {+ // `nvidia-smi` isn't installed at all ⇒ no NVIDIA driver on this host. That is a+ // real negative answer, not a failed probe — the binary ships with the driver.+ if (result.err.code === 'ENOENT') {+ return { status: 'absent', gpus: [], maxVramGb: null, error: null };+ }+ // It exists but wouldn't answer (driver/library mismatch, timeout, old driver+ // without --query-gpu). We genuinely do not know what hardware is here.+ return {+ status: 'unknown',+ gpus: [],+ maxVramGb: null,+ error: result.err.message || 'nvidia-smi failed',+ };+ }++ const gpus = parseNvidiaSmiGpus(result.stdout);+ if (!gpus.length) {+ // Exit 0 with no rows: the driver is installed and reports zero GPUs.+ return { status: 'absent', gpus: [], maxVramGb: null, error: null };+ }+ const sizes = gpus.map((g) => g.vramGb).filter((gb) => Number.isFinite(gb));+ return {+ status: 'available',+ gpus,+ // The biggest single card — a render runs on one GPU, so summing would advertise+ // capacity no single job can use.+ maxVramGb: sizes.length ? Math.max(...sizes) : null,+ error: null,+ };+}++// `null` = never probed (distinct from a probed result that says "no GPU"). Holds the+// in-flight promise so concurrent callers share one subprocess rather than racing+// several `nvidia-smi` spawns.+let cachedProbe = null;+// Epoch ms at which the memo goes stale. `Infinity` for a definitive answer (GPU+// hardware doesn't change while the server runs); a short horizon for `unknown`.+let cacheExpiresAt = Infinity;++/**+ * How long an `unknown` verdict is held before the probe is retried. Short enough that+ * a driver that comes back (a reboot, a finished update) is picked up promptly, long+ * enough that a *persistently* broken driver — where `nvidia-smi` hangs until its+ * timeout — costs one stalled spawn a minute instead of one per request. Without this+ * bound, a wedged GPU adds the full probe timeout to every `/targets` load and every+ * generate call.+ */+export const CUDA_UNKNOWN_RETRY_MS = 60_000;++/**+ * Cached `detectCudaGpus()`. GPU hardware doesn't change while the server runs, so+ * the answer is memoized — this is called per `/targets` request and a spawn on each+ * would be pure waste.+ *+ * An `unknown` result is cached only briefly (`CUDA_UNKNOWN_RETRY_MS`) rather than for+ * the process lifetime: it means the probe itself failed, often transiently (a driver+ * mid-update), so pinning it would hide a GPU that becomes visible a minute later —+ * but re-probing on every call would make a persistently-wedged driver cost a stalled+ * subprocess per request.+ *+ * @param {{refresh?: boolean, now?: () => number, execFileImpl?: Function,+ * timeoutMs?: number}} [opts]+ * @returns {Promise<object>} the `detectCudaGpus` result+ */+export async function getCudaCapability({ refresh = false, now = Date.now, ...probeOpts } = {}) {+ if (!refresh && cachedProbe && now() < cacheExpiresAt) return cachedProbe;+ const pending = detectCudaGpus(probeOpts);+ cachedProbe = pending;+ // Assume definitive until proven otherwise, and set it BEFORE the await so+ // concurrent callers share this probe instead of each spawning their own.+ cacheExpiresAt = Infinity;+ const result = await pending;+ if (result.status === 'unknown') cacheExpiresAt = now() + CUDA_UNKNOWN_RETRY_MS;+ return result;+}++/** Drop the memoized probe — for tests and for a forced re-detect. */+export function resetCudaCapabilityCache() {+ cachedProbe = null;+ cacheExpiresAt = Infinity;+}diff --git a/server/lib/cudaCapability.test.js b/server/lib/cudaCapability.test.jsnew file mode 100644index 0000000000..837725f5e7--- /dev/null+++ b/server/lib/cudaCapability.test.js@@ -0,0 +1,171 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ NVIDIA_SMI_QUERY_ARGS,+ parseNvidiaSmiGpus,+ detectCudaGpus,+ getCudaCapability,+ resetCudaCapabilityCache,+ CUDA_UNKNOWN_RETRY_MS,+} from './cudaCapability.js';++// Real output from `nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits`+// on an RTX 3090 box (driver 596.36). Kept verbatim so a format change is caught here.+const RTX_3090 = 'NVIDIA GeForce RTX 3090, 24576\n';++/** An execFile stub that invokes the callback with `(err, stdout)`. */+const execStub = (err, stdout = '') => vi.fn((_cmd, _args, _opts, cb) => cb(err, stdout));++beforeEach(() => resetCudaCapabilityCache());++describe('parseNvidiaSmiGpus', () => {+ it('parses a real single-GPU reading and rounds VRAM to whole GB', () => {+ expect(parseNvidiaSmiGpus(RTX_3090)).toEqual([+ { name: 'NVIDIA GeForce RTX 3090', vramMib: 24576, vramGb: 24 },+ ]);+ });++ it('parses several GPUs and tolerates CRLF and blank lines', () => {+ const gpus = parseNvidiaSmiGpus('NVIDIA A100, 40960\r\n\r\nNVIDIA L40S, 46068\r\n');+ expect(gpus.map((g) => g.name)).toEqual(['NVIDIA A100', 'NVIDIA L40S']);+ expect(gpus.map((g) => g.vramGb)).toEqual([40, 45]);+ });++ it('rounds a card reading a hair under its marketed size up to that size', () => {+ // A "24 GB" card commonly reports 24268 MiB — it must not miss a 24 GB floor.+ expect(parseNvidiaSmiGpus('NVIDIA RTX A5000, 24268')[0].vramGb).toBe(24);+ });++ it('keeps a GPU whose VRAM column is unreadable, sized null rather than dropped or zero', () => {+ // Some vGPU/MIG configurations report [N/A]. The card IS there; we just can't+ // size it — reporting no GPU, or a 0 GB one, would both be wrong.+ expect(parseNvidiaSmiGpus('GRID V100D-32Q, [N/A]')).toEqual([+ { name: 'GRID V100D-32Q', vramMib: null, vramGb: null },+ ]);+ });++ it('returns an empty list for empty or nullish output', () => {+ for (const input of ['', ' \n\n', null, undefined]) {+ expect(parseNvidiaSmiGpus(input)).toEqual([]);+ }+ });+});++describe('detectCudaGpus', () => {+ it('queries nvidia-smi with the CSV/nounits args and reports the largest card', async () => {+ const execFileImpl = execStub(null, 'NVIDIA A100, 40960\nNVIDIA GeForce RTX 3090, 24576\n');+ const result = await detectCudaGpus({ execFileImpl });++ expect(execFileImpl).toHaveBeenCalledWith(+ 'nvidia-smi',+ [...NVIDIA_SMI_QUERY_ARGS],+ expect.objectContaining({ windowsHide: true }),+ expect.any(Function),+ );+ expect(result).toMatchObject({ status: 'available', maxVramGb: 40 });+ expect(result.gpus).toHaveLength(2);+ });++ it('reports maxVramGb from the biggest single card, not the sum', async () => {+ // A render runs on one GPU — summing would advertise capacity no job can use.+ const result = await detectCudaGpus({ execFileImpl: execStub(null, 'A, 24576\nB, 24576\n') });+ expect(result.maxVramGb).toBe(24);+ });++ it('treats a missing nvidia-smi as a definitive "no GPU", not a failed probe', async () => {+ const enoent = Object.assign(new Error('spawn nvidia-smi ENOENT'), { code: 'ENOENT' });+ expect(await detectCudaGpus({ execFileImpl: execStub(enoent) })).toMatchObject({+ status: 'absent',+ maxVramGb: null,+ });+ });++ it('treats an installed-but-failing nvidia-smi as UNKNOWN, never as "no GPU"', async () => {+ // Driver/library mismatch pending a reboot: the hardware may well be present.+ const err = Object.assign(new Error("couldn't communicate with the NVIDIA driver"), { code: 9 });+ const result = await detectCudaGpus({ execFileImpl: execStub(err) });+ expect(result.status).toBe('unknown');+ // No boolean field exists to be misread as "no GPU" — status is the only answer.+ expect(result).not.toHaveProperty('available');+ expect(result.error).toMatch(/NVIDIA driver/);+ });++ it('treats a clean run listing zero GPUs as absent', async () => {+ expect(await detectCudaGpus({ execFileImpl: execStub(null, '\n') })).toMatchObject({+ status: 'absent',+ });+ });++ it('resolves rather than throwing when the spawn itself blows up', async () => {+ const execFileImpl = vi.fn(() => { throw new Error('spawn exploded'); });+ // A probe runs outside the request lifecycle — a throw here would crash the process.+ expect(await detectCudaGpus({ execFileImpl })).toMatchObject({ status: 'unknown' });+ });+});++describe('getCudaCapability caching', () => {+ it('probes once and serves the cached answer afterwards', async () => {+ const execFileImpl = execStub(null, RTX_3090);+ await getCudaCapability({ execFileImpl });+ await getCudaCapability({ execFileImpl });+ expect(execFileImpl).toHaveBeenCalledTimes(1);+ });++ it('shares one subprocess between concurrent callers', async () => {+ const execFileImpl = execStub(null, RTX_3090);+ const [a, b] = await Promise.all([+ getCudaCapability({ execFileImpl }),+ getCudaCapability({ execFileImpl }),+ ]);+ expect(execFileImpl).toHaveBeenCalledTimes(1);+ expect(a).toEqual(b);+ });++ it('re-probes after refresh', async () => {+ const execFileImpl = execStub(null, RTX_3090);+ await getCudaCapability({ execFileImpl });+ await getCudaCapability({ execFileImpl, refresh: true });+ expect(execFileImpl).toHaveBeenCalledTimes(2);+ });++ it('caches a definitive "absent" answer', async () => {+ const enoent = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });+ const execFileImpl = execStub(enoent);+ await getCudaCapability({ execFileImpl });+ await getCudaCapability({ execFileImpl });+ expect(execFileImpl).toHaveBeenCalledTimes(1);+ });++ it('holds an unknown result only briefly, then re-probes', async () => {+ const failing = execStub(Object.assign(new Error('driver busy'), { code: 9 }));+ let clock = 1_000_000;+ const now = () => clock;++ await getCudaCapability({ execFileImpl: failing, now });+ // Within the retry window a wedged driver must NOT be re-spawned per call —+ // nvidia-smi can hang until its timeout, so that would stall every request.+ await getCudaCapability({ execFileImpl: failing, now });+ await getCudaCapability({ execFileImpl: failing, now });+ expect(failing).toHaveBeenCalledTimes(1);++ // Past the window it tries again, so a driver that comes back is picked up.+ clock += CUDA_UNKNOWN_RETRY_MS + 1;+ await getCudaCapability({ execFileImpl: failing, now });+ expect(failing).toHaveBeenCalledTimes(2);+ });++ it('caches a recovered answer indefinitely once the driver responds', async () => {+ const failing = execStub(Object.assign(new Error('driver busy'), { code: 9 }));+ let clock = 1_000_000;+ const now = () => clock;+ await getCudaCapability({ execFileImpl: failing, now });++ clock += CUDA_UNKNOWN_RETRY_MS + 1;+ const recovered = execStub(null, RTX_3090);+ expect(await getCudaCapability({ execFileImpl: recovered, now })).toMatchObject({+ status: 'available',+ });+ clock += CUDA_UNKNOWN_RETRY_MS * 100;+ await getCudaCapability({ execFileImpl: recovered, now });+ expect(recovered).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 795c46f842..7ced684026 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -251,6 +251,7 @@ export * from './vaultCrypto.js';// === Model & config ===export * from './browserConfig.js';export * from './buildId.js';+export * from './cudaCapability.js';export * from './db.js';export * from './pgTimestamp.js';export * from './pgTools.js';diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex fa5e86dfbc..ea50c4ccba 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -6,6 +6,7 @@ import { promisify } from 'node:util';import { PATHS } from './fileUtils.js';import { safeChildProcessEnv, whichFirst } from './processEnv.js';import { createLineReader } from './streamLines.js';+import { getCudaCapability } from './cudaCapability.js';const execFileAsync = promisify(execFile);const IS_WIN = platform() === 'win32';@@ -133,14 +134,17 @@ export async function detectArm64Python() {return firstArchMatch(present, (a) => a === 'arm64');}-// True when an NVIDIA GPU is present (nvidia-smi lists at least one device).-// Used to decide whether the Windows FLUX.2 install pulls CUDA torch from the-// PyTorch index vs. the default CPU wheel. Best-effort: a missing nvidia-smi-// or any failure reads as "no GPU".+// True when an NVIDIA GPU is present. Used to decide whether the Windows FLUX.2+// install pulls CUDA torch from the PyTorch index vs. the default CPU wheel.+// Delegates to the shared probe in `cudaCapability.js` so there is one place that+// knows how to interrogate `nvidia-smi` (the image-to-3D `local-cuda` lane reads+// the richer result — VRAM per card — from the same cached call).+//+// Collapses the probe's three-way answer to a boolean deliberately: for a torch wheel+// choice, "couldn't detect" must behave like "no GPU" — a CUDA wheel on a host without+// one is an unusable venv, while the CPU wheel is merely slow.export async function hasNvidiaGpu() {- const { stdout } = await execFileAsync('nvidia-smi', ['-L'], { timeout: 8000 })- .catch(() => ({ stdout: '' }));- return /GPU \d+:/.test(stdout);+ return (await getCudaCapability()).status === 'available';}// FLUX.2 runs in its own venv because mflux (MLX) and torch+diffusers-from-gitdiff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex 86f4ed7d16..0669bcc27c 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -214,6 +214,7 @@ describe('every cwd-passing spawn pins PWD', () => {['services/appDeployer.js', 'deploy shell commands, not an AI CLI'],['services/xcodeScripts.js', 'xcodebuild/ls, not an AI CLI'],['services/imageTo3d/trellis2.js', 'python/uv toolchain inside its own install root'],+ ['services/imageTo3d/laneRunner.js', 'git/bash/python install + render steps inside a target install root, not an AI CLI'],['services/updateExecutor.js', "PortOS's own update scripts, run in the PortOS root by design"],['routes/database.js', 'psql/pg_dump, not an AI CLI'],['routes/scaffold.js', 'npm/git scaffolding, not an AI CLI'],diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex c0b005e709..a7b43fae80 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -51,7 +51,7 @@ const installsInFlight = new Set();* new branch here.*/router.get('/targets', asyncHandler(async (_req, res) => {- const capabilities = detectHostCapabilities();+ const capabilities = await detectHostCapabilities();const targets = await Promise.all(listTargets(capabilities).map(async (target) => {const adapter = getTargetAdapter(target.id);const installed = adapter ? adapter.isInstalled() : null;@@ -102,7 +102,7 @@ async function handleTargetInstall(targetId, req, res) {// Refuse on unsupported hardware rather than clone a multi-GB install that can// never run.- const capabilities = detectHostCapabilities();+ const capabilities = await detectHostCapabilities();if (!isTargetAvailable(targetId, capabilities)) {send({type: 'error',diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.jsindex c931982738..ca6fdd4292 100644--- a/server/services/imageTo3d/adapters.js+++ b/server/services/imageTo3d/adapters.js@@ -42,6 +42,11 @@ import {probeTrellis2TextureBake,probeMetalToolchain,} from './trellis2.js';+import {+ isTrellis2CudaInstalled,+ installTrellis2Cuda,+ runTrellis2CudaGenerate,+} from './trellis2Cuda.js';export const TARGET_ADAPTERS = Object.freeze({trellis2: Object.freeze({@@ -80,6 +85,24 @@ export const TARGET_ADAPTERS = Object.freeze({};},}),+ trellis2Cuda: Object.freeze({+ isInstalled: isTrellis2CudaInstalled,+ // Upstream's 4B pipeline conditions on the gated DINOv3 repo, so this lane needs+ // the resolved Hugging Face token for both install and render — same as the MPS+ // lane, resolved through the same helper.+ resolveEnv: hfChildEnv,+ install: installTrellis2Cuda,+ // The export budget (atlas size + decimation target) scales with the card. `run`+ // must stay synchronous to keep its { promise, kill } contract, so it cannot+ // probe — it reads the VRAM out of the capabilities the dispatcher resolved at+ // the request boundary and passed down. An absent/unsized card yields `null`, and+ // the runner picks the conservative 24 GB-floor lane: degraded quality, never an+ // overcommitted GPU.+ run: ({ caps, ...opts }) => runTrellis2CudaGenerate({+ ...opts,+ vramGb: caps?.cudaVramGb ?? null,+ }),+ }),});/**diff --git a/server/services/imageTo3d/laneRunner.js b/server/services/imageTo3d/laneRunner.jsnew file mode 100644index 0000000000..fe7a1dc529--- /dev/null+++ b/server/services/imageTo3d/laneRunner.js@@ -0,0 +1,272 @@+/**+ * Image-to-3D — shared execution-lane subprocess machinery.+ *+ * Every local target installs the same way (run an ordered list of shell steps,+ * retrying the ones that fail on a network blip) and renders the same way (spawn a+ * generator, stream its output through a progress parser, classify a non-zero exit).+ * Only the *steps*, the *arguments*, and the *error vocabulary* differ per lane.+ *+ * This module owns that machinery once so a second lane is a step list plus an arg+ * builder — not a copy of the retry policy, the cancel semantics, and the+ * `{ promise, kill }` contract. Both TRELLIS.2 lanes (`trellis2.js` on Apple+ * Silicon/MPS, `trellis2Cuda.js` on NVIDIA/CUDA) are built on it; it is deliberately+ * target-agnostic (no TRELLIS-specific paths, repos, or progress vocabulary — those+ * are injected), so a future non-TRELLIS clone-and-setup target reuses it as-is.+ *+ * Everything here is a child-process boundary running OUTSIDE the request lifecycle,+ * so outcomes flow through events and rejected promises — never a throw into Express+ * (CLAUDE.md child-process exception).+ */++import { spawn } from 'node:child_process';+import { sleep as defaultSleep } from '../../lib/fileUtils.js';+import { killWithEscalation } from '../../lib/killWithEscalation.js';++/**+ * Build a case-insensitive predicate testing text against an alternation of signature+ * phrases — the shape every subprocess-error classifier in this feature uses (each+ * keeps its own domain-specific phrase list; only the plumbing is shared).+ * @param {string[]} phrases+ * @returns {(text: string) => boolean}+ */+export function textMatcher(phrases) {+ const re = new RegExp(phrases.join('|'), 'i');+ return (text) => re.test(String(text ?? ''));+}++/**+ * Append a chunk of subprocess output to a bounded tail (the last `max` chars), so a+ * non-zero exit can be classified from the trailing output without retaining the+ * whole stream. Used at every child-process boundary in both lanes.+ * @param {string} prev+ * @param {*} buf+ * @param {number} [max]+ * @returns {string}+ */+export function appendTail(prev, buf, max = 4000) {+ return `${prev}${buf}`.slice(-max);+}++/**+ * Run an ordered install plan as a killable, event-emitting job.+ *+ * Emits `{type:'stage'}` per step, `{type:'log'}` for subprocess output, and a+ * terminal `{type:'complete'}`; rejects on a failed or canceled step so an SSE route+ * can emit `{type:'error'}`.+ *+ * **Transient-failure retry.** A multi-GB install over half a dozen git clones and pip+ * fetches routinely eats a mid-transfer `Connection reset` / `early EOF` (#2952) that+ * exits git 128. Install steps are *idempotent* — git removes a failed clone's target+ * dir, and setup scripts skip already-completed pieces — so a step whose output matches+ * the caller's `isTransient` signature is retried in place with a capped exponential+ * backoff. A non-transient failure (bad config, unsupported host, real setup error) is+ * NOT retried; it fails fast. `sleep` is injectable so tests don't wait on real backoff.+ *+ * **`optional` steps degrade rather than break.** A step marked `optional` that fails+ * for a non-transient reason (after burning its retries) warns and continues — for work+ * that lowers output quality but doesn't stop the install, like the MPS lane's Metal+ * Toolchain fetch (#3041). Checked AFTER the retry decision so a transient failure still+ * retries first, and scoped to a step failure so a cancel still propagates.+ *+ * @param {{steps: Array<{stage: string, command: string, args: string[], cwd?: string, optional?: boolean}>,+ * label: string, codePrefix: string, isTransient: (text: string) => boolean,+ * onEvent?: (ev: object) => void, spawnImpl?: Function, maxRetries?: number,+ * sleep?: (ms: number) => Promise<void>, env?: NodeJS.ProcessEnv,+ * verify?: (emit: (ev: object) => void) => void|Promise<void>,+ * completeMessage?: string}} opts+ * @returns {{promise: Promise<{ok: true}>, kill: () => void}}+ */+export function runInstallSteps({+ steps,+ label,+ codePrefix,+ isTransient,+ onEvent = () => {},+ spawnImpl = spawn,+ maxRetries = 3,+ sleep = defaultSleep,+ env,+ verify,+ completeMessage,+}) {+ let currentChild = null;+ let canceled = false;++ const canceledError = () => {+ const err = new Error(`${label} install canceled`);+ err.code = `${codePrefix}_INSTALL_CANCELED`;+ return err;+ };++ const runStep = (step) => new Promise((resolve, reject) => {+ onEvent({ type: 'stage', stage: step.stage, message: `${step.command} ${step.args.join(' ')}` });+ const child = spawnImpl(step.command, step.args, {+ ...(step.cwd ? { cwd: step.cwd } : {}),+ ...(env ? { env } : {}),+ });+ currentChild = child;+ // Retain a bounded tail so a non-zero exit can be classified as transient-network+ // vs. a real failure — the clue is in the subprocess text, not the exit code (git+ // exits 128 for both a network drop and a bad ref).+ let outputTail = '';+ const log = (buf) => {+ const message = String(buf).trim();+ if (message) onEvent({ type: 'log', stage: step.stage, message });+ outputTail = appendTail(outputTail, buf);+ };+ child.stdout?.on('data', log);+ child.stderr?.on('data', log);+ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 0) {+ resolve();+ return;+ }+ const err = new Error(`${label} install step '${step.stage}' exited ${code}`);+ err.code = `${codePrefix}_INSTALL_FAILED`;+ err.stage = step.stage;+ err.transient = isTransient(outputTail);+ reject(err);+ });+ });++ const runStepWithRetry = async (step) => {+ for (let attempt = 0; ; attempt += 1) {+ if (canceled) throw canceledError();+ try {+ await runStep(step);+ return;+ } catch (err) {+ const failedStep = err?.code === `${codePrefix}_INSTALL_FAILED`;+ const canRetry = failedStep && err.transient && attempt < maxRetries && !canceled;+ if (!canRetry) {+ if (step.optional && failedStep) {+ onEvent({+ type: 'log',+ stage: step.stage,+ message: `⚠️ Optional step '${step.stage}' failed (${err.message}) — continuing; output may be reduced quality.`,+ });+ return;+ }+ throw err;+ }+ const backoffMs = Math.min(30000, 2000 * 2 ** attempt);+ onEvent({+ type: 'log',+ stage: step.stage,+ message: `⚠️ Transient network error — retrying in ${Math.round(backoffMs / 1000)}s (attempt ${attempt + 2}/${maxRetries + 1})…`,+ });+ await sleep(backoffMs);+ }+ }+ };++ const promise = (async () => {+ for (const step of steps) {+ if (canceled) throw canceledError();+ await runStepWithRetry(step);+ }+ // A setup script can exit 0 with pieces of itself missing, so a bare success would+ // report an install that silently renders garbage (#2952). The lane's own verify+ // runs BEFORE the terminal `complete` frame, which closes the client's EventSource.+ if (verify) await verify(onEvent);+ onEvent({ type: 'complete', message: completeMessage || `${label} installed.` });+ return { ok: true };+ })();++ const kill = () => {+ canceled = true;+ if (currentChild && typeof currentChild.kill === 'function') currentChild.kill('SIGTERM');+ };++ return { promise, kill };+}++/**+ * Spawn a generator subprocess and drive it to a produced asset.+ *+ * Streams combined stdout/stderr through `parseProgress` one line at a time, tracking+ * the produced asset path, and resolves `{ assetPath }` once the child exits 0 and the+ * asset has been post-processed.+ *+ * Output is split on `\r` AND `\n`: tqdm redraws its progress bar in place with+ * carriage returns, so a single chunk can carry several frames separated only by `\r`.+ * Splitting on `\n` alone would treat them as one line and parse just the first+ * (lowest) percent — under-reporting progress during the long sampling phase.+ *+ * `classifiers` turn a non-zero exit into an actionable error instead of a bare+ * "exited N" — each is `{ test, code, help }` and the first match wins, so a lane can+ * name a gated-model or out-of-memory failure the user can actually fix.+ *+ * @param {{command: string, args: string[], cwd?: string, env?: NodeJS.ProcessEnv,+ * label: string, codePrefix: string, parseProgress: (line: string) => object|null,+ * assetPath?: string|null, onProgress?: (frame: object) => void,+ * spawnImpl?: Function, postprocessGlb?: (path: string) => void|Promise<void>,+ * classifiers?: Array<{test: (text: string) => boolean, code: string, help: string|(() => string)}>}} opts+ * @returns {{promise: Promise<{assetPath: string}>, kill: () => void}}+ */+export function runGenerateSubprocess({+ command,+ args,+ cwd,+ env,+ label,+ codePrefix,+ parseProgress,+ assetPath: initialAssetPath = null,+ onProgress,+ spawnImpl = spawn,+ postprocessGlb,+ classifiers = [],+}) {+ const child = spawnImpl(command, args, { ...(cwd ? { cwd } : {}), ...(env ? { env } : {}) });+ let assetPath = initialAssetPath;+ let outputTail = '';+ const promise = new Promise((resolve, reject) => {+ const ingest = (buf) => {+ outputTail = appendTail(outputTail, buf);+ for (const line of String(buf).split(/[\r\n]+/)) {+ const frame = parseProgress(line);+ if (!frame) continue;+ if (frame.assetPath) assetPath = frame.assetPath;+ if (onProgress) onProgress(frame);+ }+ };+ child.stdout?.on('data', ingest);+ child.stderr?.on('data', ingest);+ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 0 && assetPath) {+ Promise.resolve()+ .then(() => (postprocessGlb ? postprocessGlb(assetPath) : undefined))+ .then(() => resolve({ assetPath }))+ .catch((cause) => {+ const error = new Error(`${label} produced a GLB but material normalization failed: ${cause.message}`);+ error.code = `${codePrefix}_GLB_POSTPROCESS_FAILED`;+ reject(error);+ });+ return;+ }+ if (code !== 0) {+ // User-fixable setup/resource problems get named as such rather than+ // surfacing as an opaque exit code.+ const match = classifiers.find((c) => c.test(outputTail));+ if (match) {+ const err = new Error(typeof match.help === 'function' ? match.help() : match.help);+ err.code = match.code;+ reject(err);+ return;+ }+ }+ const err = new Error(+ code === 0 ? `${label} finished but produced no .glb` : `${label} generate exited ${code}`,+ );+ err.code = `${codePrefix}_GENERATE_FAILED`;+ reject(err);+ });+ });+ // Single captured child, never replaced — the helper's own exit check gates the+ // SIGKILL escalation, so `stillRunning` is unconditionally true here.+ const kill = () => killWithEscalation(child, { label: `${label} generate`, stillRunning: () => true });+ return { promise, kill };+}diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex c70a920c74..0fffceea49 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -110,7 +110,7 @@ async function failGeneration(id, operationId, error) {});}-async function executeRender({ id, operationId, adapter, sourcePath }) {+async function executeRender({ id, operationId, adapter, sourcePath, caps }) {const outputPath = assetDiskPath(id);let lastPersistedPercent = -1;try {@@ -127,6 +127,12 @@ async function executeRender({ id, operationId, adapter, sourcePath }) {imagePath: sourcePath,outputPath,env,+ // The host capabilities resolved at the request boundary, passed down rather+ // than re-probed: a target whose output budget scales with the hardware (the+ // CUDA lane's atlas size, keyed on VRAM) reads the same values the readiness+ // gate used, instead of reaching for a module-global snapshot that an injected+ // `caps` would leave unset.+ caps,onProgress: (frame) => {// Sparse, low-frequency render progress — persist only when the whole// percent actually advances so a chatty parser can't hot-write the row.@@ -210,7 +216,10 @@ export async function deleteModel(id) {return result;}-export async function createModel(input, { caps = detectHostCapabilities() } = {}) {+// `detectHostCapabilities` is async (its CUDA half shells to nvidia-smi), so it+// can't be a default parameter — resolve it in the body, and only when the caller+// didn't already supply capabilities.+export async function createModel(input, { caps } = {}) {const sourcePath = resolveGalleryImage(input.filename);if (!sourcePath) {throw new ServerError('Gallery image not found', { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });@@ -218,16 +227,17 @@ export async function createModel(input, { caps = detectHostCapabilities() } = {const targetId = input.target || DEFAULT_IMAGE_TO_3D_TARGET;// Validate the target is runnable BEFORE persisting a record so we never leave// a dangling draft when the host can't render / the model isn't installed.- const adapter = assertTargetReady(targetId, caps);+ const hostCaps = caps ?? await detectHostCapabilities();+ const adapter = assertTargetReady(targetId, hostCaps);const created = await store.createModel({ ...input, target: targetId });// Thread the already-validated adapter + resolved source straight into the// render — createModel and startGeneration share `beginRender`, so the create// path does NOT re-resolve the gallery image, re-assert readiness, or re-fetch// the row it just wrote.- return beginRender(created, adapter, sourcePath);+ return beginRender(created, adapter, sourcePath, hostCaps);}-export async function startGeneration(id, { caps = detectHostCapabilities() } = {}) {+export async function startGeneration(id, { caps } = {}) {const current = await store.getModel(id);if (!current) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });if (current.status === 'generating'@@ -235,12 +245,13 @@ export async function startGeneration(id, { caps = detectHostCapabilities() } =throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });}- const adapter = assertTargetReady(current.target, caps);+ const hostCaps = caps ?? await detectHostCapabilities();+ const adapter = assertTargetReady(current.target, hostCaps);const sourcePath = resolveGalleryImage(current.sourceImage?.filename);if (!sourcePath) {throw new ServerError('The source gallery image is no longer available', { status: 409, code: 'GALLERY_IMAGE_NOT_FOUND' });}- return beginRender(current, adapter, sourcePath);+ return beginRender(current, adapter, sourcePath, hostCaps);}/**@@ -250,7 +261,7 @@ export async function startGeneration(id, { caps = detectHostCapabilities() } =* adapter + source through. The transactional `status==='generating'` guard here* is the authoritative race check (the callers' pre-check is just a fast 409).*/-async function beginRender(record, adapter, sourcePath) {+async function beginRender(record, adapter, sourcePath, caps) {const { id } = record;const operationId = randomUUID();const startedAt = new Date().toISOString();@@ -280,7 +291,7 @@ async function beginRender(record, adapter, sourcePath) {activeOperations.add(operationId);setImmediate(() => {- void executeRender({ id, operationId, adapter, sourcePath });+ void executeRender({ id, operationId, adapter, sourcePath, caps });});return next;}diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.jsindex 55eebe48eb..ed41d1da31 100644--- a/server/services/imageTo3d/targets.js+++ b/server/services/imageTo3d/targets.js@@ -11,7 +11,8 @@* capabilities as an injected argument rather than probing hardware themselves.* Only `detectHostCapabilities()` touches the real machine, so it's the one* impure boundary (mirroring `platform.js`'s "detect at the route boundary and- * pass into pure services" contract). A target's actual installer/runner is+ * pass into pure services" contract) — and the only async export here, because+ * sizing an NVIDIA card means shelling to `nvidia-smi`. A target's installer/runner is* wired separately, in `adapters.js` — keeping runner imports out of this file* is what lets it stay a pure, no-side-effect registry that boot and tests can* import for free (#3080).@@ -19,6 +20,7 @@import os from 'os';import { isAppleSilicon } from '../../lib/platform.js';+import { getCudaCapability } from '../../lib/cudaCapability.js';/*** How a target's inference actually runs. A target declares exactly one lane;@@ -83,6 +85,39 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({}),]),}),+ trellis2Cuda: Object.freeze({+ id: 'trellis2Cuda',+ label: 'TRELLIS.2 (CUDA)',+ description:+ 'Microsoft TRELLIS.2 — single image to a PBR-textured GLB mesh, run on-device '+ + 'on an NVIDIA GPU via the upstream CUDA build.',+ executionLane: EXECUTION_LANE.LOCAL_CUDA,+ outputKind: OUTPUT_KIND.GLB_MESH,+ // Upstream's own stated floor: "An NVIDIA GPU with at least 24GB of memory is+ // necessary", CUDA 12.4, Python 3.8+, and "currently tested only on Linux".+ // `linuxHost` is therefore a real requirement, not conservatism — `setup.sh`+ // builds CUDA extensions (flash-attn, nvdiffrast, nvdiffrec, cumesh) from+ // source against a POSIX toolchain. A Windows box with a 24 GB card reaches+ // this lane through WSL2, where PortOS reports `linuxHost: true`.+ requires: Object.freeze({+ cuda: true,+ minVramGb: 24,+ linuxHost: true,+ diskGb: 15,+ python: '3.10',+ }),+ upstream: 'https://github.com/microsoft/TRELLIS.2',+ weightsRepo: 'microsoft/TRELLIS.2-4B',+ // The 4B model conditions on DINOv3, which is gated. Unlike the MPS port this+ // lane does not use RMBG-2.0 (upstream's own example feeds the image straight+ // to the pipeline), so it is deliberately absent here rather than copied over.+ gatedRepos: Object.freeze([+ Object.freeze({+ label: 'facebook/dinov3-vitl16-pretrain-lvd1689m',+ url: 'https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m',+ }),+ ]),+ }),});/** Registry keys, for Zod enums and iteration. */@@ -105,7 +140,8 @@ export function getTarget(id) {* capabilities are passed in, never probed here.** @param {string|object} target target id or descriptor.- * @param {{appleSilicon?: boolean, unifiedMemoryGb?: number, cuda?: boolean}} [caps]+ * @param {{appleSilicon?: boolean, unifiedMemoryGb?: number, cuda?: boolean,+ * cudaVramGb?: number|null, cudaProbe?: string, linuxHost?: boolean}} [caps]* @returns {string|null} a stable reason code, or null when available.*/export function unavailableReason(target, caps = {}) {@@ -118,7 +154,23 @@ export function unavailableReason(target, caps = {}) {return 'insufficient-memory';}} else if (t.executionLane === EXECUTION_LANE.LOCAL_CUDA) {- if (!caps.cuda) return 'requires-cuda';+ // Order matters: report the most fundamental unmet requirement first, so a Mac+ // is told it needs an NVIDIA GPU (true and final) rather than that it needs+ // Linux (true but beside the point), while a Windows box WITH a 24 GB card is+ // told the one thing it can actually act on.+ if (!caps.cuda) {+ // "The probe couldn't run" is not "there is no GPU" — never report absent+ // hardware we failed to look for (CLAUDE.md sentinel rule).+ return caps.cudaProbe === 'unknown' ? 'cuda-probe-failed' : 'requires-cuda';+ }+ if (req.linuxHost && !caps.linuxHost) return 'requires-linux-host';+ if (req.minVramGb) {+ // A card whose VRAM column didn't parse is a known GPU of unknown size; that+ // is a failed measurement, not a small card, so it must not read as+ // "insufficient" (which would tell the user to buy hardware they may own).+ if (!Number.isFinite(caps.cudaVramGb)) return 'cuda-probe-failed';+ if (caps.cudaVramGb < req.minVramGb) return 'insufficient-vram';+ }}// hosted-api has no local hardware requirement.return null;@@ -134,6 +186,34 @@ export function isTargetAvailable(target, caps = {}) {return unavailableReason(target, caps) === null;}+/**+ * Reason codes meaning "this machine's hardware will never run that target" — as+ * opposed to a blocker the user can act on (install an OS in WSL2, fix a driver,+ * install the model). This is a property of the REASON, not of any one target, so it+ * is classified once here rather than restated per descriptor: every lane gets the+ * same treatment, and a new target inherits it without re-deriving the policy.+ *+ * `listTargets` omits a target blocked for one of these, so a Mac isn't shown a+ * permanently-red NVIDIA card and an NVIDIA box isn't shown a permanently-red Apple+ * Silicon one. Note `cuda-probe-failed` is deliberately NOT here — "we couldn't tell"+ * is worth surfacing, and it only ever arises on a host that does have a driver.+ */+export const UNFIXABLE_HARDWARE_REASONS = Object.freeze([+ 'requires-apple-silicon',+ 'requires-cuda',+ 'insufficient-memory',+ 'insufficient-vram',+]);++/**+ * Does this reason describe hardware the host simply doesn't have? Pure.+ * @param {string|null} reason+ * @returns {boolean}+ */+export function isUnfixableHardwareReason(reason) {+ return UNFIXABLE_HARDWARE_REASONS.includes(reason);+}+/*** Resolve the effective target for a request. Pure — no fallback to a *different** model is applied here (that's a caller policy); the requested/default target is@@ -156,34 +236,71 @@ export function resolveTarget(requestedId, caps = {}, { defaultId = DEFAULT_IMAG* Every registered target annotated with its availability on a host — the shape* the API/UI consume to render a target selector with disabled/needs-install* states. Pure.+ *+ * A target blocked by hardware this host doesn't have is omitted entirely rather+ * than listed with a permanently-red badge (see `UNFIXABLE_HARDWARE_REASONS`);+ * every other blocker still renders, so a fixable one is never silently hidden.+ ** @param {object} [caps]* @returns {Array<object>}*/export function listTargets(caps = {}) {- return IMAGE_TO_3D_TARGET_IDS.map((id) => {- const target = IMAGE_TO_3D_TARGETS[id];- const reason = unavailableReason(target, caps);- return { ...target, available: reason === null, unavailableReason: reason };- });+ return IMAGE_TO_3D_TARGET_IDS+ .map((id) => {+ const target = IMAGE_TO_3D_TARGETS[id];+ const reason = unavailableReason(target, caps);+ return { ...target, available: reason === null, unavailableReason: reason };+ })+ .filter((t) => !isUnfixableHardwareReason(t.unavailableReason));}/*** The one impure boundary: read this machine's capabilities. Injectable so* routes/tests can supply deterministic values. `unifiedMemoryGb` is rounded to* the nearest whole GB (physical RAM reads a hair under the marketed size, so a- * "24 GB" Mac rounds cleanly to 24 rather than tripping the floor at 23.98).+ * "24 GB" Mac rounds cleanly to 24 rather than tripping the floor at 23.98);+ * `cudaVramGb` is rounded the same way, for the same reason.+ *+ * **Async because CUDA detection is a subprocess.** Apple-Silicon and memory reads+ * are synchronous, but there is no way to size an NVIDIA card without shelling to+ * `nvidia-smi`. Rather than keep a second, sync-but-lying capability shape (which+ * would report `cuda: false` on a real CUDA box until some background warm-up+ * finished), this stays the single boundary and awaits the cached probe — cached,+ * so the per-request cost after the first call is nil. The pure resolvers above are+ * unaffected: they still take `caps` as a plain injected object.+ *+ * Pass an explicit `cuda` (and optionally `cudaVramGb`) to skip the probe entirely —+ * that is how tests and callers with pre-resolved capabilities stay deterministic.+ *+ * `cudaProbe` carries the probe's three-way status (`'available'` / `'absent'` /+ * `'unknown'`) so consumers can distinguish "this host has no NVIDIA GPU" from "we+ * could not find out" — `unavailableReason` uses exactly that to pick between+ * `requires-cuda` and `cuda-probe-failed`.*- * @param {{appleSilicon?: boolean, totalMemBytes?: number, cuda?: boolean}} [overrides]- * @returns {{appleSilicon: boolean, unifiedMemoryGb: number, cuda: boolean}}+ * @param {{appleSilicon?: boolean, totalMemBytes?: number, linuxHost?: boolean,+ * cuda?: boolean, cudaVramGb?: number|null}} [overrides]+ * @returns {Promise<{appleSilicon: boolean, unifiedMemoryGb: number, linuxHost: boolean,+ * cuda: boolean, cudaVramGb: number|null,+ * cudaProbe: 'available'|'absent'|'unknown'}>}*/-export function detectHostCapabilities({+export async function detectHostCapabilities({appleSilicon = isAppleSilicon(),totalMemBytes = os.totalmem(),- cuda = false,+ linuxHost = os.platform() === 'linux',+ cuda,+ cudaVramGb,} = {}) {+ // Only probe when the caller didn't already state the answer.+ const probe = cuda === undefined ? await getCudaCapability() : null;+ const resolvedCuda = probe ? probe.status === 'available' : Boolean(cuda);return {appleSilicon: Boolean(appleSilicon),unifiedMemoryGb: Math.round(Number(totalMemBytes) / 1024 ** 3),- cuda: Boolean(cuda),+ // WSL2 reports linux, which is exactly right: that IS the supported way to run+ // the CUDA lane on a Windows machine.+ linuxHost: Boolean(linuxHost),+ cuda: resolvedCuda,+ cudaVramGb: cudaVramGb ?? (probe ? probe.maxVramGb : null),+ cudaProbe: probe ? probe.status : (resolvedCuda ? 'available' : 'absent'),};}diff --git a/server/services/imageTo3d/targets.test.js b/server/services/imageTo3d/targets.test.jsindex abc0803f18..040b670b4f 100644--- a/server/services/imageTo3d/targets.test.js+++ b/server/services/imageTo3d/targets.test.js@@ -14,10 +14,14 @@ import {} from './targets.js';// A host that can run TRELLIS.2's local-MPS lane, and one that can't.-const APPLE_128GB = { appleSilicon: true, unifiedMemoryGb: 128, cuda: false };-const APPLE_16GB = { appleSilicon: true, unifiedMemoryGb: 16, cuda: false };-const INTEL_MAC = { appleSilicon: false, unifiedMemoryGb: 64, cuda: false };-const CUDA_BOX = { appleSilicon: false, unifiedMemoryGb: 64, cuda: true };+const APPLE_128GB = { appleSilicon: true, unifiedMemoryGb: 128, cuda: false, cudaProbe: 'absent' };+const APPLE_16GB = { appleSilicon: true, unifiedMemoryGb: 16, cuda: false, cudaProbe: 'absent' };+const INTEL_MAC = { appleSilicon: false, unifiedMemoryGb: 64, cuda: false, cudaProbe: 'absent' };+// A Linux box with a 24 GB card — the supported host for the local-CUDA lane.+const CUDA_BOX = {+ appleSilicon: false, unifiedMemoryGb: 64, linuxHost: true,+ cuda: true, cudaVramGb: 24, cudaProbe: 'available',+};describe('image-to-3d target registry', () => {it('registers trellis2 as the default target with a stable descriptor shape', () => {@@ -43,6 +47,27 @@ describe('image-to-3d target registry', () => {]);});+ it('registers trellis2Cuda on the local-cuda lane with upstream’s stated floor', () => {+ expect(IMAGE_TO_3D_TARGET_IDS).toContain('trellis2Cuda');+ const t = getTarget('trellis2Cuda');+ expect(t).toMatchObject({+ id: 'trellis2Cuda',+ executionLane: EXECUTION_LANE.LOCAL_CUDA,+ outputKind: OUTPUT_KIND.GLB_MESH,+ upstream: 'https://github.com/microsoft/TRELLIS.2',+ });+ // Upstream: "An NVIDIA GPU with at least 24GB of memory is necessary" and+ // "currently tested only on Linux".+ expect(t.requires).toMatchObject({ cuda: true, minVramGb: 24, linuxHost: true });+ // Unlike the MPS port, this lane does not pull RMBG-2.0 — only DINOv3 is gated.+ expect(t.gatedRepos.map((r) => r.label)).toEqual(['facebook/dinov3-vitl16-pretrain-lvd1689m']);+ });++ it('leaves trellis2 (MPS) as the default target', () => {+ // Adding the CUDA lane must not change which target an unqualified request gets.+ expect(DEFAULT_IMAGE_TO_3D_TARGET).toBe('trellis2');+ });+it('freezes the registry and its descriptors so a target cannot be mutated at runtime', () => {expect(Object.isFrozen(IMAGE_TO_3D_TARGETS)).toBe(true);expect(Object.isFrozen(IMAGE_TO_3D_TARGETS.trellis2)).toBe(true);@@ -129,34 +154,124 @@ describe('resolveTarget', () => {describe('listTargets', () => {it('annotates every registered target with availability for the host', () => {const available = listTargets(APPLE_128GB);- expect(available).toHaveLength(IMAGE_TO_3D_TARGET_IDS.length);expect(available.find((t) => t.id === 'trellis2')).toMatchObject({available: true,unavailableReason: null,gatedRepos: IMAGE_TO_3D_TARGETS.trellis2.gatedRepos,});- const blocked = listTargets(CUDA_BOX);- expect(blocked.find((t) => t.id === 'trellis2')).toMatchObject({+ // A blocked-but-listed target keeps its reason for the UI to render.+ const blocked = listTargets({ ...CUDA_BOX, linuxHost: false });+ expect(blocked.find((t) => t.id === 'trellis2Cuda')).toMatchObject({available: false,- unavailableReason: 'requires-apple-silicon',+ unavailableReason: 'requires-linux-host',});});++ it('hides a target blocked for hardware the host simply does not have', () => {+ // A Mac has no NVIDIA GPU and never will — a permanently-red CUDA card is noise.+ expect(listTargets(APPLE_128GB).map((t) => t.id)).toEqual(['trellis2']);+ });++ it('applies that hiding symmetrically, not just to the newer lane', () => {+ // The mirror of the case above: an NVIDIA box is no more able to grow an Apple+ // Silicon chip than a Mac is to grow a GPU, so neither gets a dead card.+ expect(listTargets(CUDA_BOX).map((t) => t.id)).toEqual(['trellis2Cuda']);+ });++ it('still SHOWS a target when the blocker is one the user can fix', () => {+ // Windows + a qualifying card: the lane is reachable via WSL2, so the card must+ // appear with that actionable reason rather than vanish.+ const shown = listTargets({ ...CUDA_BOX, linuxHost: false });+ expect(shown.find((t) => t.id === 'trellis2Cuda')).toMatchObject({+ available: false,+ unavailableReason: 'requires-linux-host',+ });+ });++ it('shows a target whose GPU could not be probed rather than hiding it', () => {+ // "Couldn't tell" is worth surfacing — it only arises on a host that has a driver.+ const shown = listTargets({+ appleSilicon: false, linuxHost: true, cuda: false, cudaProbe: 'unknown',+ });+ expect(shown.find((t) => t.id === 'trellis2Cuda')?.unavailableReason).toBe('cuda-probe-failed');+ });++ it('lists the CUDA target as available on a supported Linux + 24 GB host', () => {+ expect(listTargets(CUDA_BOX).find((t) => t.id === 'trellis2Cuda')).toMatchObject({+ available: true,+ unavailableReason: null,+ });+ });+});++describe('unavailableReason (local-cuda gating)', () => {+ it('is available on a Linux host with a 24 GB card', () => {+ expect(unavailableReason('trellis2Cuda', CUDA_BOX)).toBeNull();+ expect(isTargetAvailable('trellis2Cuda', CUDA_BOX)).toBe(true);+ });++ it('is available at exactly the VRAM floor', () => {+ expect(isTargetAvailable('trellis2Cuda', { ...CUDA_BOX, cudaVramGb: 24 })).toBe(true);+ });++ it('reports requires-cuda on a host with no NVIDIA GPU', () => {+ expect(unavailableReason('trellis2Cuda', APPLE_128GB)).toBe('requires-cuda');+ });++ it('reports the missing GPU before the missing Linux host', () => {+ // A Mac needs to hear "you need an NVIDIA GPU" (final), not "you need Linux"+ // (true, but not the thing standing in the way).+ expect(unavailableReason('trellis2Cuda', { ...APPLE_128GB, linuxHost: false })).toBe('requires-cuda');+ });++ it('reports requires-linux-host on Windows WITH a qualifying card', () => {+ // Upstream builds CUDA extensions against a POSIX toolchain; WSL2 is the route.+ expect(unavailableReason('trellis2Cuda', { ...CUDA_BOX, linuxHost: false }))+ .toBe('requires-linux-host');+ });++ it('reports insufficient-vram for an under-spec card', () => {+ expect(unavailableReason('trellis2Cuda', { ...CUDA_BOX, cudaVramGb: 12 }))+ .toBe('insufficient-vram');+ });++ it('reports cuda-probe-failed — never requires-cuda — when the probe could not run', () => {+ // "We failed to look" must not be reported as "there is no GPU".+ expect(unavailableReason('trellis2Cuda', {+ appleSilicon: false, linuxHost: true, cuda: false, cudaProbe: 'unknown',+ })).toBe('cuda-probe-failed');+ });++ it('reports cuda-probe-failed — never insufficient-vram — for a card of unknown size', () => {+ // A [N/A] VRAM reading is a failed measurement, not a small card; telling the+ // user to buy a bigger GPU they may already own would be wrong.+ expect(unavailableReason('trellis2Cuda', { ...CUDA_BOX, cudaVramGb: null }))+ .toBe('cuda-probe-failed');+ });});describe('detectHostCapabilities', () => {- it('rounds unified memory to whole GB and normalizes flags', () => {- const caps = detectHostCapabilities({+ it('rounds unified memory to whole GB and normalizes flags', async () => {+ const caps = await detectHostCapabilities({appleSilicon: true,totalMemBytes: 128 * 1024 ** 3,+ linuxHost: false,+ cuda: false,+ });+ expect(caps).toEqual({+ appleSilicon: true,+ unifiedMemoryGb: 128,+ linuxHost: false,cuda: false,+ cudaVramGb: null,+ cudaProbe: 'absent',});- expect(caps).toEqual({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false });});- it('rounds a hair-under-marketed RAM reading up to the marketed size', () => {+ it('rounds a hair-under-marketed RAM reading up to the marketed size', async () => {// Physical RAM on a "24 GB" Mac reads slightly under 24*1024^3.- const caps = detectHostCapabilities({+ const caps = await detectHostCapabilities({appleSilicon: true,totalMemBytes: 24 * 1024 ** 3 - 50 * 1024 ** 2,cuda: false,@@ -165,9 +280,31 @@ describe('detectHostCapabilities', () => {expect(isTargetAvailable('trellis2', caps)).toBe(true);});- it('coerces truthy non-boolean overrides to strict booleans', () => {- const caps = detectHostCapabilities({ appleSilicon: 1, totalMemBytes: 8 * 1024 ** 3, cuda: 'yes' });+ it('coerces truthy non-boolean overrides to strict booleans', async () => {+ const caps = await detectHostCapabilities({+ appleSilicon: 1, totalMemBytes: 8 * 1024 ** 3, cuda: 'yes',+ });expect(caps.appleSilicon).toBe(true);expect(caps.cuda).toBe(true);});++ it('carries an injected CUDA card straight through to the CUDA lane gate', async () => {+ const caps = await detectHostCapabilities({+ appleSilicon: false,+ totalMemBytes: 64 * 1024 ** 3,+ linuxHost: true,+ cuda: true,+ cudaVramGb: 24,+ });+ expect(caps).toMatchObject({ cuda: true, cudaVramGb: 24, cudaProbe: 'available' });+ expect(isTargetAvailable('trellis2Cuda', caps)).toBe(true);+ });++ it('does not probe the machine when the caller states the CUDA answer', async () => {+ // An injected `cuda` must skip the nvidia-smi subprocess entirely — that is what+ // keeps this deterministic on any CI host, with or without a GPU.+ const caps = await detectHostCapabilities({ cuda: false, totalMemBytes: 8 * 1024 ** 3 });+ expect(caps.cudaProbe).toBe('absent');+ expect(caps.cudaVramGb).toBeNull();+ });});diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex b4b5264317..aa1c03e02b 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -23,37 +23,16 @@ import { homedir, platform, totalmem } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { spawn, execFile } from 'node:child_process';-import { killWithEscalation } from '../../lib/killWithEscalation.js';import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import { getTarget } from './targets.js';+import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';const HOME = homedir();const IS_WIN = platform() === 'win32';-/**- * Build a case-insensitive predicate that tests text against an alternation of- * signature phrases — the shared shape both subprocess-error classifiers below use- * (each keeps its own domain-specific phrase list; only the plumbing is shared).- * @param {string[]} phrases- * @returns {(text: string) => boolean}- */-function textMatcher(phrases) {- const re = new RegExp(phrases.join('|'), 'i');- return (text) => re.test(String(text ?? ''));-}--/**- * Append a chunk of subprocess output to a bounded tail (the last `max` chars), so a- * non-zero exit can be classified from the trailing output without retaining the- * whole stream. Used at both child-process boundaries (install + generate).- * @param {string} prev- * @param {*} buf- * @param {number} [max]- * @returns {string}- */-function appendTail(prev, buf, max = 4000) {- return `${prev}${buf}`.slice(-max);-}+/** Error-code namespace and user-facing name for this lane's subprocess failures. */+const CODE_PREFIX = 'TRELLIS2';+const LABEL = 'TRELLIS.2';/** The Apple Silicon MPS port of Microsoft TRELLIS.2. */export const TRELLIS2_REPO = 'https://github.com/shivampkumar/trellis-mac';@@ -558,7 +537,7 @@ export function installTrellis2({onEvent = () => {},spawnImpl = spawn,maxRetries = 3,- sleep = (ms) => new Promise((r) => setTimeout(r, ms)),+ sleep,exists = existsSync,env,probeBake = probeTrellis2TextureBake,@@ -568,116 +547,28 @@ export function installTrellis2({// 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;-- const runStep = (step) => new Promise((resolve, reject) => {- onEvent({ type: 'stage', stage: step.stage, message: `${step.command} ${step.args.join(' ')}` });- // Child-process boundary — outcomes flow through events, not a throw into the- // request lifecycle (CLAUDE.md child-process exception).- const child = spawnImpl(step.command, step.args, {- ...(step.cwd ? { cwd: step.cwd } : {}),- ...(env ? { env } : {}),- });- currentChild = child;- // Retain a bounded tail of combined output so a non-zero exit can be classified- // as transient-network vs. a real failure (the clue is in the subprocess text,- // not the exit code — git exits 128 for both a network drop and a bad ref).- let outputTail = '';- const log = (buf) => {- const message = String(buf).trim();- if (message) onEvent({ type: 'log', stage: step.stage, message });- outputTail = appendTail(outputTail, buf);- };- child.stdout?.on('data', log);- child.stderr?.on('data', log);- child.on('error', reject);- child.on('close', (code) => {- if (code === 0) {- resolve();- return;- }- const err = new Error(`TRELLIS.2 install step '${step.stage}' exited ${code}`);- err.code = 'TRELLIS2_INSTALL_FAILED';- err.stage = step.stage;- err.transient = isTransientInstallError(outputTail);- reject(err);- });- });-- // Retry an idempotent step in place while its failure looks like a transient- // network drop and attempts remain; otherwise surface the error unchanged.- const runStepWithRetry = async (step) => {- for (let attempt = 0; ; attempt += 1) {- if (canceled) {- const err = new Error('TRELLIS.2 install canceled');- err.code = 'TRELLIS2_INSTALL_CANCELED';- throw err;- }- try {- await runStep(step);- return;- } catch (err) {- const canRetry = err?.code === 'TRELLIS2_INSTALL_FAILED'- && err.transient && attempt < maxRetries && !canceled;- 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',- stage: step.stage,- message: `⚠️ Transient network error — retrying in ${Math.round(backoffMs / 1000)}s (attempt ${attempt + 2}/${maxRetries + 1})…`,- });- await sleep(backoffMs);- }- }- };-- const promise = (async () => {- for (const step of steps) {- if (canceled) {- const err = new Error('TRELLIS.2 install canceled');- err.code = 'TRELLIS2_INSTALL_CANCELED';- throw err;- }- await runStepWithRetry(step);- }+ return runInstallSteps({+ steps: buildInstallSteps(base, { exists, installMetalToolchain }),+ label: LABEL,+ codePrefix: CODE_PREFIX,+ isTransient: isTransientInstallError,+ onEvent,+ spawnImpl,+ maxRetries,+ sleep,+ env,// `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 };- })();-- const kill = () => {- canceled = true;- if (currentChild && typeof currentChild.kill === 'function') currentChild.kill('SIGTERM');- };-- return { promise, kill };+ // scrambled surfaces (#2952). Report what actually landed.+ verify: async (emit) => {+ const bake = await probeBake({ base });+ if (bake.quality === 'fallback') {+ emit({ type: 'log', stage: 'verify', message: `⚠️ ${bake.help}` });+ } else if (bake.quality === 'metal') {+ emit({ type: 'log', stage: 'verify', message: '✅ Metal texture baking is available.' });+ }+ },+ });}/**@@ -710,14 +601,27 @@ export const isHfAuthError = textMatcher([* page is the fix; the CLI/env route is the fallback for someone already set up that* way. Terms acceptance is a separate step a token alone doesn't cover.*/-const HF_AUTH_REPOS = getTarget('trellis2')?.gatedRepos ?? [];-const HF_AUTH_REPO_HELP = HF_AUTH_REPOS- .map(({ label, url }) => `${label} at ${url}`)- .join(' and ') || 'the required model at https://huggingface.co';-const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from '- + `Hugging Face. Accept the terms for ${HF_AUTH_REPO_HELP}, then add your `- + 'Hugging Face token on the 3D page (or set HF_TOKEN / run `huggingface-cli login`) '- + 'and try again.';+/**+ * Build that guidance for a target, naming its own gated repos so the registry stays+ * the single source and the two lanes can't drift on the wording.+ *+ * Resolved lazily, at failure time, rather than at module scope: this module is in the+ * import graph of every registry consumer, and reading a descriptor at import time+ * makes merely LOADING it depend on `targets.js` being fully materialized — which a+ * partial test mock of that module breaks, taking the whole graph down with it.+ * @param {string} targetId+ * @returns {string}+ */+export function hfGatedRepoHelp(targetId) {+ const repos = getTarget(targetId)?.gatedRepos ?? [];+ const repoHelp = repos+ .map(({ label, url }) => `${label} at ${url}`)+ .join(' and ') || 'the required model at https://huggingface.co';+ return 'TRELLIS.2 could not download a gated model dependency from '+ + `Hugging Face. Accept the terms for ${repoHelp}, then add your `+ + 'Hugging Face token on the 3D page (or set HF_TOKEN / run `huggingface-cli login`) '+ + 'and try again.';+}/*** Run a single image→GLB generation. The one real-subprocess boundary — GUARDED:@@ -776,59 +680,22 @@ export function runTrellis2Generate({textureSize: resolvedTextureSize,pipelineType: resolvedPipelineType,});- // 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 } : {}) });- let assetPath = outputPath || null;- // Retain a bounded tail of combined output so a non-zero exit can be classified- // (HF auth/gated-repo vs. a real crash) — the clue is in the text, not the code.- let outputTail = '';- const promise = new Promise((resolve, reject) => {- const ingest = (buf) => {- outputTail = appendTail(outputTail, buf);- // Split on \r AND \n: tqdm redraws its sampling bar in place with carriage- // returns, so a single chunk can carry several progress frames separated only- // by \r. Splitting on \n alone would treat them as one line and parse just the- // first (lowest) percent — under-reporting progress during the long sampling phase.- for (const line of String(buf).split(/[\r\n]+/)) {- const frame = parseGenerateProgress(line);- if (!frame) continue;- if (frame.assetPath) assetPath = frame.assetPath;- if (onProgress) onProgress(frame);- }- };- child.stdout?.on('data', ingest);- child.stderr?.on('data', ingest);- child.on('error', reject);- child.on('close', (code) => {- if (code === 0 && assetPath) {- Promise.resolve()- .then(() => postprocessGlb(assetPath))- .then(() => resolve({ assetPath }))- .catch((cause) => {- const error = new Error(`TRELLIS.2 produced a GLB but material normalization failed: ${cause.message}`);- error.code = 'TRELLIS2_GLB_POSTPROCESS_FAILED';- reject(error);- });- return;- }- // A gated-dependency / HF-auth failure is a user-fixable setup problem, not a- // crash — surface it as such with actionable guidance instead of "exited N".- if (code !== 0 && isHfAuthError(outputTail)) {- const err = new Error(HF_AUTH_HELP);- err.code = 'TRELLIS2_HF_AUTH_REQUIRED';- reject(err);- return;- }- const err = new Error(- code === 0 ? 'TRELLIS.2 finished but produced no .glb' : `TRELLIS.2 generate exited ${code}`,- );- err.code = 'TRELLIS2_GENERATE_FAILED';- reject(err);- });+ return runGenerateSubprocess({+ command,+ args,+ cwd: trellis2Root(base),+ env,+ label: LABEL,+ codePrefix: CODE_PREFIX,+ parseProgress: parseGenerateProgress,+ assetPath: outputPath || null,+ onProgress,+ spawnImpl,+ postprocessGlb,+ // A gated-dependency / HF-auth failure is a user-fixable setup problem, not a+ // crash — surface it as such with actionable guidance instead of "exited N".+ classifiers: [+ { test: isHfAuthError, code: `${CODE_PREFIX}_HF_AUTH_REQUIRED`, help: () => hfGatedRepoHelp('trellis2') },+ ],});- // Single captured child, never replaced — the helper's own exit check gates the- // SIGKILL escalation, so `stillRunning` is unconditionally true here.- const kill = () => killWithEscalation(child, { label: 'trellis2 generate', stillRunning: () => true });- return { promise, kill };}diff --git a/server/services/imageTo3d/trellis2Cuda.js b/server/services/imageTo3d/trellis2Cuda.jsnew file mode 100644index 0000000000..b7f75f24c6--- /dev/null+++ b/server/services/imageTo3d/trellis2Cuda.js@@ -0,0 +1,403 @@+/**+ * TRELLIS.2 (local NVIDIA / CUDA) target — install detection, pure command+ * builders, and a guarded generate runner.+ *+ * The CUDA sibling of `trellis2.js` (which drives the Apple-Silicon MPS port). Both+ * lanes are thin: the subprocess machinery they share — install-step sequencing with+ * transient retry, cancel, and the generate child driver — lives in `laneRunner.js`,+ * so this file is only what is genuinely CUDA-specific (paths, steps, args, error+ * classification). Everything here is either pure or exercised through injectable+ * `exists`/`spawnImpl`, so the wiring is unit-testable WITHOUT a 24 GB NVIDIA box, a+ * ~15 GB weight download, or a live render. `runTrellis2CudaGenerate` is the one real+ * subprocess boundary and NEVER auto-runs: it rejects unless the model is installed,+ * and is only reached from an explicit user action (CLAUDE.md no-cold-bootstrap policy).+ *+ * **Two things differ from the MPS lane, and both drive the design here:**+ *+ * 1. **Conda, not a venv.** Upstream's `setup.sh` creates and activates a conda+ * environment named `trellis2` (PyTorch 2.6 / CUDA 12.4) rather than a `.venv`+ * inside the clone. So "installed" is resolved by probing the usual conda roots+ * for `envs/trellis2/bin/python` instead of a fixed path under the repo — the+ * same candidate-probe shape `pythonSetup.js#resolveFlux2Python` already uses.+ *+ * 2. **Upstream ships no CLI.** `microsoft/TRELLIS.2` has only `example.py`, a demo+ * with hard-coded paths — there is no `generate.py` to shell into the way the mac+ * port provides one. PortOS therefore ships its own entrypoint,+ * `trellis2CudaGenerateRunner.py`, which drives the documented public API+ * (`Trellis2ImageTo3DPipeline.from_pretrained` → `.run(image)` →+ * `o_voxel.postprocess.to_glb` → `.export`) and prints the SAME stage banners the+ * MPS lane emits, so `parseGenerateProgress` parses both lanes with no second+ * vocabulary to maintain.+ *+ * Clone layout mirrors the MPS lane: the upstream repo lands at `~/.portos/trellis2-cuda`.+ */++import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawn } from 'node:child_process';+import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';+import {+ hfGatedRepoHelp,+ isHfAuthError,+ isTransientInstallError,+ parseGenerateProgress,+ trellis2OutputStem,+} from './trellis2.js';+import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';++const HOME = homedir();++/** Error-code namespace and user-facing name for this lane's subprocess failures. */+const CODE_PREFIX = 'TRELLIS2_CUDA';+const LABEL = 'TRELLIS.2 (CUDA)';++/** Upstream Microsoft TRELLIS.2 (CUDA). */+export const TRELLIS2_CUDA_REPO = 'https://github.com/microsoft/TRELLIS.2.git';++/** The conda environment name upstream's `setup.sh --new-env` creates. */+export const TRELLIS2_CUDA_CONDA_ENV = 'trellis2';++/** Clone/install root. `base` overridable for tests. */+export function trellis2CudaRoot(base = join(HOME, '.portos')) {+ return join(base, 'trellis2-cuda');+}++/** The upstream package directory inside the clone — the second half of "installed". */+function trellis2CudaPackageDir(base) {+ return join(trellis2CudaRoot(base), 'trellis2');+}++/**+ * Where `setup.sh --new-env` may have put the `trellis2` conda environment. Probed+ * as an ordered candidate list rather than configured separately, mirroring+ * `resolveFlux2Python`. `CONDA_PREFIX` (when PortOS itself runs under conda) and+ * `CONDA_ROOT` come first because they are the machine's actual answer; the rest are+ * the standard miniconda/anaconda/miniforge install locations.+ *+ * Linux-only paths (`bin/python`) — the CUDA lane is gated to a Linux host by the+ * target descriptor's `linuxHost` requirement, so there is no Windows branch here to+ * bit-rot. A Windows machine reaches this lane through WSL2, which is Linux.+ *+ * @param {{env?: object}} [opts]+ * @returns {string[]}+ */+export function trellis2CudaPythonCandidates({ env = process.env } = {}) {+ const roots = [+ // `CONDA_PREFIX` points at the ACTIVE env, which may itself be `envs/trellis2`+ // or the base install — handle both by walking up from an `envs/<name>` prefix.+ env.CONDA_PREFIX && /[/\\]envs[/\\][^/\\]+$/.test(env.CONDA_PREFIX)+ ? join(env.CONDA_PREFIX, '..', '..')+ : env.CONDA_PREFIX,+ env.CONDA_ROOT,+ join(HOME, 'miniconda3'),+ join(HOME, 'anaconda3'),+ join(HOME, 'miniforge3'),+ join(HOME, 'mambaforge'),+ '/opt/conda',+ ].filter(Boolean);+ return roots.map((root) => join(root, 'envs', TRELLIS2_CUDA_CONDA_ENV, 'bin', 'python'));+}++/**+ * The conda Python upstream's `setup.sh` built, or null when no candidate exists.+ * `exists` is injectable so the probe is deterministic in tests.+ * @param {{exists?: (p: string) => boolean, env?: object}} [opts]+ * @returns {string|null}+ */+export function trellis2CudaPython({ exists = existsSync, env } = {}) {+ return trellis2CudaPythonCandidates({ env }).find((p) => exists(p)) || null;+}++/** PortOS's own generate entrypoint (upstream ships only a hard-coded `example.py`). */+export function trellis2CudaGenerateRunnerScript() {+ return fileURLToPath(new URL('./trellis2CudaGenerateRunner.py', import.meta.url));+}++/**+ * Installed ⇔ the conda env's Python exists AND the upstream package is on disk.+ * Both halves matter: `setup.sh` can create the env and then fail while building the+ * CUDA extensions, which would otherwise read as a complete install.+ * @param {{base?: string, exists?: (p: string) => boolean, env?: object}} [opts]+ * @returns {boolean}+ */+export function isTrellis2CudaInstalled({ base, exists = existsSync, env } = {}) {+ if (!trellis2CudaPython({ exists, env })) return false;+ return exists(trellis2CudaPackageDir(base));+}++/**+ * The upstream setup flags, verbatim from TRELLIS.2's README:+ * `. ./setup.sh --new-env --basic --flash-attn --nvdiffrast --nvdiffrec --cumesh --o-voxel --flexgemm`+ *+ * Every extension is load-bearing for the image→GLB path this target exposes:+ * `--o-voxel` provides `o_voxel.postprocess.to_glb` (the exporter the runner calls),+ * `--nvdiffrast`/`--nvdiffrec` the texture baking, `--cumesh` the mesh ops, and+ * `--flash-attn`/`--flexgemm` the attention/GEMM kernels the 4B model samples with.+ * Trimming the list produces an install that imports and then fails mid-render.+ */+export const TRELLIS2_CUDA_SETUP_FLAGS = Object.freeze([+ '--new-env', '--basic', '--flash-attn', '--nvdiffrast', '--nvdiffrec',+ '--cumesh', '--o-voxel', '--flexgemm',+]);++/**+ * The install as an ordered list of `{stage, command, args, cwd?}` steps: recursive+ * clone (upstream vendors its extensions as submodules — a non-recursive clone+ * silently yields empty extension dirs and a setup that fails deep in a compile),+ * then its `setup.sh`.+ *+ * **The clone step is skipped when the repo is already present** (`<root>/.git`),+ * the same resume property the MPS lane relies on: a run that cloned but died+ * inside `setup.sh` must re-reach the idempotent setup rather than abort on+ * "destination path already exists".+ *+ * **`setup.sh` is SOURCED inside a login shell**, not executed. Upstream documents+ * `. ./setup.sh` because the script calls `conda activate` and then installs into the+ * activated env; running it as `bash setup.sh` gives `conda activate` no shell hooks+ * and the packages land in the wrong interpreter (or the script aborts). `bash -lc`+ * loads the profile that `conda init` wrote, which is what makes `conda activate`+ * work in a non-interactive child.+ *+ * @param {string} [base]+ * @param {{exists?: (p: string) => boolean}} [opts]+ * @returns {Array<{stage: string, command: string, args: string[], cwd?: string}>}+ */+export function buildCudaInstallSteps(base, { exists = existsSync } = {}) {+ const root = trellis2CudaRoot(base);+ const steps = [];+ if (!exists(join(root, '.git'))) {+ steps.push({+ stage: 'clone',+ command: 'git',+ args: ['clone', '-b', 'main', '--recursive', TRELLIS2_CUDA_REPO, root],+ });+ }+ steps.push({+ stage: 'setup',+ command: 'bash',+ args: ['-lc', `. ./setup.sh ${TRELLIS2_CUDA_SETUP_FLAGS.join(' ')}`],+ cwd: root,+ });+ return steps;+}++/**+ * Texture-atlas / decimation lanes for the CUDA exporter.+ *+ * Upstream's `example.py` bakes a 4096 atlas at a 1,000,000-triangle decimation+ * target — tuned for the H100 it benchmarks on. On the 24 GB floor this target+ * supports, that combination is the difference between a render and an OOM, so+ * PortOS scales both to the card: the supported-floor lane stays at a 2K atlas /+ * 200k triangles (matching what the MPS lane proved usable), and only a card with+ * real headroom gets upstream's full-fat settings.+ */+export const TRELLIS2_CUDA_TEXTURE_SIZES = [2048, 4096];+export const TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE = 2048;+export const TRELLIS2_CUDA_HIGH_QUALITY_TEXTURE_SIZE = 4096;+export const TRELLIS2_CUDA_DEFAULT_DECIMATION = 200_000;+export const TRELLIS2_CUDA_HIGH_QUALITY_DECIMATION = 1_000_000;++/**+ * VRAM at which the high-quality lane turns on. 24 GB is the *minimum* to render at+ * all; doubling the atlas (4× the texel budget) and 5×-ing the triangle target needs+ * genuine headroom, so it is gated at 40 GB — the next real card tier (A100 40 GB,+ * L40S/A6000 48 GB) rather than a fractional bump over the floor.+ */+export const TRELLIS2_CUDA_HIGH_QUALITY_MIN_VRAM_GB = 40;++/**+ * Pick the whole export budget from the card's VRAM. Pure.+ *+ * Atlas size and decimation target move together by design — a 4K atlas over a 200k+ * mesh (or the reverse) is a combination nothing intends — so they are chosen once+ * rather than by two selectors that could be retuned apart. An unknown/unparseable+ * VRAM reading degrades to the conservative floor lane rather than overcommitting a+ * card we failed to size.+ *+ * @param {number|null} vramGb+ * @returns {{textureSize: number, decimationTarget: number}}+ */+export function selectTrellis2CudaExportBudget(vramGb) {+ return Number(vramGb) >= TRELLIS2_CUDA_HIGH_QUALITY_MIN_VRAM_GB+ ? {+ textureSize: TRELLIS2_CUDA_HIGH_QUALITY_TEXTURE_SIZE,+ decimationTarget: TRELLIS2_CUDA_HIGH_QUALITY_DECIMATION,+ }+ : {+ textureSize: TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,+ decimationTarget: TRELLIS2_CUDA_DEFAULT_DECIMATION,+ };+}++/**+ * The generate invocation:+ * `<conda-python> trellis2CudaGenerateRunner.py <image> --repo-root <root> [--output <stem>] …`+ *+ * Pure. Throws on a missing image (a render with no input is a bug, not an empty+ * run) and on a texture size outside the accepted set — better to fail here than to+ * have argparse abort a job we already queued. `outputPath` is the desired `.glb`+ * disk path, reduced to the stem the runner appends `.glb` to (shared with the MPS+ * lane via `trellis2OutputStem`).+ *+ * @param {{imagePath: string, outputPath?: string, base?: string, python?: string,+ * textureSize?: number, decimationTarget?: number}} opts+ * @returns {{command: string, args: string[]}}+ */+export function buildCudaGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ textureSize = TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,+ decimationTarget = TRELLIS2_CUDA_DEFAULT_DECIMATION,+} = {}) {+ if (!imagePath) throw new Error('buildCudaGenerateArgs: imagePath is required');+ if (!TRELLIS2_CUDA_TEXTURE_SIZES.includes(textureSize)) {+ throw new Error(+ `buildCudaGenerateArgs: textureSize must be one of ${TRELLIS2_CUDA_TEXTURE_SIZES.join(', ')}`,+ );+ }+ const args = [+ trellis2CudaGenerateRunnerScript(),+ imagePath,+ '--repo-root', trellis2CudaRoot(base),+ '--texture-size', String(textureSize),+ '--decimation-target', String(decimationTarget),+ ];+ if (outputPath) args.push('--output', trellis2OutputStem(outputPath));+ return { command: python || trellis2CudaPython({}) || 'python', args };+}++/**+ * A CUDA out-of-memory failure — user-actionable (free the card, or render smaller),+ * so it must not surface as a bare "exited 1" the way a real crash does.+ */+export const isCudaOomError = textMatcher([+ 'CUDA out of memory', 'CUBLAS_STATUS_ALLOC_FAILED', 'CUDNN_STATUS_ALLOC_FAILED',+]);++const CUDA_OOM_HELP = 'The GPU ran out of memory during this render. Close other '+ + 'GPU workloads and try again — TRELLIS.2 needs most of a 24 GB card to itself.';++/**+ * Run the install as a killable, event-emitting job: recursive clone → upstream+ * `setup.sh` (~15 GB plus a long CUDA extension build). Real subprocesses —+ * user-triggered only. Retry/cancel/backoff semantics come from the shared+ * `runInstallSteps`, so both lanes stay in lockstep by construction.+ *+ * @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function,+ * maxRetries?: number, sleep?: (ms: number) => Promise<void>,+ * exists?: (p: string) => boolean, env?: NodeJS.ProcessEnv}} [opts]+ * @returns {{promise: Promise<{ok: true}>, kill: () => void}}+ */+export function installTrellis2Cuda({+ base,+ onEvent = () => {},+ spawnImpl = spawn,+ maxRetries = 3,+ sleep,+ exists = existsSync,+ env,+} = {}) {+ return runInstallSteps({+ steps: buildCudaInstallSteps(base, { exists }),+ label: LABEL,+ codePrefix: CODE_PREFIX,+ isTransient: isTransientInstallError,+ onEvent,+ spawnImpl,+ maxRetries,+ sleep,+ env,+ // `setup.sh` can leave a usable conda env behind while an extension build failed,+ // so confirm what actually landed rather than trusting exit 0 — the same lesson+ // the MPS lane's verify step encodes (#2952).+ verify: (emit) => {+ if (!isTrellis2CudaInstalled({ base, exists, env })) {+ const err = new Error(+ `${LABEL} setup finished but its conda environment or upstream package is `+ + 'missing — check the setup log above for a failed extension build.',+ );+ err.code = `${CODE_PREFIX}_INSTALL_INCOMPLETE`;+ err.stage = 'verify';+ throw err;+ }+ emit({ type: 'log', stage: 'verify', message: '✅ TRELLIS.2 CUDA environment is present.' });+ },+ });+}++/**+ * Run a single image→GLB generation on CUDA. The one real-subprocess boundary —+ * GUARDED: rejects `TRELLIS2_CUDA_NOT_INSTALLED` unless the environment is present,+ * so it can never run from a cold boot. `spawnImpl`/`exists` are injectable so the+ * wiring is unit-testable without a real render.+ *+ * Returns `{ promise, kill }` so a caller can terminate the render mid-flight — e.g.+ * when the user deletes the record while its GLB is still rendering.+ *+ * `vramGb` is the size of the card this host will render on, passed down from the+ * host capabilities resolved at the request boundary; it selects the export budget.+ * Null/unknown degrades to the conservative floor lane.+ *+ * A successful render is normalized to opaque before it resolves, for the same reason+ * the MPS lane does it: prediction noise in low-alpha texels otherwise turns into+ * visible holes in both PortOS and downloaded GLBs.+ *+ * @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,+ * decimationTarget?: number, vramGb?: number|null,+ * onProgress?: (frame: object) => void, spawnImpl?: Function,+ * exists?: (p: string) => boolean, env?: NodeJS.ProcessEnv,+ * postprocessGlb?: (path: string) => void|Promise<void>}} opts+ * @returns {{promise: Promise<{assetPath: string}>, kill: () => void}}+ */+export function runTrellis2CudaGenerate({+ imagePath,+ outputPath,+ base,+ textureSize,+ decimationTarget,+ vramGb = null,+ onProgress,+ spawnImpl = spawn,+ exists = existsSync,+ env,+ postprocessGlb = rewriteGlbMaterialsOpaque,+} = {}) {+ // Resolve the interpreter once and reuse it as the "is the env there?" answer —+ // `isTrellis2CudaInstalled` would re-walk the same candidate list on the next line.+ const python = trellis2CudaPython({ exists, env });+ if (!python || !exists(trellis2CudaPackageDir(base))) {+ const err = new Error(`${LABEL} is not installed — install it before generating.`);+ err.code = `${CODE_PREFIX}_NOT_INSTALLED`;+ return { promise: Promise.reject(err), kill: () => {} };+ }+ const budget = selectTrellis2CudaExportBudget(vramGb);+ const { command, args } = buildCudaGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ textureSize: textureSize ?? budget.textureSize,+ decimationTarget: decimationTarget ?? budget.decimationTarget,+ });+ return runGenerateSubprocess({+ command,+ args,+ cwd: trellis2CudaRoot(base),+ env,+ label: LABEL,+ codePrefix: CODE_PREFIX,+ parseProgress: parseGenerateProgress,+ assetPath: outputPath || null,+ onProgress,+ spawnImpl,+ postprocessGlb,+ classifiers: [+ { test: isHfAuthError, code: `${CODE_PREFIX}_HF_AUTH_REQUIRED`, help: () => hfGatedRepoHelp('trellis2Cuda') },+ { test: isCudaOomError, code: `${CODE_PREFIX}_OUT_OF_MEMORY`, help: CUDA_OOM_HELP },+ ],+ });+}diff --git a/server/services/imageTo3d/trellis2Cuda.test.js b/server/services/imageTo3d/trellis2Cuda.test.jsnew file mode 100644index 0000000000..99cbddc8dd--- /dev/null+++ b/server/services/imageTo3d/trellis2Cuda.test.js@@ -0,0 +1,392 @@+import { EventEmitter } from 'node:events';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import {+ TRELLIS2_CUDA_REPO,+ TRELLIS2_CUDA_CONDA_ENV,+ TRELLIS2_CUDA_SETUP_FLAGS,+ TRELLIS2_CUDA_TEXTURE_SIZES,+ TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,+ TRELLIS2_CUDA_HIGH_QUALITY_TEXTURE_SIZE,+ TRELLIS2_CUDA_DEFAULT_DECIMATION,+ TRELLIS2_CUDA_HIGH_QUALITY_DECIMATION,+ TRELLIS2_CUDA_HIGH_QUALITY_MIN_VRAM_GB,+ trellis2CudaRoot,+ trellis2CudaPython,+ trellis2CudaPythonCandidates,+ trellis2CudaGenerateRunnerScript,+ isTrellis2CudaInstalled,+ buildCudaInstallSteps,+ buildCudaGenerateArgs,+ selectTrellis2CudaExportBudget,+ installTrellis2Cuda,+ runTrellis2CudaGenerate,+} from './trellis2Cuda.js';++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++// Paths are composed with join() rather than written as posix literals so these+// assertions hold on every host the repo is developed on.+const BASE = join('/tmp', 'portos-test-home');+const ROOT = join(BASE, 'trellis2-cuda');+const CONDA = join('/opt', 'conda');+const CONDA_PY = join(CONDA, 'envs', 'trellis2', 'bin', 'python');++/** An `exists` stub that answers true for exactly the listed paths. */+const existsFor = (...paths) => (p) => paths.includes(p);++/** A fully installed host: conda env python + the upstream package on disk. */+const INSTALLED = existsFor(CONDA_PY, join(ROOT, 'trellis2'));+const CONDA_ENV = { CONDA_ROOT: CONDA };++const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++describe('trellis2Cuda path resolution', () => {+ it('roots the install under the injected base, beside (not inside) the MPS lane', () => {+ expect(trellis2CudaRoot(BASE)).toBe(ROOT);+ // Distinct dirs — the two lanes must never share a clone or a venv.+ expect(trellis2CudaRoot(BASE)).not.toBe(join(BASE, 'trellis2'));+ });++ it('probes conda roots for the env setup.sh --new-env creates', () => {+ const candidates = trellis2CudaPythonCandidates({ env: CONDA_ENV });+ expect(candidates).toContain(CONDA_PY);+ expect(candidates.every((p) => p.includes(join('envs', TRELLIS2_CUDA_CONDA_ENV)))).toBe(true);+ });++ it('walks up from an active envs/<name> CONDA_PREFIX to find the base install', () => {+ // PortOS itself running under some other conda env must still locate `trellis2`.+ const candidates = trellis2CudaPythonCandidates({+ env: { CONDA_PREFIX: join(CONDA, 'envs', 'portos') },+ });+ expect(candidates.some((p) => p.includes(join('conda', 'envs', 'trellis2')))).toBe(true);+ });++ it('returns the first existing candidate, or null when none is present', () => {+ expect(trellis2CudaPython({ exists: existsFor(CONDA_PY), env: CONDA_ENV })).toBe(CONDA_PY);+ expect(trellis2CudaPython({ exists: () => false, env: CONDA_ENV })).toBeNull();+ });++ it('resolves PortOS’s own runner script (upstream ships no CLI entrypoint)', () => {+ expect(trellis2CudaGenerateRunnerScript()).toMatch(/trellis2CudaGenerateRunner\.py$/);+ });+});++describe('isTrellis2CudaInstalled', () => {+ it('is true only when BOTH the conda python and the upstream package exist', () => {+ expect(isTrellis2CudaInstalled({ base: BASE, exists: INSTALLED, env: CONDA_ENV })).toBe(true);+ });++ it('is false when setup.sh built the env but the package is missing', () => {+ // The realistic half-install: env created, then a CUDA extension build failed.+ expect(isTrellis2CudaInstalled({ base: BASE, exists: existsFor(CONDA_PY), env: CONDA_ENV }))+ .toBe(false);+ });++ it('is false when the clone exists but no conda env was ever built', () => {+ expect(isTrellis2CudaInstalled({+ base: BASE, exists: existsFor(join(ROOT, 'trellis2')), env: CONDA_ENV,+ })).toBe(false);+ });+});++describe('buildCudaInstallSteps', () => {+ it('clones recursively — upstream vendors its CUDA extensions as submodules', () => {+ const steps = buildCudaInstallSteps(BASE, { exists: () => false });+ expect(steps.map((s) => s.stage)).toEqual(['clone', 'setup']);+ expect(steps[0]).toMatchObject({+ command: 'git',+ args: ['clone', '-b', 'main', '--recursive', TRELLIS2_CUDA_REPO, ROOT],+ });+ });++ it('SOURCES setup.sh in a login shell so `conda activate` has its hooks', () => {+ // `bash setup.sh` would run conda activate in a shell with no profile loaded and+ // install into the wrong interpreter — upstream documents `. ./setup.sh`.+ const [, setup] = buildCudaInstallSteps(BASE, { exists: () => false });+ expect(setup).toMatchObject({ stage: 'setup', command: 'bash', cwd: ROOT });+ expect(setup.args[0]).toBe('-lc');+ expect(setup.args[1]).toMatch(/^\. \.\/setup\.sh /);+ });++ it('passes upstream’s documented extension flags verbatim', () => {+ const [, setup] = buildCudaInstallSteps(BASE, { exists: () => false });+ for (const flag of TRELLIS2_CUDA_SETUP_FLAGS) expect(setup.args[1]).toContain(flag);+ // --o-voxel provides the to_glb exporter the runner calls; dropping it yields an+ // install that imports and then fails mid-render.+ expect(setup.args[1]).toContain('--o-voxel');+ });++ it('skips the clone and resumes at setup when the repo is already on disk', () => {+ // Load-bearing for resume: an unconditional clone would abort on "destination+ // path already exists" and never reach the idempotent setup.+ const steps = buildCudaInstallSteps(BASE, { exists: existsFor(join(ROOT, '.git')) });+ expect(steps.map((s) => s.stage)).toEqual(['setup']);+ });+});++describe('selectTrellis2CudaExportBudget', () => {+ it('keeps the supported 24 GB floor on the conservative lane', () => {+ expect(selectTrellis2CudaExportBudget(24)).toEqual({+ textureSize: TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,+ decimationTarget: TRELLIS2_CUDA_DEFAULT_DECIMATION,+ });+ });++ it('opts into upstream’s full-fat settings only with real headroom', () => {+ expect(selectTrellis2CudaExportBudget(TRELLIS2_CUDA_HIGH_QUALITY_MIN_VRAM_GB)).toEqual({+ textureSize: TRELLIS2_CUDA_HIGH_QUALITY_TEXTURE_SIZE,+ decimationTarget: TRELLIS2_CUDA_HIGH_QUALITY_DECIMATION,+ });+ });++ it('falls back to the conservative lane when VRAM is unknown', () => {+ // An unsized card must degrade quality, never overcommit VRAM.+ for (const unknown of [null, undefined, NaN]) {+ expect(selectTrellis2CudaExportBudget(unknown)).toEqual({+ textureSize: TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,+ decimationTarget: TRELLIS2_CUDA_DEFAULT_DECIMATION,+ });+ }+ });++ it('moves atlas size and decimation target together, never one without the other', () => {+ // A 4K atlas over a 200k mesh (or the reverse) is a combination nothing intends.+ const floor = selectTrellis2CudaExportBudget(24);+ const high = selectTrellis2CudaExportBudget(80);+ expect(floor.textureSize).not.toBe(high.textureSize);+ expect(floor.decimationTarget).not.toBe(high.decimationTarget);+ });+});++describe('buildCudaGenerateArgs', () => {+ const args = (extra = {}) => buildCudaGenerateArgs({+ imagePath: '/img/in.png', base: BASE, python: CONDA_PY, ...extra,+ });++ it('invokes PortOS’s runner with the conda python and the repo root', () => {+ const { command, args: argv } = args();+ expect(command).toBe(CONDA_PY);+ expect(argv[0]).toMatch(/trellis2CudaGenerateRunner\.py$/);+ expect(argv[1]).toBe('/img/in.png');+ expect(argv).toContain('--repo-root');+ expect(argv[argv.indexOf('--repo-root') + 1]).toBe(ROOT);+ });++ it('strips a trailing .glb so the runner’s stem+extension does not double it', () => {+ const { args: argv } = args({ outputPath: '/out/model.glb' });+ expect(argv[argv.indexOf('--output') + 1]).toBe('/out/model');+ });++ it('passes the resolved texture size and decimation target', () => {+ const { args: argv } = args({ textureSize: 4096, decimationTarget: 1_000_000 });+ expect(argv[argv.indexOf('--texture-size') + 1]).toBe('4096');+ expect(argv[argv.indexOf('--decimation-target') + 1]).toBe('1000000');+ });++ it('throws without a source image — a render with no input is a bug, not an empty run', () => {+ expect(() => buildCudaGenerateArgs({ base: BASE })).toThrow(/imagePath is required/);+ });++ it('rejects an unsupported texture size here rather than in the child’s argparse', () => {+ expect(() => args({ textureSize: 8192 })).toThrow(/must be one of/);+ expect(TRELLIS2_CUDA_TEXTURE_SIZES).not.toContain(8192);+ });+});++describe('installTrellis2Cuda', () => {+ it('runs the steps in order and completes once the install verifies', async () => {+ const children = [];+ const spawnImpl = vi.fn(() => { const c = makeChild(); children.push(c); return c; });+ const events = [];+ // Not installed at plan time (so the clone step is included), installed at verify.+ let installed = false;+ const exists = (p) => (installed ? INSTALLED(p) : false);++ const { promise } = installTrellis2Cuda({+ base: BASE, spawnImpl, exists, env: CONDA_ENV, onEvent: (e) => events.push(e),+ });+ await flush();+ children[0].emit('close', 0); // clone+ await flush();+ installed = true;+ children[1].emit('close', 0); // setup+ await expect(promise).resolves.toEqual({ ok: true });++ expect(spawnImpl.mock.calls.map((c) => c[0])).toEqual(['git', 'bash']);+ expect(events.at(-1)).toMatchObject({ type: 'complete' });+ });++ it('fails loudly when setup.sh exits 0 without producing a usable environment', async () => {+ // setup.sh can leave a conda env behind while an extension build failed; a bare+ // exit-0 success would report an install that cannot render (the #2952 lesson).+ const children = [];+ const spawnImpl = vi.fn(() => { const c = makeChild(); children.push(c); return c; });+ const { promise } = installTrellis2Cuda({+ base: BASE, spawnImpl, exists: existsFor(join(ROOT, '.git')), env: CONDA_ENV,+ });+ await flush();+ children[0].emit('close', 0);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_INSTALL_INCOMPLETE' });+ });++ it('retries a transient network failure in place, then succeeds', async () => {+ const children = [];+ const spawnImpl = vi.fn(() => { const c = makeChild(); children.push(c); return c; });+ let installed = false;+ const { promise } = installTrellis2Cuda({+ base: BASE,+ spawnImpl,+ exists: (p) => (installed ? INSTALLED(p) : existsFor(join(ROOT, '.git'))(p)),+ env: CONDA_ENV,+ sleep: () => Promise.resolve(),+ });+ await flush();+ children[0].stderr.emit('data', 'fatal: early EOF\nfetch-pack: invalid index-pack output');+ children[0].emit('close', 128);+ await flush();+ expect(spawnImpl).toHaveBeenCalledTimes(2); // retried the same idempotent step+ installed = true;+ children[1].emit('close', 0);+ await expect(promise).resolves.toEqual({ ok: true });+ });++ it('does NOT retry a real (non-transient) failure', async () => {+ const children = [];+ const spawnImpl = vi.fn(() => { const c = makeChild(); children.push(c); return c; });+ const { promise } = installTrellis2Cuda({+ base: BASE, spawnImpl, exists: existsFor(join(ROOT, '.git')), env: CONDA_ENV,+ sleep: () => Promise.resolve(),+ });+ await flush();+ children[0].stderr.emit('data', 'error: no CUDA toolkit found; aborting');+ children[0].emit('close', 1);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_INSTALL_FAILED', stage: 'setup' });+ expect(spawnImpl).toHaveBeenCalledTimes(1);+ });++ it('cancels in flight and stops before the next step', async () => {+ const children = [];+ const spawnImpl = vi.fn(() => { const c = makeChild(); children.push(c); return c; });+ const { promise, kill } = installTrellis2Cuda({+ base: BASE, spawnImpl, exists: () => false, env: CONDA_ENV,+ });+ await flush();+ kill();+ expect(children[0].kill).toHaveBeenCalledWith('SIGTERM');+ children[0].emit('close', 0);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_INSTALL_CANCELED' });+ expect(spawnImpl).toHaveBeenCalledTimes(1); // never started `setup`+ });+});++describe('runTrellis2CudaGenerate', () => {+ const run = (opts = {}) => runTrellis2CudaGenerate({+ imagePath: '/img/in.png',+ outputPath: '/out/model.glb',+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ postprocessGlb: vi.fn(),+ ...opts,+ });++ it('refuses to run — and never spawns — when the environment is absent', async () => {+ // The no-cold-bootstrap guard: this must be impossible to reach on a fresh host.+ const spawnImpl = vi.fn();+ const { promise } = run({ exists: () => false, spawnImpl });+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_NOT_INSTALLED' });+ expect(spawnImpl).not.toHaveBeenCalled();+ });++ it('resolves with the produced asset and normalizes its materials to opaque', async () => {+ const child = makeChild();+ const postprocessGlb = vi.fn();+ const { promise } = run({ spawnImpl: () => child, postprocessGlb });+ await flush();+ child.stdout.emit('data', 'Saved: /out/model.glb\n');+ child.emit('close', 0);+ await expect(promise).resolves.toEqual({ assetPath: '/out/model.glb' });+ expect(postprocessGlb).toHaveBeenCalledWith('/out/model.glb');+ });++ it('streams progress through the MPS lane’s parser — one vocabulary, two lanes', async () => {+ const child = makeChild();+ const frames = [];+ const { promise } = run({ spawnImpl: () => child, onProgress: (f) => frames.push(f) });+ await flush();+ // The banners the Python runner prints, in order.+ child.stdout.emit('data', 'Loading pipeline...\n');+ child.stdout.emit('data', 'Device: cuda (NVIDIA GeForce RTX 3090)\n');+ child.stdout.emit('data', 'Generating 3D model...\n');+ child.stdout.emit('data', ' 50%|##### | 6/12\r 75%|####### | 9/12\r');+ child.stdout.emit('data', 'Mesh: 120000 vertices, 240000 faces\n');+ child.stdout.emit('data', 'Baking textures at 2048px...\n');+ child.stdout.emit('data', 'Saved: /out/model.glb\n');+ child.emit('close', 0);+ await promise;++ expect(frames.map((f) => f.stage)).toEqual([+ 'loading', 'loading', 'generating', 'generating', 'generating', 'meshing', 'texturing', 'export',+ ]);+ // Percent advances monotonically across the whole render.+ const percents = frames.map((f) => f.percent);+ expect(percents).toEqual([...percents].sort((a, b) => a - b));+ });++ it('classifies a gated-repo failure as actionable HF auth, not a crash', async () => {+ const child = makeChild();+ const { promise } = run({ spawnImpl: () => child });+ await flush();+ child.stderr.emit('data', 'GatedRepoError: access to model facebook/dinov3 is restricted');+ child.emit('close', 1);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_HF_AUTH_REQUIRED' });+ // The message names the gated repo from the registry, so the two never drift.+ await promise.catch((err) => expect(err.message).toContain('facebook/dinov3-vitl16-pretrain-lvd1689m'));+ });++ it('classifies a CUDA OOM distinctly from a generic failure', async () => {+ const child = makeChild();+ const { promise } = run({ spawnImpl: () => child });+ await flush();+ child.stderr.emit('data', 'torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB');+ child.emit('close', 1);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_OUT_OF_MEMORY' });+ });++ it('fails when the child exits 0 without ever emitting a .glb', async () => {+ const child = makeChild();+ const { promise } = run({ spawnImpl: () => child, outputPath: undefined });+ await flush();+ child.emit('close', 0);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_GENERATE_FAILED' });+ });++ it('surfaces a postprocess failure rather than reporting a bad mesh as ready', async () => {+ const child = makeChild();+ const { promise } = run({+ spawnImpl: () => child,+ postprocessGlb: vi.fn(() => { throw new Error('not a GLB'); }),+ });+ await flush();+ child.stdout.emit('data', 'Saved: /out/model.glb\n');+ child.emit('close', 0);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_GLB_POSTPROCESS_FAILED' });+ });++ it('kills the child on request so a deleted record stops burning GPU', async () => {+ const child = makeChild();+ const { promise, kill } = run({ spawnImpl: () => child });+ await flush();+ kill();+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ child.emit('close', 143);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_CUDA_GENERATE_FAILED' });+ });+});diff --git a/server/services/imageTo3d/trellis2CudaGenerateRunner.py b/server/services/imageTo3d/trellis2CudaGenerateRunner.pynew file mode 100644index 0000000000..09efabc6ee--- /dev/null+++ b/server/services/imageTo3d/trellis2CudaGenerateRunner.py@@ -0,0 +1,132 @@+"""Single image -> textured GLB via upstream Microsoft TRELLIS.2 (CUDA).++Upstream ships no CLI: `example.py` is a demo with hard-coded input/output paths and+H100-tuned export settings. This is PortOS's entrypoint over the same documented+public API -- pipeline load, `run(image)`, then `o_voxel.postprocess.to_glb` -- with+the paths and the export budget passed in as arguments.++Progress contract: the banners printed here are the SAME vocabulary the Apple-Silicon+port's `generate.py` emits, because `server/services/imageTo3d/trellis2.js`'s+`parseGenerateProgress` parses both lanes. Keep them in sync with+GENERATE_STAGE_SIGNATURES there -- changing a banner silently flatlines the progress+bar for this lane. Output is unbuffered/flushed so the frames stream while a+multi-minute render is still running instead of arriving all at once at exit.+"""++import argparse+import os+import sys+import time+from pathlib import Path++# Must precede the torch/trellis2 imports: the EXR reader is opt-in in OpenCV, and+# the allocator setting materially reduces fragmentation OOMs on a 24GB card, which+# is the floor this lane supports.+os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1")+os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+++def log(message):+ """Emit one progress banner, flushed so the parent sees it live."""+ print(message, flush=True)+++def parse_args():+ parser = argparse.ArgumentParser(description="TRELLIS.2 CUDA image-to-3D runner")+ parser.add_argument("image", help="Source image path")+ parser.add_argument(+ "--repo-root",+ required=True,+ help="Clone of microsoft/TRELLIS.2 (its package dir goes on sys.path)",+ )+ parser.add_argument(+ "--output",+ help="Output path STEM -- '.glb' is appended, matching the Apple-Silicon port",+ )+ parser.add_argument("--texture-size", type=int, default=2048)+ parser.add_argument("--decimation-target", type=int, default=200_000)+ parser.add_argument(+ "--model",+ default="microsoft/TRELLIS.2-4B",+ help="Hugging Face repo id for the pipeline weights",+ )+ return parser.parse_args()+++def main():+ args = parse_args()++ image_path = Path(args.image)+ if not image_path.is_file():+ raise SystemExit(f"Source image not found: {image_path}")++ # Upstream's package is imported from the clone, not installed into site-packages+ # by setup.sh -- put the repo root first on sys.path, mirroring what running+ # example.py from inside the checkout would give us.+ repo_root = str(Path(args.repo_root).resolve())+ if repo_root not in sys.path:+ sys.path.insert(0, repo_root)++ log("Loading pipeline...")+ import torch # noqa: E402 (deferred: importing torch costs seconds)+ from PIL import Image # noqa: E402+ from trellis2.pipelines import Trellis2ImageTo3DPipeline # noqa: E402+ import o_voxel # noqa: E402++ if not torch.cuda.is_available():+ raise SystemExit(+ "CUDA is not available inside the TRELLIS.2 environment -- "+ "check the NVIDIA driver and the torch build installed by setup.sh."+ )+ log(f"Device: cuda ({torch.cuda.get_device_name(0)})")++ pipeline = Trellis2ImageTo3DPipeline.from_pretrained(args.model)+ pipeline.cuda()++ image = Image.open(image_path)+ log("Generating 3D model...")+ started = time.time()+ # The pipeline's own sampling loops print tqdm bars; the parent scales those into+ # its sampling band, so nothing extra is emitted here.+ mesh = pipeline.run(image)[0]++ # nvdiffrast cannot rasterize past 2^24 triangles; upstream simplifies to that+ # ceiling before any export work. This is the hard renderer limit, distinct from+ # --decimation-target below (the quality/VRAM budget PortOS picks per card).+ mesh.simplify(16_777_216)+ log(f"Mesh: {len(mesh.vertices)} vertices, {len(mesh.faces)} faces")+ log(f"Generation time: {time.time() - started:.1f}s")++ log(f"Baking textures at {args.texture_size}px...")+ glb = o_voxel.postprocess.to_glb(+ vertices=mesh.vertices,+ faces=mesh.faces,+ attr_volume=mesh.attrs,+ coords=mesh.coords,+ attr_layout=mesh.layout,+ voxel_size=mesh.voxel_size,+ aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],+ decimation_target=args.decimation_target,+ texture_size=args.texture_size,+ remesh=True,+ remesh_band=1,+ remesh_project=0,+ verbose=True,+ )++ # The parent hands us a stem and appends nothing itself, so own the extension here+ # -- the same contract the Apple-Silicon port's generate.py uses.+ stem = args.output or str(image_path.with_suffix(""))+ out_path = Path(f"{stem}.glb")+ out_path.parent.mkdir(parents=True, exist_ok=True)+ # extension_webp keeps the baked atlas small enough to serve and download without+ # a separate compression pass.+ glb.export(str(out_path), extension_webp=True)++ # Terminal signal: the parent treats a printed .glb path as the export frame and+ # takes the produced asset path from it.+ log(f"Saved: {out_path}")+++if __name__ == "__main__":+ main()