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
add Pixal3D as a second CUDA image-to-3D target (#4677)
[._.]/ Adam Eivy62b040703772
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsxindex d529ee5e07..7ce4c1c1bd 100644--- a/client/src/components/media/ImageTo3dRenderOptions.jsx+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx@@ -7,6 +7,10 @@ import { SEED_MAX, STEPS_PRESETS } from '../../lib/imageTo3dRenderOptions';// Image-to-3D-specific by design: the presets bake in TRELLIS.2's 12-step// default and the keying toggle has no analogue in image/video gen.//+// Not every target honors every knob — Pixal3D's upstream CLI has no per-phase step+// override — so `stepsSupported={false}` disables the Quality control and says why,+// rather than offering a setting the runner silently drops.+//// Value conventions (see lib/imageTo3dRenderOptions.js for the body mapping):// - steps: '' = pipeline default, else a preset number string.// - seed: '' = a fresh random seed every render; a value pins this run.@@ -23,15 +27,20 @@ export default function ImageTo3dRenderOptions({keyBackground,onKeyBackgroundChange,disabled = false,+ stepsSupported = true,}) {return (<div className="flex flex-col gap-2"><div className="grid gap-3 sm:grid-cols-3">- <FormField label="Quality" labelClassName={FIELD_LABEL_CLASS}>+ <FormField+ label="Quality"+ labelClassName={FIELD_LABEL_CLASS}+ hint={stepsSupported ? undefined : 'This model has no step control'}+ ><select- value={steps}+ value={stepsSupported ? steps : ''}onChange={(e) => onStepsChange(e.target.value)}- disabled={disabled}+ disabled={disabled || !stepsSupported}className={FIELD_INPUT_CLASS}>{STEPS_PRESETS.map((preset) => (diff --git a/client/src/components/media/ImageTo3dRenderOptions.test.jsx b/client/src/components/media/ImageTo3dRenderOptions.test.jsxnew file mode 100644index 0000000000..25bec9c815--- /dev/null+++ b/client/src/components/media/ImageTo3dRenderOptions.test.jsx@@ -0,0 +1,47 @@+import { describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import ImageTo3dRenderOptions from './ImageTo3dRenderOptions';++const setup = (props = {}) => render(+ <ImageTo3dRenderOptions+ steps=""+ onStepsChange={vi.fn()}+ seed=""+ onSeedChange={vi.fn()}+ keyBackground+ onKeyBackgroundChange={vi.fn()}+ {...props}+ />,+);++describe('ImageTo3dRenderOptions', () => {+ it('enables the Quality control by default', () => {+ setup();+ expect(screen.getByLabelText('Quality')).toBeEnabled();+ expect(screen.queryByText(/no step control/i)).toBeNull();+ });++ // A target whose runner drops `steps` (Pixal3D's upstream CLI has no per-phase step+ // override) must not be offered a control that silently does nothing.+ it('disables the Quality control and says why when steps are unsupported', () => {+ setup({ stepsSupported: false, steps: '24' });+ const quality = screen.getByLabelText('Quality');+ expect(quality).toBeDisabled();+ expect(screen.getByText(/no step control/i)).toBeInTheDocument();+ // Forced to the pipeline default rather than showing a value that won't apply.+ expect(quality).toHaveValue('');+ });++ it('leaves Seed and the keying toggle usable when only steps are unsupported', () => {+ setup({ stepsSupported: false });+ expect(screen.getByLabelText('Seed')).toBeEnabled();+ expect(screen.getByRole('checkbox')).toBeEnabled();+ });++ it('disables everything when the whole form is disabled', () => {+ setup({ disabled: true });+ expect(screen.getByLabelText('Quality')).toBeDisabled();+ expect(screen.getByLabelText('Seed')).toBeDisabled();+ expect(screen.getByRole('checkbox')).toBeDisabled();+ });+});diff --git a/client/src/lib/imageTo3dReasons.js b/client/src/lib/imageTo3dReasons.jsindex c3d6636a39..e5654bea9e 100644--- a/client/src/lib/imageTo3dReasons.js+++ b/client/src/lib/imageTo3dReasons.js@@ -21,7 +21,12 @@ export const UNAVAILABLE_REASONS = Object.freeze({// 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)',- 'insufficient-vram': 'Needs a 24 GB+ NVIDIA GPU',+ // Deliberately carries NO GB figure. It used to read "Needs a 24 GB+ NVIDIA GPU"+ // when every CUDA target shared that floor; `pixal3dCuda` runs from 12 GB, so a+ // single number here would be wrong for one lane or the other. The per-target+ // requirement travels to the client on the descriptor (`requires.minVramGb`) for a+ // UI that wants to name it.+ 'insufficient-vram': 'This NVIDIA GPU has too little VRAM',// The probe itself failed — say so rather than claiming the GPU isn't there.'cuda-probe-failed': 'Could not detect this host’s GPU',});diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex 720605eee3..3c28658c53 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -89,14 +89,16 @@ function StatusBadge({ target }) {);}if (target.installed) {- // An installed target whose Metal texture bake is missing still renders — the- // geometry is fine — but the surface comes out scrambled, so "Ready" alone- // would be a lie. `quality:'unknown'` (the probe couldn't run) stays Ready- // rather than crying wolf about an install that is probably fine.- if (target.textureBake?.quality === 'fallback') {+ // An installed-but-degraded target still renders — TRELLIS.2 with no Metal bake+ // produces correct geometry with a scrambled surface; Pixal3D with no NATTEN+ // falls back to DINO projection features — so "Ready" alone would be a lie. The+ // server normalizes every such case into `degraded` (see the adapter contract),+ // and a probe that could NOT run reports nothing here rather than crying wolf+ // about an install that is probably fine.+ if (target.degraded) {return (<span className="inline-flex items-center gap-1.5 text-xs font-medium text-port-warning">- <AlertTriangle className="w-3.5 h-3.5" /> Ready · degraded textures+ <AlertTriangle className="w-3.5 h-3.5" /> Ready · {target.degraded.label}</span>);}@@ -113,12 +115,12 @@ function TargetCard({ target, onInstall }) {// Install only applies to targets with a local install concept (installed is a// boolean); hosted targets report installed:null and are Ready when available.const canInstall = target.available && target.installed === false;- const degradedBake = target.textureBake?.quality === 'fallback';- // Repair install re-runs setup, which now downloads the Metal Toolchain itself- // (#3041) — but only offer it when the server says it can actually fix this. On a- // Command-Line-Tools-only host `repairable` is false and the remedy is installing- // Xcode, so a Repair button would just fail the same way and read as broken.- const canRepair = degradedBake && target.textureBake?.repairable !== false;+ const degraded = target.degraded;+ // Repair install re-runs setup — but only offer it when the server says it can+ // actually fix this. On a Command-Line-Tools-only host `repairable` is false and the+ // remedy is installing Xcode, so a Repair button would just fail the same way and+ // read as broken.+ const canRepair = !!degraded && degraded.repairable !== false;return (<div className="rounded-lg border border-port-border bg-port-card p-4">@@ -164,9 +166,9 @@ function TargetCard({ target, onInstall }) {)}</div></div>- {degradedBake && target.textureBake?.help && (+ {degraded?.help && (<p className="mt-3 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-[11px] leading-relaxed text-port-warning">- {target.textureBake.help}+ {degraded.help}</p>)}</div>@@ -395,6 +397,7 @@ export default function Media3D() {)}<ImageTo3dRenderOptions+ stepsSupported={selectedTarget?.supportsRenderOptions?.steps !== false}steps={steps}onStepsChange={setSteps}seed={seed}@@ -520,15 +523,26 @@ export default function Media3D() {runtime={installTarget?.id}label={installTarget?.label}installUrlBase={installTarget ? `/api/image-to-3d/targets/${installTarget.id}/install` : undefined}- // Repairing an already-installed target must re-run setup.sh rather than- // short-circuit on "already installed" — that re-run is what rebuilds the Metal- // texture-baking backends once their build deps are present: the Metal Toolchain- // (#2952/#3041) and trellis2-apple's Eigen submodule, which upstream's setup.sh- // never fetches, so o_voxel could never compile without the apple-deps step.- params={installTarget?.textureBake?.quality === 'fallback' ? { repair: '1' } : undefined}- description={installTarget?.textureBake?.quality === 'fallback'- ? 'Fetching whichever build dependency is missing — the Xcode Metal Toolchain, the Eigen submodule the mesh baker compiles against, or both — then re-running the TRELLIS.2 setup to rebuild its Metal texture-baking backends. Your already-downloaded models are kept, and no password is required.'- : `Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python environment (~15 GB on first run). Missing build dependencies (the Xcode Metal Toolchain, the mesh baker's Eigen submodule) are fetched first, so textures bake at full quality.${gatedRepoCount ? ` It also pulls ${gatedRepoCount} gated Hugging Face ${gatedRepoCount === 1 ? 'model' : 'models'} on first render — accept their terms and add a Hugging Face token above (see the note on the 3D page).` : ''}`}+ // Repairing an already-installed target must re-run its setup rather than+ // short-circuit on "already installed" — that re-run is what rebuilds whatever+ // was missing (TRELLIS.2's Metal backends, Pixal3D's NATTEN kernels) now that+ // its build deps are present.+ params={installTarget?.degraded ? { repair: '1' } : undefined}+ // Copy comes from the target descriptor, never hard-coded here: this modal is+ // shared by every target, so TRELLIS.2-specific prose would misdescribe the+ // others. A degraded target explains its own remedy via `degraded.help`.+ // `undefined` rather than '' when a target has nothing to say, so+ // RuntimeInstallModal's own default description applies instead of a blank panel.+ description={installTarget?.degraded+ // The degraded help text owns the whole message (both targets' already end by+ // saying downloaded models are kept) — appending to it would repeat that.+ ? installTarget.degraded.help+ : [+ installTarget?.installNotes,+ gatedRepoCount+ ? `It also pulls ${gatedRepoCount} gated Hugging Face ${gatedRepoCount === 1 ? 'model' : 'models'} on first render — accept their terms and add a Hugging Face token above (see the note on the 3D page).`+ : null,+ ].filter(Boolean).join(' ') || undefined}onClose={() => setInstallTarget(null)}onComplete={() => { setInstallTarget(null); load(); }}/>diff --git a/client/src/pages/Media3D.test.jsx b/client/src/pages/Media3D.test.jsxindex 1ec0bc6fc0..ed559075ec 100644--- a/client/src/pages/Media3D.test.jsx+++ b/client/src/pages/Media3D.test.jsx@@ -111,7 +111,7 @@ describe('Media3D — models & install', () => {getImageTo3dTargets.mockResolvedValue({targets: [target({installed: true,- textureBake: { quality: 'fallback', missing: ['mtldiffrast'], help: 'Install the Metal Toolchain.' },+ degraded: { label: 'degraded textures', help: 'Install the Metal Toolchain.', repairable: true },})],});renderAt();@@ -126,9 +126,8 @@ describe('Media3D — models & install', () => {getImageTo3dTargets.mockResolvedValue({targets: [target({installed: true,- textureBake: {- quality: 'fallback', missing: ['mtldiffrast'], repairable: false,- blocker: 'requires-xcode', help: 'Install Xcode from the App Store.',+ degraded: {+ label: 'degraded textures', help: 'Install Xcode from the App Store.', repairable: false,},})],});@@ -138,14 +137,37 @@ describe('Media3D — models & install', () => {expect(screen.queryByRole('button', { name: /install/i })).toBeNull();});- it('stays plain Ready when the bake probe could not determine anything', async () => {- // A probe that failed must not cry wolf about an install that is probably fine.+ // The degraded projection is normalized server-side, so a target degraded for an+ // entirely different reason (Pixal3D with no NATTEN) renders through the same path+ // with no per-target UI branch.+ it('renders a non-TRELLIS degradation through the same badge and Repair button', async () => {getImageTo3dTargets.mockResolvedValue({- targets: [target({ installed: true, textureBake: { quality: 'unknown', missing: [] } })],+ targets: [target({+ id: 'pixal3dCuda',+ label: 'Pixal3D (CUDA)',+ installed: true,+ degraded: { label: 'NAF fallback', help: 'NATTEN is missing.', repairable: true },+ })],+ });+ renderAt();+ expect(await screen.findByText(/NAF fallback/i)).toBeInTheDocument();+ expect(screen.getByText('NATTEN is missing.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /repair install/i })).toBeInTheDocument();+ // Must NOT leak the other lane's copy.+ expect(screen.queryByText(/metal toolchain/i)).toBeNull();+ });++ it('stays plain Ready when the server reports no degradation', async () => {+ // The server owns the unknown-vs-degraded distinction (a probe that merely failed+ // must not cry wolf) and expresses it by OMITTING `degraded`. Asserting on the+ // absence of that field is what actually exercises the component; a `textureBake`+ // fixture would not, since nothing here reads it.+ getImageTo3dTargets.mockResolvedValue({+ targets: [target({ installed: true })],});renderAt();expect(await screen.findByText(/ready/i)).toBeInTheDocument();- expect(screen.queryByText(/degraded textures/i)).toBeNull();+ expect(screen.queryByText(/degraded/i)).toBeNull();expect(screen.queryByRole('button', { name: /install/i })).toBeNull();});diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsxindex c6f91876ae..74b0ea73c1 100644--- a/client/src/pages/Media3DDetail.jsx+++ b/client/src/pages/Media3DDetail.jsx@@ -169,6 +169,7 @@ export default function Media3DDetail() {<div className="mb-4 rounded-lg border border-port-border bg-port-card p-3"><ImageTo3dRenderOptions+ stepsSupported={record.supportsRenderOptions?.steps !== false}steps={steps}onStepsChange={setSteps}seed={seed}diff --git a/server/lib/README.md b/server/lib/README.mdindex 279c36f61b..538c47e094 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -340,7 +340,8 @@ 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`). |+| `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. |+| `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`). `detectCudaComputeCapability()` is a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH`; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. || `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/condaEnv.js b/server/lib/condaEnv.jsnew file mode 100644index 0000000000..55e50f0883--- /dev/null+++ b/server/lib/condaEnv.js@@ -0,0 +1,67 @@+/**+ * Conda environment resolution.+ *+ * Where a NAMED conda environment's interpreter lives. Deliberately its own module+ * rather than part of `pythonSetup.js`: every resolver in that file probes *venv*+ * layouts (`~/.portos/venv-<name>/bin/python3`), and — more importantly — it computes+ * candidate lists from `PATHS` at MODULE LOAD time, so importing it just to resolve a+ * conda path drags that eager work (and its mock sensitivity) into every consumer.+ * This module imports nothing but `node:fs`/`node:os`/`node:path` and has no+ * load-time side effects.+ *+ * Consumed by the image-to-3D CUDA lanes (`trellis2Cuda.js`, `pixal3dCuda.js`), which+ * each own a separate conda env on purpose so one lane's pinned dependencies cannot+ * disturb the other's.+ */++import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';++/**+ * Ordered candidate paths for a named CONDA environment's python.+ *+ * Distinct from every other resolver in this file, which probe *venv* layouts+ * (`~/.portos/venv-<name>/bin/python3`). Conda puts its environments under+ * `<root>/envs/<name>`, and the root itself varies by installer — so the machine's own+ * answer comes first (`CONDA_PREFIX`, `CONDA_ROOT`) and the standard+ * miniconda/anaconda/miniforge/mamba locations follow.+ *+ * The subtle part, and the reason this is shared rather than copied per caller: when+ * PortOS is ITSELF running under some other conda env, `CONDA_PREFIX` points at+ * `<root>/envs/<that-env>` rather than at the root — so an `envs/<name>` prefix is+ * walked up two levels to recover the root. Getting that wrong makes the target look+ * uninstalled on exactly the machines most likely to have it.+ *+ * Linux/macOS paths (`bin/python`) only; every current caller gates itself to a POSIX+ * host, so there is no Windows branch here to bit-rot (WSL2 reports as Linux).+ *+ * @param {string} envName the conda environment name (e.g. `trellis2`).+ * @param {{env?: object}} [opts]+ * @returns {string[]}+ */+export function condaEnvPythonCandidates(envName, { env = process.env } = {}) {+ const roots = [+ env.CONDA_PREFIX && /[/\\]envs[/\\][^/\\]+$/.test(env.CONDA_PREFIX)+ ? join(env.CONDA_PREFIX, '..', '..')+ : env.CONDA_PREFIX,+ env.CONDA_ROOT,+ join(homedir(), 'miniconda3'),+ join(homedir(), 'anaconda3'),+ join(homedir(), 'miniforge3'),+ join(homedir(), 'mambaforge'),+ '/opt/conda',+ ].filter(Boolean);+ return roots.map((root) => join(root, 'envs', envName, 'bin', 'python'));+}++/**+ * The first existing candidate from `condaEnvPythonCandidates`, or null. `exists` is+ * injectable so callers stay unit-testable without a real conda install.+ * @param {string} envName+ * @param {{exists?: (p: string) => boolean, env?: object}} [opts]+ * @returns {string|null}+ */+export function resolveCondaEnvPython(envName, { exists = existsSync, env } = {}) {+ return condaEnvPythonCandidates(envName, { env }).find((p) => exists(p)) || null;+}diff --git a/server/lib/condaEnv.test.js b/server/lib/condaEnv.test.jsnew file mode 100644index 0000000000..c2a046455a--- /dev/null+++ b/server/lib/condaEnv.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import { posixPath } from './testHelper.js';+import { condaEnvPythonCandidates, resolveCondaEnvPython } from './condaEnv.js';++describe('conda environment python resolution', () => {+ const CONDA = '/opt/conda';+ const envPy = (root, name) => `${root}/envs/${name}/bin/python`;+ // The resolver composes paths with `join()`, which emits backslashes on Windows, so+ // EVERY comparison against a forward-slash literal has to normalize first — a raw+ // `toBe(envPy(...))` here passed on macOS and failed the Windows CI job.+ const candidatesFor = (name, env) => condaEnvPythonCandidates(name, { env }).map(posixPath);++ it('probes the machine-declared roots first, then the standard install locations', () => {+ const candidates = candidatesFor('trellis2', { CONDA_ROOT: CONDA });+ expect(candidates[0]).toBe(envPy(CONDA, 'trellis2'));+ // Every candidate targets the requested env, never another one.+ expect(candidates.every((p) => p.includes('/envs/trellis2/'))).toBe(true);+ expect(candidates.some((p) => p.startsWith('/opt/conda/'))).toBe(true);+ });++ it('walks up from an active envs/<name> CONDA_PREFIX to recover the root', () => {+ // The subtle case this helper exists to centralize: PortOS itself running under a+ // DIFFERENT conda env must still locate the target env, not look inside its own.+ const candidates = candidatesFor('pixal3d', { CONDA_PREFIX: `${CONDA}/envs/portos` });+ expect(candidates).toContain(envPy(CONDA, 'pixal3d'));+ expect(candidates.some((p) => p.includes('/envs/portos/'))).toBe(false);+ });++ it('uses a base-install CONDA_PREFIX as the root directly', () => {+ expect(candidatesFor('trellis2', { CONDA_PREFIX: CONDA })).toContain(envPy(CONDA, 'trellis2'));+ });++ it('keeps each env name separate', () => {+ const a = condaEnvPythonCandidates('trellis2', { env: { CONDA_ROOT: CONDA } });+ const b = condaEnvPythonCandidates('pixal3d', { env: { CONDA_ROOT: CONDA } });+ // Two lanes with diverged dependency sets must never resolve to one interpreter.+ expect(a.filter((p) => b.includes(p))).toEqual([]);+ });++ it('resolves the first existing candidate, or null when none exist', () => {+ const target = condaEnvPythonCandidates('pixal3d', { env: { CONDA_ROOT: CONDA } })[0];+ expect(resolveCondaEnvPython('pixal3d', {+ exists: (p) => p === target, env: { CONDA_ROOT: CONDA },+ })).toBe(target);+ expect(resolveCondaEnvPython('pixal3d', {+ exists: () => false, env: { CONDA_ROOT: CONDA },+ })).toBeNull();+ });+});diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.jsindex c518fa82f4..aa0f5c8a96 100644--- a/server/lib/cudaCapability.js+++ b/server/lib/cudaCapability.js@@ -25,6 +25,57 @@import { execFile } from './childProcess.js';+/**+ * Spawn `nvidia-smi` with `queryArgs` and triage the outcome, without interpreting the+ * rows. The three probes below differ only in their columns and their parser, so the+ * shell they share — the callback-to-promise wrapper and the `ENOENT` ⇒ real-negative+ * vs anything-else ⇒ `'unknown'` triage — lives here once.+ *+ * `status` is null when the command SUCCEEDED and the caller should parse `stdout`.+ * Module-private on purpose: it is a shape-sharing device, not a new public probe, so+ * it adds no `server/lib/` barrel or README obligation.+ *+ * @param {string[]} queryArgs+ * @param {{execFileImpl?: Function, timeoutMs?: number}} [opts]+ * `error` follows the majority contract (null on `ENOENT`, since absent hardware is an+ * answer rather than a failure); `rawError` always carries the underlying message, so+ * the one probe with a different historical contract can keep it.+ *+ * @returns {Promise<{status: 'absent'|'unknown'|null, stdout: string,+ * error: string|null, rawError: string|null}>}+ */+async function queryNvidiaSmi(queryArgs, { execFileImpl = execFile, timeoutMs } = {}) {+ const result = await new Promise((resolve) => {+ execFileImpl('nvidia-smi', [...queryArgs], { timeout: timeoutMs },+ (err, stdout) => resolve({ err, stdout: String(stdout ?? '') }));+ }).catch((err) => ({ err, stdout: '' }));+ if (!result.err) return { status: null, stdout: result.stdout, error: null, rawError: null };+ const rawError = result.err.message || null;+ // `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', stdout: '', error: null, rawError };+ // It exists but wouldn't answer (driver/library mismatch, timeout, a driver too old+ // for one of these columns). We genuinely do not know what hardware is here.+ return { status: 'unknown', stdout: '', error: rawError || 'nvidia-smi failed', rawError };+}++/**+ * MiB → whole GB, or null when the column didn't parse.+ *+ * Rounded rather than floored because a "24 GB" card reports a hair under 24 GiB and+ * must not trip a 24 GB floor. Shared by both row parsers so this policy is stated+ * once — it matters more since the CUDA image-to-3D lanes have DIFFERENT VRAM floors+ * (12 GB and 24 GB), and a rounding change that reached only one parser would move one+ * lane's gate and not the other's.+ *+ * @param {string|number} mib+ * @returns {number|null}+ */+function vramGbFromMib(mib) {+ const vramMib = Number(mib);+ return Number.isFinite(vramMib) && vramMib > 0 ? Math.round(vramMib / 1024) : null;+}+/*** 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:@@ -59,17 +110,91 @@ export function parseNvidiaSmiUtilization(stdout) {}export async function detectCudaUtilization({ execFileImpl = execFile, timeoutMs = 2000 } = {}) {- const result = await new Promise((resolve) => {- execFileImpl('nvidia-smi', [...NVIDIA_SMI_UTILIZATION_QUERY_ARGS], { timeout: timeoutMs },- (err, stdout) => resolve({ err, stdout: String(stdout ?? '') }));- }).catch((err) => ({ err, stdout: '' }));- if (result.err) {- return { status: result.err.code === 'ENOENT' ? 'absent' : 'unknown', gpus: [], error: result.err.message || null };- }- const gpus = parseNvidiaSmiUtilization(result.stdout);+ const probe = await queryNvidiaSmi(NVIDIA_SMI_UTILIZATION_QUERY_ARGS, { execFileImpl, timeoutMs });+ // NOTE: this probe reports the raw `error` message even on ENOENT, where the other+ // two report null. That asymmetry is pre-existing, so it reads `rawError` to preserve+ // its exact contract — sharing the spawn shell must not silently change what a+ // caller returns.+ if (probe.status) return { status: probe.status, gpus: [], error: probe.rawError };+ const gpus = parseNvidiaSmiUtilization(probe.stdout);return { status: gpus.length ? 'available' : 'absent', gpus, error: null };}+/**+ * One CSV row per GPU: `<name>, <compute capability>, <total VRAM in MiB>` — e.g.+ * `NVIDIA GeForce RTX 3090, 8.6, 24576`.+ *+ * **Deliberately a SECOND query rather than extra columns on `NVIDIA_SMI_QUERY_ARGS`.**+ * `compute_cap` needs a reasonably modern `nvidia-smi`; asking an older driver for it+ * fails the WHOLE query, which would turn every host with an old driver into a global+ * `'unknown'` and take the working `local-cuda` lane down with it. Compute capability+ * is only needed at Pixal3D install time (to build NATTEN for the right arch), so it+ * gets its own probe whose failure is contained to that one installer.+ */+export const NVIDIA_SMI_COMPUTE_CAP_QUERY_ARGS = Object.freeze([+ '--query-gpu=name,compute_cap,memory.total',+ '--format=csv,noheader,nounits',+]);++/**+ * Parse the compute-capability query into GPU descriptors. Pure.+ *+ * A row whose `compute_cap` column doesn't parse carries `computeCap: null` (the same+ * "present but unmeasured" sentinel `parseNvidiaSmiGpus` uses for VRAM) rather than+ * being dropped — a card we cannot classify is still a card, and callers gate on the+ * null instead of being told there is no GPU.+ *+ * @param {string} stdout+ * @returns {Array<{name: string, computeCap: string|null, vramGb: number|null}>}+ */+export function parseNvidiaSmiComputeCaps(stdout) {+ const gpus = [];+ for (const raw of String(stdout ?? '').split(/\r?\n/)) {+ const line = raw.trim();+ if (!line) continue;+ const [name, cap, mib] = line.split(',').map((cell) => cell.trim());+ if (!name) continue;+ // `8.6` / `12.0` — a bare major.minor. Anything else is an unreadable column, not+ // an arch we should hand to a compiler flag.+ const computeCap = /^\d+\.\d+$/.test(cap || '') ? cap : null;+ gpus.push({ name, computeCap, vramGb: vramGbFromMib(mib) });+ }+ return gpus;+}++/**+ * Probe the CUDA compute capability of this host's GPUs. Always resolves, with the+ * same three-state `status` contract as `detectCudaGpus` (see the file header).+ *+ * `primaryComputeCap` is the arch of the LARGEST card, not the highest arch: a render+ * runs on one GPU and the lane picks the biggest one, so the build flag must describe+ * that same card. Ties resolve to the first row. `null` when no row carried a+ * readable arch — callers must treat that as "could not determine" and fall back to a+ * compiler default, never guess an arch.+ *+ * @param {{execFileImpl?: Function, timeoutMs?: number}} [opts]+ * @returns {Promise<{status: 'available'|'absent'|'unknown', gpus: Array<object>,+ * primaryComputeCap: string|null, error: string|null}>}+ */+export async function detectCudaComputeCapability({ execFileImpl = execFile, timeoutMs = 8000 } = {}) {+ // A driver too old for `compute_cap` lands in `'unknown'` via the shared triage.+ const probe = await queryNvidiaSmi(NVIDIA_SMI_COMPUTE_CAP_QUERY_ARGS, { execFileImpl, timeoutMs });+ if (probe.status) {+ return { status: probe.status, gpus: [], primaryComputeCap: null, error: probe.error };+ }++ const gpus = parseNvidiaSmiComputeCaps(probe.stdout);+ if (!gpus.length) return { status: 'absent', gpus: [], primaryComputeCap: null, error: null };+ // Largest card first (unsized cards sort last), then take its arch.+ const ranked = [...gpus].sort((a, b) => (b.vramGb ?? -1) - (a.vramGb ?? -1));+ return {+ status: 'available',+ gpus,+ primaryComputeCap: ranked.find((g) => g.computeCap)?.computeCap ?? null,+ error: null,+ };+}+/*** 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@@ -93,14 +218,11 @@ export function parseNvidiaSmiGpus(stdout) {// 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;+ const vramGb = vramGbFromMib(mib);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,+ vramMib: vramGb === null ? null : Number(mib),+ vramGb,});}return gpus;@@ -116,32 +238,12 @@ export function parseNvidiaSmiGpus(stdout) {* 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 },- (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 probe = await queryNvidiaSmi(NVIDIA_SMI_QUERY_ARGS, { execFileImpl, timeoutMs });+ if (probe.status) {+ return { status: probe.status, gpus: [], maxVramGb: null, error: probe.error };}- const gpus = parseNvidiaSmiGpus(result.stdout);+ const gpus = parseNvidiaSmiGpus(probe.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 };diff --git a/server/lib/cudaCapability.test.js b/server/lib/cudaCapability.test.jsindex ecc2b69992..fa8369908f 100644--- a/server/lib/cudaCapability.test.js+++ b/server/lib/cudaCapability.test.js@@ -6,6 +6,10 @@ import {getCudaCapability,resetCudaCapabilityCache,CUDA_UNKNOWN_RETRY_MS,+ parseNvidiaSmiComputeCaps,+ detectCudaComputeCapability,+ NVIDIA_SMI_COMPUTE_CAP_QUERY_ARGS,+ detectCudaUtilization,} from './cudaCapability.js';// Real output from `nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits`@@ -175,3 +179,105 @@ describe('getCudaCapability caching', () => {expect(recovered).toHaveBeenCalledTimes(1);});});++describe('parseNvidiaSmiComputeCaps', () => {+ it('parses name, compute capability and VRAM per row', () => {+ const gpus = parseNvidiaSmiComputeCaps(+ 'NVIDIA GeForce RTX 3090, 8.6, 24576\nNVIDIA L40S, 8.9, 46068\n',+ );+ expect(gpus).toEqual([+ { name: 'NVIDIA GeForce RTX 3090', computeCap: '8.6', vramGb: 24 },+ { name: 'NVIDIA L40S', computeCap: '8.9', vramGb: 45 },+ ]);+ });++ it('keeps a card whose arch column is unreadable, with a null sentinel', () => {+ // Present but unclassifiable is NOT the same as absent — dropping the row would+ // under-report the host as having no GPU.+ const gpus = parseNvidiaSmiComputeCaps('NVIDIA A100-SXM4-40GB, [N/A], 40960\n');+ expect(gpus).toEqual([{ name: 'NVIDIA A100-SXM4-40GB', computeCap: null, vramGb: 40 }]);+ });++ it('ignores blank lines and rows with no name', () => {+ expect(parseNvidiaSmiComputeCaps('\n\n \n')).toEqual([]);+ expect(parseNvidiaSmiComputeCaps(null)).toEqual([]);+ });+});++describe('detectCudaComputeCapability', () => {+ const smi = (stdout) => (_bin, _args, _opts, cb) => cb(null, stdout);++ it('reports the arch of the LARGEST card, not the highest arch', async () => {+ // A render runs on one GPU and the lane picks the biggest one, so the build flag+ // must describe THAT card even when a smaller card has a newer arch.+ const res = await detectCudaComputeCapability({+ execFileImpl: smi('NVIDIA RTX 5090, 12.0, 32768\nNVIDIA L40S, 8.9, 46068\n'),+ });+ expect(res.status).toBe('available');+ expect(res.primaryComputeCap).toBe('8.9');+ });++ it('queries compute_cap separately from the VRAM probe', () => {+ // Folding compute_cap into NVIDIA_SMI_QUERY_ARGS would make an old driver fail the+ // whole probe and take the working local-cuda lane down with it.+ expect(NVIDIA_SMI_COMPUTE_CAP_QUERY_ARGS.join(' ')).toContain('compute_cap');+ expect(NVIDIA_SMI_QUERY_ARGS.join(' ')).not.toContain('compute_cap');+ });++ it('says absent when nvidia-smi is not installed', async () => {+ const err = Object.assign(new Error('nope'), { code: 'ENOENT' });+ const res = await detectCudaComputeCapability({ execFileImpl: (_b, _a, _o, cb) => cb(err) });+ expect(res).toMatchObject({ status: 'absent', primaryComputeCap: null });+ });++ it('says unknown — not absent — when an old driver rejects the query', async () => {+ const err = Object.assign(new Error('invalid field'), { code: 1 });+ const res = await detectCudaComputeCapability({ execFileImpl: (_b, _a, _o, cb) => cb(err) });+ expect(res.status).toBe('unknown');+ expect(res.primaryComputeCap).toBeNull();+ });++ it('reports null arch (never a guess) when no row carries a readable one', async () => {+ const res = await detectCudaComputeCapability({+ execFileImpl: smi('NVIDIA A100-SXM4-40GB, [N/A], 40960\n'),+ });+ expect(res.status).toBe('available');+ expect(res.primaryComputeCap).toBeNull();+ });++ it('says absent on exit 0 with no rows', async () => {+ const res = await detectCudaComputeCapability({ execFileImpl: smi('\n') });+ expect(res).toMatchObject({ status: 'absent', primaryComputeCap: null });+ });+});++describe('detectCudaUtilization', () => {+ it('parses utilization rows', async () => {+ const res = await detectCudaUtilization({+ execFileImpl: (_b, _a, _o, cb) => cb(null, 'NVIDIA L40S, 42, 1024, 46068\n'),+ });+ expect(res.status).toBe('available');+ expect(res.gpus[0]).toEqual({+ name: 'NVIDIA L40S', utilizationPercent: 42, memoryUsedMib: 1024, memoryTotalMib: 46068,+ });+ });++ it('keeps its divergent ENOENT error contract', async () => {+ // This probe reports the RAW error message on ENOENT where detectCudaGpus and+ // detectCudaComputeCapability both report null. That asymmetry is pre-existing and+ // is the sole reason the shared nvidia-smi shell carries a separate `rawError`+ // field — pin it, so a later "simplification" that folds rawError into error can't+ // change this payload with a green suite.+ const err = Object.assign(new Error('spawn nvidia-smi ENOENT'), { code: 'ENOENT' });+ const util = await detectCudaUtilization({ execFileImpl: (_b, _a, _o, cb) => cb(err) });+ expect(util).toMatchObject({ status: 'absent', error: 'spawn nvidia-smi ENOENT' });+ // The contrast that makes the divergence explicit:+ expect((await detectCudaGpus({ execFileImpl: (_b, _a, _o, cb) => cb(err) })).error).toBeNull();+ });++ it('says unknown when nvidia-smi exists but fails', async () => {+ const err = Object.assign(new Error('driver mismatch'), { code: 1 });+ const res = await detectCudaUtilization({ execFileImpl: (_b, _a, _o, cb) => cb(err) });+ expect(res).toMatchObject({ status: 'unknown', error: 'driver mismatch' });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 5e883afbb2..d166814842 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -320,6 +320,7 @@ export * from './vaultCrypto.js';// === Model & config ===export * from './browserConfig.js';export * from './buildId.js';+export * from './condaEnv.js';export * from './cudaCapability.js';export * from './db.js';export * from './pgTimestamp.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 688a0f06a5..1b750a57d3 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -74,7 +74,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk', 'add model', 'install model', 'custom model'] },{ id: 'nav.media.threejs', path: '/media/threejs', label: 'Three.js Models', section: 'Create', aliases: ['threejs', 'three-js', '3d-models', 'image-to-3d', 'img2threejs'], keywords: ['procedural', '3d', 'mesh', 'model', 'gallery', 'webgl', 'preview'] },- { id: 'nav.create.3d', path: '/3d', label: '3D', section: 'Create', aliases: ['3d', 'image-to-mesh', 'mesh', 'trellis', 'neural-3d'], keywords: ['trellis', 'glb', 'mesh', 'photogrammetry', 'neural', 'image to 3d', 'install', 'model', 'pbr'] },+ { id: 'nav.create.3d', path: '/3d', label: '3D', section: 'Create', aliases: ['3d', 'image-to-mesh', 'mesh', 'trellis', 'pixal3d', 'neural-3d'], keywords: ['trellis', 'pixal3d', 'pixal', 'glb', 'mesh', 'photogrammetry', 'neural', 'image to 3d', 'install', 'model', 'pbr'] },{ id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },{ id: 'nav.create.universe-builder', path: '/universes', label: 'Universes', section: 'Create', aliases: ['universes', 'universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries', 'list', 'manage'] },{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 513cd7e5f4..f7686e75f1 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -3,14 +3,7 @@ import { createReadStream } from 'node:fs';import { z } from 'zod';import { asyncHandler, ServerError, sendErrorResponse } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import {- getTarget,- listTargets,- detectHostCapabilities,- unavailableReason,- unavailableReasonLabel,- IMAGE_TO_3D_TARGET_IDS,-} from '../services/imageTo3d/targets.js';+import { getTarget, listTargets, detectHostCapabilities, unavailableReason, unavailableReasonLabel, IMAGE_TO_3D_TARGET_IDS, renderOptionSupportFor } from '../services/imageTo3d/targets.js';import { getTargetAdapter } from '../services/imageTo3d/adapters.js';import {listModels,@@ -252,10 +245,27 @@ router.get('/models', asyncHandler(async (_req, res) => {res.json(await listModels());}));+/**+ * Attach the target's render-option support to a model response.+ *+ * Projected at the response boundary, never stored: the detail view loads a RECORD+ * rather than the target list, and still has to know which per-run knobs this record's+ * target honors. Derived from the descriptor on every read, so it cannot go stale.+ *+ * Applied to EVERY response that returns a model, not just the GET. The client does+ * `setRecord(next)` with the POST body, so a create/re-render response that omitted the+ * field would blank it — flipping the disabled Quality control and its hint back on+ * until the next poll restored them.+ */+const withRenderSupport = (model) => {+ const supportsRenderOptions = renderOptionSupportFor(model.target);+ return supportsRenderOptions ? { ...model, supportsRenderOptions } : model;+};+router.post('/models', asyncHandler(async (req, res) => {const input = validateRequest(createModelSchema, req.body);const model = await createModel(input);- res.status(202).json(model);+ res.status(202).json(withRenderSupport(model));}));router.get('/models/:id/asset', asyncHandler(async (req, res) => {@@ -287,7 +297,7 @@ router.get('/models/:id/asset', asyncHandler(async (req, res) => {router.get('/models/:id', asyncHandler(async (req, res) => {const model = await getModel(req.params.id);if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });- res.json(model);+ res.json(withRenderSupport(model));}));router.post('/models/:id/generate', asyncHandler(async (req, res) => {@@ -295,7 +305,7 @@ router.post('/models/:id/generate', asyncHandler(async (req, res) => {// only and are recorded on its run entry.const options = validateRequest(renderOptionsSchema, req.body ?? {});const model = await startGeneration(req.params.id, { options });- res.status(202).json(model);+ res.status(202).json(withRenderSupport(model));}));router.delete('/models/:id', asyncHandler(async (req, res) => {diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex b41f21d7a4..a95e18877c 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -162,6 +162,82 @@ describe('image-to-3d routes', () => {expect(trellis2.probeMetalToolchain).not.toHaveBeenCalled();});+ // FINDING: the render-option projection had no route coverage at all, and the client+ // does `setRecord(next)` with the POST bodies — so a create/re-render response that+ // omitted the field blanked the disabled Quality control until the next poll.+ describe('supportsRenderOptions projection', () => {+ const record = (target) => ({ id: 'image3d-1', target, status: 'ready', runs: [] });++ it('projects the field onto GET, create, and re-render responses', async () => {+ const app = makeApp();+ models.getModel.mockResolvedValue(record('pixal3dCuda'));+ models.createModel.mockResolvedValue(record('pixal3dCuda'));+ models.startGeneration.mockResolvedValue(record('pixal3dCuda'));++ const get = await request(app).get('/api/image-to-3d/models/image3d-1');+ expect(get.body.supportsRenderOptions).toEqual({ steps: false });++ const created = await request(app).post('/api/image-to-3d/models')+ .send({ filename: 'example.png', name: 'x' });+ expect(created.body.supportsRenderOptions).toEqual({ steps: false });++ const regen = await request(app).post('/api/image-to-3d/models/image3d-1/generate').send({});+ expect(regen.body.supportsRenderOptions).toEqual({ steps: false });+ });++ it('omits the field for a target that honors every knob', async () => {+ // Absent must mean "all supported" so existing targets need no descriptor entry.+ models.getModel.mockResolvedValue(record('trellis2'));+ const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1');+ expect(res.body.supportsRenderOptions).toBeUndefined();+ });+ });++ // The `degraded` projection is what the CLIENT actually renders (badge, help panel,+ // Repair button); `textureBake` above is retained only for API back-compat and has no+ // in-repo reader. These cases pin the live contract, which was previously untested.+ it('GET /targets projects a degraded bake into the normalized `degraded` shape', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'fix it',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].degraded).toEqual({+ label: 'degraded textures', help: 'fix it', repairable: true,+ });+ });++ it('GET /targets carries repairable:false into `degraded` when nothing PortOS runs can fix it', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'fix it',+ });+ trellis2.probeMetalToolchain.mockResolvedValueOnce({+ available: false, installable: false, blocker: 'requires-xcode', hint: 'install Xcode',+ });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ // The inversion here (`repairable !== false`) is easy to get backwards, and getting+ // it backwards offers a Repair button that cannot work.+ expect(res.body.targets[0].degraded).toMatchObject({ repairable: false, help: 'install Xcode' });+ });++ it('GET /targets omits `degraded` when the bake probe could not determine anything', async () => {+ // The sentinel that matters: 'unknown' must NOT read as degraded, or a probe that+ // simply failed makes a healthy install look broken.+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({+ quality: 'unknown', missing: [], degradedQuality: [], modules: {},+ });+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].degraded).toBeUndefined();+ });++ it('GET /targets omits `degraded` for a healthy bake', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(true);+ const res = await request(makeApp()).get('/api/image-to-3d/targets');+ expect(res.body.targets[0].degraded).toBeUndefined();+ });+it('GET /targets skips the bake probe entirely when trellis2 is not installed', async () => {trellis2.probeTrellis2TextureBake.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);diff --git a/server/services/imageTo3d/adapters.degraded.test.js b/server/services/imageTo3d/adapters.degraded.test.jsnew file mode 100644index 0000000000..32383209ed--- /dev/null+++ b/server/services/imageTo3d/adapters.degraded.test.js@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest';++// Only the module probe is stubbed — the projection under test is the real thing.+vi.mock('./pixal3dCuda.js', async (importOriginal) => ({+ ...(await importOriginal()),+ probePixal3dModules: vi.fn(),+}));++import { TARGET_ADAPTERS } from './adapters.js';+import { probePixal3dModules, PIXAL3D_NAF_FALLBACK_HELP } from './pixal3dCuda.js';++const describeState = () => TARGET_ADAPTERS.pixal3dCuda.describeInstallState();++describe('pixal3dCuda degraded-state projection', () => {+ it('reports an incomplete install when a REQUIRED extension did not build', async () => {+ // `setup.sh` is sourced and can exit 0 with a failed extension build, and the+ // install's `verify` hook only checks the interpreter + entrypoint. So this+ // projection is the ONLY thing standing between a half-built install and a card+ // that reads plain "Ready" until the first render dies in the GLB exporter.+ probePixal3dModules.mockResolvedValueOnce({ naf: 'available', missing: ['o_voxel'] });+ const state = await describeState();+ expect(state.fields.degraded).toMatchObject({ label: 'incomplete install', repairable: true });+ expect(state.fields.degraded.help).toContain('o_voxel');+ expect(state.warnings).toHaveLength(1);+ });++ it('names every missing extension, not just the first', async () => {+ probePixal3dModules.mockResolvedValueOnce({ naf: 'available', missing: ['o_voxel', 'flex_gemm'] });+ const state = await describeState();+ expect(state.fields.degraded.help).toContain('o_voxel and flex_gemm');+ });++ it('lets an incomplete install outrank a NAF fallback', async () => {+ // Both are repairable by the same action, so reporting the milder one would+ // understate the problem.+ probePixal3dModules.mockResolvedValueOnce({+ naf: 'unavailable', missing: ['o_voxel'], help: PIXAL3D_NAF_FALLBACK_HELP,+ });+ const state = await describeState();+ expect(state.fields.degraded.label).toBe('incomplete install');+ });++ it('reports the NAF fallback when the install is otherwise complete', async () => {+ probePixal3dModules.mockResolvedValueOnce({+ naf: 'unavailable', missing: [], help: PIXAL3D_NAF_FALLBACK_HELP,+ });+ const state = await describeState();+ expect(state.fields.degraded).toEqual({+ label: 'NAF fallback', help: PIXAL3D_NAF_FALLBACK_HELP, repairable: true,+ });+ });++ it('reports nothing degraded for a healthy install', async () => {+ probePixal3dModules.mockResolvedValueOnce({ naf: 'available', missing: [] });+ const state = await describeState();+ expect(state.fields.degraded).toBeUndefined();+ expect(state.warnings).toEqual([]);+ expect(state.fields.naf).toBe('available');+ });++ it('reports nothing degraded when the probe could not run', async () => {+ // "Failed to determine" must never render as "determined to be broken".+ probePixal3dModules.mockResolvedValueOnce({ naf: 'unknown', missing: [] });+ const state = await describeState();+ expect(state.fields.degraded).toBeUndefined();+ expect(state.warnings).toEqual([]);+ });+});diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.jsindex 99716b96b2..2ee670cf17 100644--- a/server/services/imageTo3d/adapters.js+++ b/server/services/imageTo3d/adapters.js@@ -35,6 +35,17 @@* short-circuit) without knowing what they're about; `fields` are extra keys* merged onto the target in `GET /targets` (e.g. TRELLIS.2's texture-bake* quality). Omit when a target has nothing extra to report.+ *+ * **A degraded-but-working install reports `fields.degraded`**:+ * `{ label, help, repairable }`. This is the ONE shape the client renders, so the+ * badge / help panel / Repair button work for any target without a per-target+ * branch. `repairable: false` means re-running install cannot fix it and no Repair+ * button is offered.+ *+ * A target may also return its own narrow diagnostic field, but keep it small and+ * keep the UI off it. `trellis2` still returns `textureBake` with **no in-repo+ * reader** — retained purely for API back-compat, since an older client on a newer+ * server reads that field and PortOS installs update independently.*/import { hfChildEnv } from '../../lib/hfToken.js';@@ -50,6 +61,13 @@ import {installTrellis2Cuda,runTrellis2CudaGenerate,} from './trellis2Cuda.js';+import {+ isPixal3dCudaInstalled,+ installPixal3dCuda,+ runPixal3dCudaGenerate,+ probePixal3dModules,+} from './pixal3dCuda.js';+import { detectCudaComputeCapability } from '../../lib/cudaCapability.js';export const TARGET_ADAPTERS = Object.freeze({trellis2: Object.freeze({@@ -73,7 +91,8 @@ export const TARGET_ADAPTERS = Object.freeze({run: runTrellis2Generate,async describeInstallState() {const bake = await probeTrellis2TextureBake();- const toolchain = bake.quality === 'fallback' ? await probeMetalToolchain() : null;+ const degradedBake = bake.quality === 'fallback';+ const toolchain = degradedBake ? await probeMetalToolchain() : null;// A degraded bake has two very different remedies, and the card must not// offer the wrong one: when the Metal Toolchain is merely missing, Repair// install fetches it and rebuilds (#3041); when only the Command Line Tools@@ -81,10 +100,22 @@ export const TARGET_ADAPTERS = Object.freeze({// Xcode first.const textureBake = toolchain?.blocker? { ...bake, repairable: false, blocker: toolchain.blocker, help: toolchain.hint }- : { ...bake, ...(bake.quality === 'fallback' ? { repairable: true } : {}) };+ : { ...bake, ...(degradedBake ? { repairable: true } : {}) };return {- fields: { textureBake },- warnings: textureBake.quality === 'fallback' ? [textureBake.help] : [],+ fields: {+ textureBake,+ // Normalized degraded-state projection — see the `degraded` note in this+ // file's adapter contract. The client renders THIS, not `textureBake`, so a+ // target with a different kind of degradation needs no new UI branch.+ ...(degradedBake ? {+ degraded: {+ label: 'degraded textures',+ help: textureBake.help,+ repairable: textureBake.repairable !== false,+ },+ } : {}),+ },+ warnings: degradedBake ? [textureBake.help] : [],};},}),@@ -106,6 +137,74 @@ export const TARGET_ADAPTERS = Object.freeze({vramGb: caps?.cudaVramGb ?? null,}),}),+ pixal3dCuda: Object.freeze({+ isInstalled: isPixal3dCudaInstalled,+ // Nothing Pixal3D pulls is GATED (see its descriptor), but the download still goes+ // through Hugging Face, so the same resolved token is passed for rate-limit+ // headroom on a ~24 GB weight fetch.+ resolveEnv: hfChildEnv,+ async install({ onEvent = () => {}, env } = {}) {+ // NATTEN compiles CUDA kernels for a specific arch, so the install needs this+ // host's compute capability. Resolved HERE (the impure adapter boundary) rather+ // than inside the pure step builder, and never guessed: an `unknown` probe omits+ // the env var so NATTEN picks its own default instead of building for the wrong+ // card. Surfaced as a log line because it changes what the build produces.+ const probe = await detectCudaComputeCapability();+ const computeCap = probe.primaryComputeCap;+ onEvent({+ type: 'log',+ stage: 'preflight',+ message: computeCap+ ? `\u2139\uFE0F Building NATTEN for CUDA arch ${computeCap}.`+ : '\u26A0\uFE0F Could not read this GPU\u2019s CUDA compute capability — '+ + 'NATTEN will build for its default arch, which may not match this card.',+ });+ return installPixal3dCuda({ onEvent, env, computeCap });+ },+ // Resolution/offload tier scales with the card. `run` must stay synchronous to keep+ // its { promise, kill } contract, so it reads VRAM out of the capabilities the+ // dispatcher resolved at the request boundary. An absent/unsized card yields `null`+ // and the runner picks the 1024 low-VRAM floor: degraded quality, never an+ // overcommitted GPU.+ run: ({ caps, ...opts }) => runPixal3dCudaGenerate({+ ...opts,+ vramGb: caps?.cudaVramGb ?? null,+ }),+ async describeInstallState() {+ const probe = await probePixal3dModules();+ // A REQUIRED module missing means the install did not COMPLETE — `setup.sh` is+ // sourced and can exit 0 with a failed extension build, and `installPixal3dCuda`'s+ // `verify` hook only checks the interpreter and the entrypoint, never the compiled+ // extensions. So this is the only place that can surface it: without this, a+ // half-built install reads plain "Ready" and the first render dies deep in the GLB+ // exporter as an unclassified failure.+ const incomplete = probe.missing?.length ? probe.missing : null;+ const nafFallback = probe.naf === 'unavailable';+ // An incomplete install outranks a NAF fallback — it is the more severe problem,+ // and the same Repair action addresses both, so only the worse one is reported.+ const degraded = incomplete+ ? {+ label: 'incomplete install',+ help: `Pixal3D is installed but ${incomplete.join(' and ')} did not build, so renders `+ + 'will fail in the mesh exporter. Repair install rebuilds the CUDA extensions; '+ + 'your downloaded models are kept.',+ repairable: true,+ }+ : nafFallback+ ? { label: 'NAF fallback', help: probe.help, repairable: true }+ : null;+ return {+ fields: {+ // Narrow on purpose: shipping the whole probe made the wire shape+ // `target.modules.modules` (a raw find_spec map) with no consumer.+ naf: probe.naf,+ // The normalized shape the client renders — see the adapter contract above.+ ...(degraded ? { degraded } : {}),+ },+ warnings: degraded?.help ? [degraded.help] : [],+ };+ },+ }),});/**diff --git a/server/services/imageTo3d/laneRunner.js b/server/services/imageTo3d/laneRunner.jsindex 7270cf239a..c3048d6386 100644--- a/server/services/imageTo3d/laneRunner.js+++ b/server/services/imageTo3d/laneRunner.js@@ -18,11 +18,58 @@* (CLAUDE.md child-process exception).*/-import { spawn } from '../../lib/childProcess.js';+import { execFile, spawn } from '../../lib/childProcess.js';import { sleep as defaultSleep } from '../../lib/fileUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { createLineReader } from '../../lib/streamLines.js';+/** The one-liner the module probe runs; `find_spec` resolves without importing. */+export const PYTHON_MODULE_PROBE_SOURCE = 'import importlib.util as u,json,sys;'+ + 'print(json.dumps({m: u.find_spec(m) is not None for m in sys.argv[1:]}))';++/**+ * Which of `modules` resolve inside a target's python environment.+ *+ * Uses `importlib.util.find_spec`, which locates a module WITHOUT importing it — so+ * the probe costs ~20-30 ms and never pulls in torch. That is what makes it cheap+ * enough to run on every `GET /targets` request; a real `import` would cost seconds.+ *+ * Shared because every lane needs the same question answered about a different module+ * set, and only the CLASSIFICATION of the answer is lane-specific (TRELLIS.2 maps it+ * to a texture-bake quality, Pixal3D to a NAF availability). Returns `null` — never a+ * partial map — when the probe could not run, so callers can keep "failed to+ * determine" distinct from "determined to be missing" (CLAUDE.md sentinel rule).+ *+ * Child-process boundary outside the request lifecycle: every failure path resolves.+ * Note the JSON parse happens AFTER the callback resolves rather than inside it — a+ * throw inside an `execFile` callback escapes the enclosing promise entirely and+ * reaches the event loop, which would crash the process rather than degrade the probe.+ *+ * @param {{python: string, modules: string[], execFileImpl?: Function, timeoutMs?: number}} opts+ * @returns {Promise<Record<string, boolean>|null>}+ */+export async function probePythonModules({+ python,+ modules,+ execFileImpl = execFile,+ timeoutMs = 15000,+} = {}) {+ if (!python || !Array.isArray(modules) || !modules.length) return null;+ const stdout = await new Promise((resolve) => {+ execFileImpl(python, ['-c', PYTHON_MODULE_PROBE_SOURCE, ...modules], { timeout: timeoutMs },+ (err, out) => resolve(err ? null : String(out ?? '')));+ }).catch(() => null);+ if (stdout === null) return null;+ const parsed = (() => {+ try {+ return JSON.parse(stdout.trim() || 'null');+ } catch {+ return null;+ }+ })();+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;+}+/*** Build a case-insensitive predicate testing text against an alternation of signature* phrases — the shape every subprocess-error classifier in this feature uses (eachdiff --git a/server/services/imageTo3d/laneRunner.test.js b/server/services/imageTo3d/laneRunner.test.jsindex 368a567dff..d8a48ba839 100644--- a/server/services/imageTo3d/laneRunner.test.js+++ b/server/services/imageTo3d/laneRunner.test.js@@ -1,6 +1,9 @@import { EventEmitter } from 'node:events';import { describe, expect, it, vi } from 'vitest';-import { runGenerateSubprocess } from './laneRunner.js';+import {+ runGenerateSubprocess,+ probePythonModules,+} from './laneRunner.js';const makeChild = () => {const child = new EventEmitter();@@ -113,3 +116,47 @@ describe('runGenerateSubprocess line buffering', () => {await expect(promise).rejects.toMatchObject({ code: 'TEST_OOM' });});});++describe('probePythonModules', () => {+ const ok = (payload) => (_py, _args, _opts, cb) => cb(null, JSON.stringify(payload));++ it('reports which modules resolve', async () => {+ const res = await probePythonModules({+ python: '/py', modules: ['a', 'b'], execFileImpl: ok({ a: true, b: false }),+ });+ expect(res).toEqual({ a: true, b: false });+ });++ it('passes the find_spec one-liner and the module list to the interpreter', async () => {+ const seen = [];+ await probePythonModules({+ python: '/py',+ modules: ['o_voxel', 'natten'],+ execFileImpl: (py, args, _o, cb) => { seen.push(py, args); cb(null, '{}'); },+ });+ expect(seen[0]).toBe('/py');+ // find_spec, NOT import — the probe must never pull torch into the request path.+ expect(seen[1][1]).toContain('find_spec');+ expect(seen[1].slice(2)).toEqual(['o_voxel', 'natten']);+ });++ it('returns null — never a partial map — when the probe cannot run', async () => {+ // "Failed to determine" must stay distinct from "determined to be missing", or a+ // broken probe reports a healthy install as degraded.+ expect(await probePythonModules({+ python: '/py', modules: ['a'], execFileImpl: (_p, _a, _o, cb) => cb(new Error('boom')),+ })).toBeNull();+ expect(await probePythonModules({ python: null, modules: ['a'] })).toBeNull();+ expect(await probePythonModules({ python: '/py', modules: [] })).toBeNull();+ });++ it('degrades rather than crashing on unparseable output', async () => {+ // Regression guard: parsing inside the execFile callback would let a throw escape+ // the enclosing promise and reach the event loop, killing the process.+ for (const bad of ['not json', '', 'null', '[1,2]', ' ']) {+ await expect(probePythonModules({+ python: '/py', modules: ['a'], execFileImpl: (_p, _a, _o, cb) => cb(null, bad),+ })).resolves.toBeNull();+ }+ });+});diff --git a/server/services/imageTo3d/models.genericDispatch.test.js b/server/services/imageTo3d/models.genericDispatch.test.jsindex 050a4a54a4..26db8c0a20 100644--- a/server/services/imageTo3d/models.genericDispatch.test.js+++ b/server/services/imageTo3d/models.genericDispatch.test.js@@ -24,6 +24,7 @@ vi.mock('./targets.js', () => ({resolveTarget: vi.fn((id) => ({targetId: id, target: { id, label: id }, available: true, reason: null,})),+ renderOptionSupportFor: () => null,}));vi.mock('../../lib/hfToken.js', () => ({diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex 365029e3fc..2c19934932 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -23,9 +23,13 @@ import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';import { prepareLocalMemory } from '../../lib/localMemory.js';import { slugifyForFilename } from '../../lib/civitai.js';-import { detectHostCapabilities, resolveTarget, DEFAULT_IMAGE_TO_3D_TARGET } from './targets.js';+import {+ detectHostCapabilities, resolveTarget, renderOptionSupportFor, DEFAULT_IMAGE_TO_3D_TARGET,+} from './targets.js';import { getTargetAdapter } from './adapters.js';-import { normalizeRenderOptions, randomRenderSeed } from './renderOptions.js';+import {+ normalizeRenderOptions, randomRenderSeed, honorTargetRenderSupport,+} from './renderOptions.js';import { prepareSourceImage } from './sourceKeying.js';import * as store from './db.js';@@ -321,7 +325,14 @@ async function beginRender(record, adapter, sourcePath, caps, requestOptions) {const operationId = randomUUID();const startedAt = new Date().toISOString();const normalized = normalizeRenderOptions(requestOptions);- const options = { ...normalized, seed: normalized.seed ?? randomRenderSeed() };+ // Drop knobs this target's runner won't honor BEFORE the run entry is written, so the+ // persisted record is what the subprocess actually received rather than what was+ // asked for (renderOptions.js's stated invariant). Pixal3D is the case in point: its+ // `inference.py` has no step override, so a recorded `steps: 48` would be a lie.+ const options = honorTargetRenderSupport(+ { ...normalized, seed: normalized.seed ?? randomRenderSeed() },+ renderOptionSupportFor(record.target),+ );const next = await store.mutateModel(id, (fresh) => {if (fresh.status === 'generating') {throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsindex f93213fb27..fadceb3d73 100644--- a/server/services/imageTo3d/models.test.js+++ b/server/services/imageTo3d/models.test.js@@ -22,6 +22,7 @@ vi.mock('./targets.js', () => ({? { targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: true, reason: null }: { targetId: id, target: null, available: false, reason: 'unknown-target' })),+ renderOptionSupportFor: vi.fn(() => null),}));vi.mock('./trellis2.js', () => ({@@ -65,7 +66,7 @@ vi.mock('./db.js', () => ({import { rm } from 'node:fs/promises';import { ensureDir } from '../../lib/fileUtils.js';-import { resolveTarget } from './targets.js';+import { resolveTarget, renderOptionSupportFor } from './targets.js';import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';import { prepareSourceImage } from './sourceKeying.js';@@ -348,6 +349,20 @@ describe('render options and source keying', () => {expect(current.renderOptions).toBeUndefined();});+ // The run entry is the reproducible record of what the subprocess RECEIVED. A target+ // whose runner drops a knob (Pixal3D has no per-phase step override) must therefore+ // record it as unset AND not hand it to the runner — logging the requested value+ // would make the ledger lie about a setting that never applied.+ it('drops an unsupported render option from BOTH the runner call and the run entry', async () => {+ renderOptionSupportFor.mockReturnValueOnce({ steps: false });+ await createModel({ name: 'Beacon', filename: 'example.png', steps: 48, seed: 7 });+ await vi.waitFor(() => expect(current.status).toBe('ready'));++ const [generateArgs] = runTrellis2Generate.mock.calls[0];+ expect(generateArgs.steps).toBeNull();+ expect(current.runs.at(-1)).toMatchObject({ steps: null, seed: 7 });+ });+it('a re-generate without options gets defaults, not the previous run’s values', async () => {wireStore({...draftRecord(),diff --git a/server/services/imageTo3d/pixal3dCuda.js b/server/services/imageTo3d/pixal3dCuda.jsnew file mode 100644index 0000000000..e32fc82468--- /dev/null+++ b/server/services/imageTo3d/pixal3dCuda.js@@ -0,0 +1,592 @@+/**+ * Pixal3D (local NVIDIA / CUDA) target — install detection, pure command builders,+ * and a guarded generate runner.+ *+ * `TencentARC/Pixal3D` (SIGGRAPH 2026, MIT) is a pixel-aligned image→3D model built+ * on the TRELLIS.2 backbone: it back-projects pixel features into 3D instead of+ * injecting them through attention, which is what buys it near-reconstruction-level+ * geometry and PBR texture at 1536³. This lane is the CUDA sibling of+ * `trellis2Cuda.js` and deliberately mirrors its shape — the subprocess machinery+ * (install sequencing with transient retry, cancel, the generate child driver) is+ * shared through `laneRunner.js`, so this file is only what is Pixal3D-specific.+ * Everything is either pure or exercised through injectable `exists`/`spawnImpl`, so+ * the wiring is unit-testable WITHOUT an NVIDIA box, a ~40 GB install, or a live+ * render. `runPixal3dCudaGenerate` is the one real subprocess boundary and NEVER+ * auto-runs (CLAUDE.md no-cold-bootstrap policy).+ *+ * **Four things differ from the TRELLIS.2 CUDA lane, and each drives the design:**+ *+ * 1. **Upstream SHIPS a CLI.** Unlike `microsoft/TRELLIS.2` (whose `example.py` has+ * hard-coded paths, forcing PortOS to ship `trellis2CudaGenerateRunner.py`),+ * Pixal3D's `inference.py` is a real image→GLB entrypoint. So there is no PortOS+ * Python runner here — re-implementing it would mean re-deriving its MoGe-2 camera+ * estimation and FOV/distance solve, which is exactly the domain code most likely+ * to be got subtly wrong.+ *+ * 2. **`--output` is a full path, NOT a stem.** TRELLIS.2's runners take a stem and+ * append `.glb`; `inference.py` writes precisely the path it is given. So this lane+ * must NOT route `outputPath` through `trellis2OutputStem` — doing so would silently+ * produce `model` with no extension.+ *+ * 3. **Its own conda env, and its own TRELLIS.2 checkout.** Pixal3D's install is+ * "set up TRELLIS.2's environment, then add our deps", and those deps pin+ * `transformers`/`diffusers`/`pillow` versions. Installing them into the existing+ * `trellis2` env would mutate a working target's dependency set — a change that+ * degrades a *different* lane is the worst kind, so this lane pays ~15 GB of extra+ * disk for isolation. Upstream's `setup.sh --new-env` hard-codes+ * `conda create -n trellis2`, so the env is created here (named `pixal3d`) and+ * `setup.sh` is sourced WITHOUT `--new-env` so it installs into the active env.+ *+ * 4. **No gated Hugging Face repos.** `trellis2Cuda` needs `facebook/dinov3` accepted;+ * Pixal3D loads DINOv3 from the `camenduru/...` mirror and MoGe from+ * `Ruicheng/moge-2-vitl`, both ungated. Its descriptor therefore declares no+ * `gatedRepos` — a token still helps with rate limits, but nothing needs accepting.+ *+ * Clone layout: `~/.portos/pixal3d/{TRELLIS.2,Pixal3D}`, conda env `pixal3d`. The env's+ * interpreter is resolved by the shared `resolveCondaEnvPython` (`lib/condaEnv.js`),+ * which both CUDA lanes use — the `CONDA_PREFIX` walk-up it encodes is subtle enough+ * that a second copy would be a liability.+ */++import { existsSync } from 'node:fs';+import { cpus, homedir } from 'node:os';+import { join } from 'node:path';+import { spawn } from '../../lib/childProcess.js';+import { resolveCondaEnvPython } from '../../lib/condaEnv.js';+import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';+import {+ hfGatedRepoHelp,+ isHfAuthError,+ isTransientInstallError,+ parseGenerateProgress,+} from './trellis2.js';+import { isCudaOomError, TRELLIS2_CUDA_REPO } from './trellis2Cuda.js';+import {+ textMatcher, runInstallSteps, runGenerateSubprocess, probePythonModules,+} from './laneRunner.js';+import { validateRenderOptions } from './renderOptions.js';++const HOME = homedir();++/** Error-code namespace and user-facing name for this lane's subprocess failures. */+const CODE_PREFIX = 'PIXAL3D_CUDA';+const LABEL = 'Pixal3D (CUDA)';++/**+ * Upstream TencentARC/Pixal3D.+ *+ * **Cloned at its DEFAULT branch (`master`), deliberately not `main`.** Upstream's+ * README carries a "Branches" table naming `main` as the TRELLIS.2-backbone version+ * and `paper` as the Direct3D-S2 original — but there is no `main` branch on the+ * remote (only `master`, `paper`, `pr-12`), and `master` is the TRELLIS.2-backbone+ * code. Pinning `-b main` from the README would make the clone step fail outright.+ */+export const PIXAL3D_REPO = 'https://github.com/TencentARC/Pixal3D.git';++/** The conda environment this lane builds. Named to avoid colliding with `trellis2`. */+export const PIXAL3D_CONDA_ENV = 'pixal3d';++/** Python the env is created with — matches what TRELLIS.2's `setup.sh` uses. */+export const PIXAL3D_PYTHON_VERSION = '3.10';++/** NATTEN pin from upstream's install guide (neighborhood attention for the NAF upsampler). */+export const PIXAL3D_NATTEN_VERSION = '0.21.0';++/** The `utils3d` wheel upstream pins by URL (not on PyPI at this version). */+export const PIXAL3D_UTILS3D_WHEEL = 'https://github.com/LDYang694/Storages/releases/download/20260430/utils3d-0.0.2-py3-none-any.whl';++/** Clone/install root. `base` overridable for tests. */+export function pixal3dRoot(base = join(HOME, '.portos')) {+ return join(base, 'pixal3d');+}++/** Where TRELLIS.2 is cloned — sourced only for its `setup.sh` + extension submodules. */+export function pixal3dTrellisDir(base) {+ return join(pixal3dRoot(base), 'TRELLIS.2');+}++/** Where Pixal3D itself is cloned — the code this lane actually runs. */+function pixal3dRepoDir(base) {+ return join(pixal3dRoot(base), 'Pixal3D');+}++/** Upstream's shipped entrypoint. */+function pixal3dInferenceScript(base) {+ return join(pixal3dRepoDir(base), 'inference.py');+}++/**+ * The conda Python for this lane, or null when its env doesn't exist. A one-line+ * wrapper over the shared resolver so the env name lives in exactly one place.+ * @param {{exists?: (p: string) => boolean, env?: object}} [opts]+ * @returns {string|null}+ */+export function pixal3dPython({ exists = existsSync, env } = {}) {+ return resolveCondaEnvPython(PIXAL3D_CONDA_ENV, { exists, env });+}++/**+ * Installed ⇔ the conda env's Python exists AND upstream's entrypoint is on disk.+ * Both halves matter: the env can be created and then the dependency build can fail,+ * which would otherwise read as a complete install (the lesson `trellis2Cuda`'s verify+ * step encodes).+ * @param {{base?: string, exists?: (p: string) => boolean, env?: object}} [opts]+ * @returns {boolean}+ */+export function isPixal3dCudaInstalled({ base, exists = existsSync, env } = {}) {+ if (!pixal3dPython({ exists, env })) return false;+ return exists(pixal3dInferenceScript(base));+}++/**+ * TRELLIS.2 `setup.sh` flags for this lane — the same extension set the+ * `trellis2Cuda` lane builds, MINUS `--new-env` (see the file header: the env is+ * created separately so it can be named `pixal3d`).+ *+ * Pixal3D imports `o_voxel` (the GLB exporter) and `flex_gemm` directly, and defaults+ * `ATTN_BACKEND` to `flash_attn`, so `--o-voxel`, `--flexgemm` and `--flash-attn` are+ * load-bearing rather than optional; `--nvdiffrast`/`--nvdiffrec`/`--cumesh` back the+ * texture bake and mesh ops the exporter calls.+ */+export const PIXAL3D_SETUP_FLAGS = Object.freeze([+ '--basic', '--flash-attn', '--nvdiffrast', '--nvdiffrec',+ '--cumesh', '--o-voxel', '--flexgemm',+]);++/** Build workers for the NATTEN compile — bounded so it can't monopolize the box. */+export function nattenWorkerCount(cpuCount = cpus().length) {+ const n = Number.isFinite(cpuCount) && cpuCount > 0 ? cpuCount : 4;+ return Math.max(1, Math.min(8, Math.floor(n / 2)));+}++/**+ * The install as an ordered list of `{stage, command, args, cwd?, optional?}` steps.+ *+ * Every step is skippable/idempotent so a run that died partway re-reaches the rest+ * rather than aborting on "already exists" — the resume property both TRELLIS.2 lanes+ * rely on. `conda create` is skipped when the env's Python is already present, and+ * each clone is skipped when its `.git` is there.+ *+ * Same sourcing mechanics as `buildCudaInstallSteps` (`. ./setup.sh` inside `bash -lc`,+ * so `conda activate` has the hooks `conda init` wrote); the one difference is that our+ * env is activated FIRST, because `--new-env` is omitted — see the file header.+ *+ * **The NATTEN step is `optional`.** It compiles CUDA kernels for a specific arch, and+ * a failure there is survivable: without NATTEN the pipeline takes upstream's+ * documented NAF fallback path — slower and lower quality, but it renders. Failing the+ * whole ~40 GB install over it would be a worse outcome than a degraded one the+ * install-state probe then reports. `computeCap` comes from+ * `detectCudaComputeCapability()`; when it could not be determined the env var is+ * omitted entirely rather than guessed, letting NATTEN pick its own default.+ *+ * `env` is threaded through so the "does the conda env already exist?" question gets+ * the SAME answer here as in the install's `verify` hook — reading `process.env` here+ * while `verify` reads an injected env would let this prepend a redundant `conda create`+ * that `verify` then disagrees with.+ *+ * @param {string} [base]+ * @param {{exists?: (p: string) => boolean, env?: object, computeCap?: string|null}} [opts]+ * @returns {Array<{stage: string, command: string, args: string[], cwd?: string, optional?: boolean}>}+ */+export function buildPixal3dInstallSteps(base, { exists = existsSync, env, computeCap = null } = {}) {+ const trellisDir = pixal3dTrellisDir(base);+ const repoDir = pixal3dRepoDir(base);+ const steps = [];++ if (!pixal3dPython({ exists, env })) {+ steps.push({+ stage: 'env',+ command: 'conda',+ args: ['create', '-n', PIXAL3D_CONDA_ENV, `python=${PIXAL3D_PYTHON_VERSION}`, '-y'],+ });+ }+ // Recursive: TRELLIS.2 vendors its CUDA extensions as submodules, and a shallow+ // clone yields empty extension dirs and a setup that fails deep in a compile.+ if (!exists(join(trellisDir, '.git'))) {+ steps.push({+ stage: 'clone-trellis',+ command: 'git',+ args: ['clone', '--recursive', TRELLIS2_CUDA_REPO, trellisDir],+ });+ }+ if (!exists(join(repoDir, '.git'))) {+ steps.push({ stage: 'clone', command: 'git', args: ['clone', PIXAL3D_REPO, repoDir] });+ }+ // Every remaining step is "activate our env, then run one command", so only the+ // command, the cwd and the optional-ness are worth reading per step.+ const condaStep = (stage, script, extra = {}) => ({+ stage,+ command: 'bash',+ args: ['-lc', `conda activate ${PIXAL3D_CONDA_ENV} && ${script}`],+ cwd: repoDir,+ ...extra,+ });+ const nattenEnv = [+ ...(computeCap ? [`NATTEN_CUDA_ARCH=${computeCap}`] : []),+ `NATTEN_N_WORKERS=${nattenWorkerCount()}`,+ ].join(' ');+ steps.push(+ condaStep('setup', `. ./setup.sh ${PIXAL3D_SETUP_FLAGS.join(' ')}`, { cwd: trellisDir }),+ condaStep('deps', 'pip install -r requirements.txt'),+ condaStep(+ 'natten',+ `${nattenEnv} pip install natten==${PIXAL3D_NATTEN_VERSION} --no-build-isolation`,+ { optional: true },+ ),+ condaStep('utils3d', `pip install ${PIXAL3D_UTILS3D_WHEEL}`),+ );+ return steps;+}++export const PIXAL3D_STANDARD_MODE_MIN_VRAM_GB = 36;+export const PIXAL3D_HIGH_RES_MIN_VRAM_GB = 24;+/** Upstream's two supported pipeline resolutions, low to high. */+export const PIXAL3D_RESOLUTIONS = [1024, 1536];+const [PIXAL3D_RES_FLOOR, PIXAL3D_RES_FULL] = PIXAL3D_RESOLUTIONS;++/**+ * Resolution / offload lane, picked from the card's VRAM.+ *+ * Upstream documents three usable combinations, and they are genuinely three tiers+ * rather than a single quality knob (Pixal3D issue #7 measured "18–36 GB depending on+ * settings"; the merged low-VRAM PR brings peak to ~10–12 GB by loading one pipeline+ * stage onto the GPU at a time):+ *+ * - `>= PIXAL3D_STANDARD_MODE_MIN_VRAM_GB` → standard mode at full resolution. No+ * offload, so it is also the fastest.+ * - `>= PIXAL3D_HIGH_RES_MIN_VRAM_GB` → full resolution with `--low_vram`. Upstream+ * explicitly supports forcing full resolution in low-VRAM mode; the stage-at-a-time+ * offload pays for it in wall-clock rather than quality.+ * - otherwise → the floor resolution with `--low_vram`, the least this lane supports.+ *+ * An unknown/unparseable VRAM reading degrades to the floor rather than overcommitting+ * a card we failed to size (CLAUDE.md sentinel rule).+ *+ * @param {number|null} vramGb+ * @returns {{lowVram: boolean, resolution: number}}+ */+export function selectPixal3dRenderBudget(vramGb) {+ const gb = Number(vramGb);+ if (gb >= PIXAL3D_STANDARD_MODE_MIN_VRAM_GB) return { lowVram: false, resolution: PIXAL3D_RES_FULL };+ if (gb >= PIXAL3D_HIGH_RES_MIN_VRAM_GB) return { lowVram: true, resolution: PIXAL3D_RES_FULL };+ return { lowVram: true, resolution: PIXAL3D_RES_FLOOR };+}++/**+ * The generate invocation:+ * `<conda-python> inference.py --image <src> --output <dst.glb> [--resolution N] [--low_vram] …`+ *+ * Pure. Throws on a missing image (a render with no input is a bug, not an empty run)+ * and on a resolution outside upstream's accepted set — better to fail here than to+ * have argparse abort a job we already queued.+ *+ * `outputPath` is passed THROUGH, not reduced to a stem: `inference.py --output` is a+ * full file path (see the file header).+ *+ * `steps`/`seed` are validated against the shared ranges so they cannot drift from the+ * TRELLIS.2 lanes — but upstream's `inference.py` exposes no per-phase step override, so+ * `steps` is validated and NOT emitted (an unrecognized flag would make argparse abort a+ * job we already queued). The target descriptor declares that with+ * `supportsRenderOptions.steps: false`, which is what stops the UI offering a control+ * that does nothing and stops the run ledger recording a value that never applied.+ *+ * @param {{imagePath: string, outputPath?: string, base?: string, python?: string,+ * resolution?: number, lowVram?: boolean,+ * steps?: number|null, seed?: number|null}} opts+ * @returns {{command: string, args: string[]}}+ */+export function buildPixal3dGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ resolution = PIXAL3D_RES_FLOOR,+ lowVram = true,+ steps = null,+ seed = null,+} = {}) {+ if (!imagePath) throw new Error('buildPixal3dGenerateArgs: imagePath is required');+ if (!PIXAL3D_RESOLUTIONS.includes(resolution)) {+ throw new Error(+ `buildPixal3dGenerateArgs: resolution must be one of ${PIXAL3D_RESOLUTIONS.join(', ')}`,+ );+ }+ // Both are range-checked at the same boundary as the other lanes; only seed is emitted.+ validateRenderOptions('buildPixal3dGenerateArgs', { steps, seed });+ const args = [+ pixal3dInferenceScript(base),+ '--image', imagePath,+ '--resolution', String(resolution),+ ];+ if (outputPath) args.push('--output', outputPath);+ if (lowVram) args.push('--low_vram');+ if (seed !== null) args.push('--seed', String(seed));+ return { command: python || pixal3dPython({}) || 'python', args };+}++/**+ * Upstream's own progress banners, mapped to the shared stage/percent vocabulary.+ *+ * Pixal3D prints `[Pipeline]`/`[Inference]`/`[MoGe-2]`/`[NAF]`-prefixed lines rather+ * than the banners `parseGenerateProgress` was written for, so this table covers them+ * — kept HERE rather than added to `GENERATE_STAGE_SIGNATURES` so the two TRELLIS.2+ * lanes' parsing cannot regress from a Pixal3D change. Percents follow the same bands+ * (load < 10, sampling 10–50, texture ~65, export 92) so the bar stays monotonic.+ */+const PIXAL3D_STAGE_SIGNATURES = [+ { re: /^\[Pipeline\] Loading from/i, stage: 'loading', percent: 2 },+ { re: /^\[ImageCond\]/i, stage: 'loading', percent: 3 },+ { re: /^\[NAF\]/i, stage: 'loading', percent: 4 },+ { re: /^\[Pipeline\] (Low-VRAM|Standard) mode/i, stage: 'loading', percent: 5 },+ { re: /^\[Inference\] Processing image/i, stage: 'loading', percent: 6 },+ { re: /^\[MoGe-2\]/i, stage: 'loading', percent: 7 },+ { re: /^\[Inference\] (Estimating camera|Using manual FOV)/i, stage: 'loading', percent: 8 },+ { re: /^\[Inference\] Running 3D generation/i, stage: 'generating', percent: 10 },+ { re: /^\[Inference\] Using pipeline_type/i, stage: 'generating', percent: 11 },+ { re: /^\[Inference\] Extracting GLB/i, stage: 'texturing', percent: 65 },+];++/**+ * Parse one line of `inference.py` output into a progress frame, or null.+ *+ * Delegates to the shared `parseGenerateProgress` FIRST, which is what handles the two+ * signals both lanes share: a written `.glb` path (the terminal export frame, matched+ * by `[Done] GLB saved to: …`) and a bare `tqdm` percentage scaled into the sampling+ * band. Only lines it finds no signal in are matched against Pixal3D's own banners, so+ * the terminal export frame can never be shadowed by a banner rule.+ *+ * @param {string} line+ * @returns {{stage: string, percent?: number, assetPath?: string, message: string}|null}+ */+export function parsePixal3dProgress(line) {+ const shared = parseGenerateProgress(line);+ if (shared) return shared;+ const text = String(line ?? '').trim();+ if (!text) return null;+ for (const sig of PIXAL3D_STAGE_SIGNATURES) {+ if (sig.re.test(text)) return { stage: sig.stage, percent: sig.percent, message: text };+ }+ return null;+}++/**+ * Modules Pixal3D imports directly — absent means the install did not complete, not+ * that quality degrades. `o_voxel` is the GLB exporter and `flex_gemm` the sparse GEMM+ * its autotuner configures on import. Upstream's own `pixal3d` package is deliberately+ * NOT probed: it resolves only with the clone root on `sys.path`, which the render+ * subprocess gets from its `cwd` and this probe does not, so it would always read as+ * missing.+ */+export const PIXAL3D_REQUIRED_MODULES = ['o_voxel', 'flex_gemm'];++/** NATTEN backs the NAF upsampler. Absent ⇒ renders take upstream's fallback path. */+export const PIXAL3D_NAF_MODULES = ['natten'];++export const PIXAL3D_NAF_FALLBACK_HELP = 'Pixal3D is installed, but NATTEN is missing, '+ + 'so its NAF refinement step falls back to DINO projection features — slower, and '+ + 'geometry/texture detail is a notch lower than upstream. Repair install rebuilds '+ + 'NATTEN for this GPU; your downloaded models are kept.';++/**+ * Probe which of the env's modules resolve, for the install-state card. The spawn and+ * its find_spec one-liner are shared (`probePythonModules`); only the classification+ * below is Pixal3D-specific.+ *+ * **`naf: 'available'` means the NATTEN PACKAGE resolves — it does NOT prove the CUDA+ * `libnatten` kernels built.** Confirming that needs `import natten` to read+ * `HAS_LIBNATTEN`, which costs a torch import; paying that per `/targets` request is+ * not worth it, so the deep check is left to render time, where+ * `isPixal3dNafError` classifies the failure into an actionable message. Reported as+ * `'unknown'` when the probe itself could not run — deliberately distinct from+ * `'unavailable'`, so a broken probe never renders a warning about a fine install+ * (CLAUDE.md sentinel rule: "failed to determine" ≠ "determined to be bad").+ *+ * @param {{execFileImpl?: Function, exists?: (p: string) => boolean,+ * env?: NodeJS.ProcessEnv}} [opts]+ * @returns {Promise<{naf: 'available'|'unavailable'|'unknown', missing: string[], help?: string}>}+ */+export async function probePixal3dModules({+ execFileImpl,+ exists = existsSync,+ env,+} = {}) {+ const modules = await probePythonModules({+ python: pixal3dPython({ exists, env }),+ modules: [...PIXAL3D_REQUIRED_MODULES, ...PIXAL3D_NAF_MODULES],+ execFileImpl,+ });+ if (!modules) return { naf: 'unknown', missing: [] };+ const nafPresent = PIXAL3D_NAF_MODULES.every((m) => modules[m]);+ return {+ naf: nafPresent ? 'available' : 'unavailable',+ missing: PIXAL3D_REQUIRED_MODULES.filter((m) => !modules[m]),+ ...(nafPresent ? {} : { help: PIXAL3D_NAF_FALLBACK_HELP }),+ };+}++/**+ * A NATTEN / NAF-upsampler failure. Distinct from a generic crash because it is+ * user-actionable: repair the install to rebuild NATTEN for this card.+ */+export const isPixal3dNafError = textMatcher([+ 'libnatten', 'HAS_LIBNATTEN', "No module named 'natten'", 'NATTEN was not compiled',+]);++const NAF_ERROR_HELP = 'This render failed inside Pixal3D\'s NAF upsampler, which needs '+ + 'NATTEN built with CUDA kernels for this GPU. Run Repair install to rebuild it.';++/**+ * The WSL2 NAF crash. Upstream issue #31 reports a reproducible+ * `CUDA driver error: device not ready` inside the NAF upsampler's encoder on WSL2,+ * on passes where `use_naf_upsample=True` — while the same NATTEN build works in+ * isolation. It is classified separately from a NATTEN *build* problem because the+ * remedy is different and Repair install will not help: PortOS points Windows users at+ * WSL2 for the TRELLIS.2 CUDA lane, and that advice does not carry over here.+ */+export const isPixal3dWslNafError = textMatcher(['CUDA driver error: device not ready']);++const WSL_NAF_HELP = 'The GPU driver reported "device not ready" inside Pixal3D\'s NAF '+ + 'upsampler. This is a known upstream failure under WSL2 (Pixal3D issue #31) that a '+ + 'reinstall does not fix — render on a native Linux host, or use the TRELLIS.2 (CUDA) '+ + 'target on this machine instead.';++const CUDA_OOM_HELP = 'The GPU ran out of memory during this render. Close other GPU '+ + 'workloads and try again, or render at a lower resolution — Pixal3D needs ~12 GB at '+ + '1024 and up to ~36 GB for full-quality 1536.';++/**+ * Run the install as a killable, event-emitting job: conda env → TRELLIS.2 clone ++ * `setup.sh` → Pixal3D clone → deps → NATTEN → utils3d (~40 GB and a long CUDA+ * extension build). Real subprocesses — user-triggered only. Retry/cancel/backoff+ * semantics come from the shared `runInstallSteps`.+ *+ * `computeCap` is resolved by the caller (the adapter, via+ * `detectCudaComputeCapability`) rather than probed here, keeping this function's+ * inputs explicit and its steps deterministic in tests.+ *+ * @param {{base?: string, onEvent?: (ev: object) => void, spawnImpl?: Function,+ * maxRetries?: number, sleep?: (ms: number) => Promise<void>,+ * exists?: (p: string) => boolean, env?: NodeJS.ProcessEnv,+ * computeCap?: string|null}} [opts]+ * @returns {{promise: Promise<{ok: true}>, kill: () => void}}+ */+export function installPixal3dCuda({+ base,+ onEvent = () => {},+ spawnImpl = spawn,+ maxRetries = 3,+ sleep,+ exists = existsSync,+ env,+ computeCap = null,+} = {}) {+ return runInstallSteps({+ steps: buildPixal3dInstallSteps(base, { exists, env, computeCap }),+ label: LABEL,+ codePrefix: CODE_PREFIX,+ isTransient: isTransientInstallError,+ onEvent,+ spawnImpl,+ maxRetries,+ sleep,+ env,+ // Steps can leave a usable env behind while a build failed, so confirm what+ // actually landed rather than trusting exit 0 (#2952's lesson).+ verify: (emit) => {+ if (!isPixal3dCudaInstalled({ base, exists, env })) {+ const err = new Error(+ `${LABEL} setup finished but its conda environment or the Pixal3D checkout 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: '✅ Pixal3D CUDA environment is present.' });+ },+ });+}++/**+ * Run a single image→GLB generation. Same contract as `runTrellis2CudaGenerate`: the one+ * real-subprocess boundary, GUARDED (rejects `PIXAL3D_CUDA_NOT_INSTALLED` unless the+ * environment is present, so it can never run from a cold boot), returning+ * `{ promise, kill }` so a caller can terminate the render mid-flight, and normalizing+ * the result to opaque so low-alpha prediction noise doesn't become visible holes.+ * `spawnImpl`/`exists` are injectable so the wiring is unit-testable without a render.+ *+ * Cancellation matters more here than on the TRELLIS.2 lanes: a full-quality Pixal3D+ * render is measured in minutes, not seconds.+ *+ * `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 resolution/offload+ * tier. Null/unknown degrades to the floor.+ *+ * `cwd` is the Pixal3D checkout, which is load-bearing rather than tidiness: upstream's+ * `inference.py` imports its own `pixal3d` package relative to the checkout and writes+ * its `flex_gemm` autotune cache next to the script.+ *+ * @param {{imagePath: string, outputPath?: string, base?: string, resolution?: number,+ * lowVram?: boolean, vramGb?: number|null,+ * steps?: number|null, seed?: 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 runPixal3dCudaGenerate({+ imagePath,+ outputPath,+ base,+ resolution,+ lowVram,+ vramGb = null,+ steps = null,+ seed = null,+ onProgress,+ spawnImpl = spawn,+ exists = existsSync,+ env,+ postprocessGlb = rewriteGlbMaterialsOpaque,+} = {}) {+ // Resolve the interpreter once and reuse it as the "is the env there?" answer.+ const python = pixal3dPython({ exists, env });+ if (!python || !exists(pixal3dInferenceScript(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 = selectPixal3dRenderBudget(vramGb);+ const { command, args } = buildPixal3dGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ resolution: resolution ?? budget.resolution,+ lowVram: lowVram ?? budget.lowVram,+ steps,+ seed,+ });+ return runGenerateSubprocess({+ command,+ args,+ cwd: pixal3dRepoDir(base),+ env,+ label: LABEL,+ codePrefix: CODE_PREFIX,+ parseProgress: parsePixal3dProgress,+ assetPath: outputPath || null,+ onProgress,+ spawnImpl,+ postprocessGlb,+ // Order matters: the WSL2 driver fault and a missing NATTEN build both surface from+ // the NAF stage but have different remedies, so the more specific one is tested+ // first and never collapses into "rebuild NATTEN" (which would not help).+ classifiers: [+ { test: isPixal3dWslNafError, code: `${CODE_PREFIX}_NAF_DEVICE_NOT_READY`, help: WSL_NAF_HELP },+ { test: isPixal3dNafError, code: `${CODE_PREFIX}_NAF_UNAVAILABLE`, help: NAF_ERROR_HELP },+ { test: isHfAuthError, code: `${CODE_PREFIX}_HF_AUTH_REQUIRED`, help: () => hfGatedRepoHelp('pixal3dCuda') },+ { test: isCudaOomError, code: `${CODE_PREFIX}_OUT_OF_MEMORY`, help: CUDA_OOM_HELP },+ ],+ });+}diff --git a/server/services/imageTo3d/pixal3dCuda.test.js b/server/services/imageTo3d/pixal3dCuda.test.jsnew file mode 100644index 0000000000..860e82f834--- /dev/null+++ b/server/services/imageTo3d/pixal3dCuda.test.js@@ -0,0 +1,450 @@+import { EventEmitter } from 'node:events';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import {+ PIXAL3D_REPO,+ PIXAL3D_CONDA_ENV,+ PIXAL3D_SETUP_FLAGS,+ PIXAL3D_NATTEN_VERSION,+ PIXAL3D_UTILS3D_WHEEL,+ PIXAL3D_RESOLUTIONS,+ PIXAL3D_STANDARD_MODE_MIN_VRAM_GB,+ PIXAL3D_HIGH_RES_MIN_VRAM_GB,+ PIXAL3D_NAF_FALLBACK_HELP,+ pixal3dRoot,+ pixal3dRepoDir,+ pixal3dTrellisDir,+ pixal3dInferenceScript,+ pixal3dPython,+ isPixal3dCudaInstalled,+ nattenWorkerCount,+ buildPixal3dInstallSteps,+ buildPixal3dGenerateArgs,+ selectPixal3dRenderBudget,+ parsePixal3dProgress,+ probePixal3dModules,+ isPixal3dNafError,+ isPixal3dWslNafError,+ runPixal3dCudaGenerate,+} from './pixal3dCuda.js';+import { trellis2CudaRoot } from './trellis2Cuda.js';++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++// Paths are composed with join() rather than 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, 'pixal3d');+const REPO = join(ROOT, 'Pixal3D');+const TRELLIS = join(ROOT, 'TRELLIS.2');+const INFERENCE = join(REPO, 'inference.py');+const CONDA = join('/opt', 'conda');+const CONDA_PY = join(CONDA, 'envs', 'pixal3d', 'bin', 'python');+const CONDA_ENV = { CONDA_ROOT: CONDA };++/** 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 + upstream's entrypoint on disk. */+const INSTALLED = existsFor(CONDA_PY, INFERENCE);++const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++const stageOf = (steps, stage) => steps.find((s) => s.stage === stage);++describe('pixal3dCuda path resolution', () => {+ it('roots its install apart from BOTH TRELLIS.2 lanes', () => {+ expect(pixal3dRoot(BASE)).toBe(ROOT);+ // The whole point of a separate env: nothing may share a clone with trellis2Cuda,+ // whose dependency set Pixal3D's pinned requirements would otherwise mutate.+ expect(pixal3dRoot(BASE)).not.toBe(trellis2CudaRoot(BASE));+ expect(pixal3dRoot(BASE)).not.toBe(join(BASE, 'trellis2'));+ });++ it('keeps its own TRELLIS.2 checkout inside its own root', () => {+ expect(pixal3dTrellisDir(BASE)).toBe(TRELLIS);+ expect(pixal3dTrellisDir(BASE).startsWith(ROOT)).toBe(true);+ });++ // The candidate-list shape and the CONDA_PREFIX walk-up are covered once, with the+ // shared resolver (`server/lib/pythonSetup.test.js`). What matters here is that this+ // lane asks for its OWN env — resolving to `trellis2` would hand Pixal3D an+ // interpreter whose dependency set it must not touch.+ it('resolves its own conda env, never the TRELLIS.2 one', () => {+ expect(pixal3dPython({ exists: existsFor(CONDA_PY), env: CONDA_ENV })).toBe(CONDA_PY);+ expect(CONDA_PY).toContain(join('envs', PIXAL3D_CONDA_ENV));+ expect(PIXAL3D_CONDA_ENV).not.toBe('trellis2');+ // A host with ONLY the trellis2 env present must read as not-installed here.+ expect(pixal3dPython({+ exists: existsFor(join(CONDA, 'envs', 'trellis2', 'bin', 'python')), env: CONDA_ENV,+ })).toBeNull();+ expect(pixal3dPython({ exists: () => false, env: CONDA_ENV })).toBeNull();+ });+});++describe('isPixal3dCudaInstalled', () => {+ it('requires BOTH the env python and upstream entrypoint', () => {+ expect(isPixal3dCudaInstalled({ base: BASE, exists: INSTALLED, env: CONDA_ENV })).toBe(true);+ // Env created but the clone/build never landed — must not read as installed.+ expect(isPixal3dCudaInstalled({ base: BASE, exists: existsFor(CONDA_PY), env: CONDA_ENV })).toBe(false);+ // Clone present but no env.+ expect(isPixal3dCudaInstalled({ base: BASE, exists: existsFor(INFERENCE), env: CONDA_ENV })).toBe(false);+ });+});++describe('buildPixal3dInstallSteps', () => {+ const fresh = () => buildPixal3dInstallSteps(BASE, { exists: () => false, computeCap: '8.6' });++ it('creates its own conda env rather than relying on setup.sh --new-env', () => {+ const env = stageOf(fresh(), 'env');+ expect(env.command).toBe('conda');+ expect(env.args).toEqual(['create', '-n', 'pixal3d', 'python=3.10', '-y']);+ });++ it('sources setup.sh WITHOUT --new-env, inside the activated pixal3d env', () => {+ const setup = stageOf(fresh(), 'setup');+ expect(setup.cwd).toBe(TRELLIS);+ const script = setup.args[1];+ // `--new-env` would hard-code `conda create -n trellis2` and install into the+ // wrong env — the single most important property of this step.+ expect(script).not.toContain('--new-env');+ expect(script).toContain('conda activate pixal3d');+ expect(script).toContain('. ./setup.sh');+ for (const flag of PIXAL3D_SETUP_FLAGS) expect(script).toContain(flag);+ });++ it('clones TRELLIS.2 recursively and Pixal3D at its default branch', () => {+ const steps = fresh();+ const trellisClone = stageOf(steps, 'clone-trellis');+ // TRELLIS.2 vendors its CUDA extensions as submodules.+ expect(trellisClone.args).toContain('--recursive');+ expect(trellisClone.args).toContain(TRELLIS);++ const clone = stageOf(steps, 'clone');+ expect(clone.args).toEqual(['clone', PIXAL3D_REPO, REPO]);+ // Upstream's README names a `main` branch that does not exist on the remote;+ // pinning it would make the clone fail outright.+ expect(clone.args).not.toContain('-b');+ expect(clone.args).not.toContain('main');+ });++ it('builds NATTEN for the probed arch and tolerates its failure', () => {+ const natten = stageOf(fresh(), 'natten');+ expect(natten.args[1]).toContain('NATTEN_CUDA_ARCH=8.6');+ expect(natten.args[1]).toContain(`NATTEN_N_WORKERS=${nattenWorkerCount()}`);+ expect(natten.args[1]).toContain(`natten==${PIXAL3D_NATTEN_VERSION}`);+ expect(natten.args[1]).toContain('--no-build-isolation');+ // Without NATTEN the pipeline takes upstream's NAF fallback path — degraded, but+ // it renders. Failing a ~40 GB install over it would be the worse outcome.+ expect(natten.optional).toBe(true);+ });++ it('omits NATTEN_CUDA_ARCH entirely when the arch could not be determined', () => {+ const steps = buildPixal3dInstallSteps(BASE, { exists: () => false, computeCap: null });+ const natten = stageOf(steps, 'natten');+ // Never guess an arch — let NATTEN pick its own default (sentinel rule).+ expect(natten.args[1]).not.toContain('NATTEN_CUDA_ARCH');+ expect(natten.args[1]).toContain('NATTEN_N_WORKERS=');+ });++ it('installs the pinned utils3d wheel', () => {+ expect(stageOf(fresh(), 'utils3d').args[1]).toContain(PIXAL3D_UTILS3D_WHEEL);+ });++ it('is resumable — skips the env and clones that already exist', () => {+ const steps = buildPixal3dInstallSteps(BASE, {+ exists: existsFor(CONDA_PY, join(TRELLIS, '.git'), join(REPO, '.git')),+ computeCap: '8.6',+ });+ expect(stageOf(steps, 'env')).toBeUndefined();+ expect(stageOf(steps, 'clone-trellis')).toBeUndefined();+ expect(stageOf(steps, 'clone')).toBeUndefined();+ // The idempotent build steps must still run — that is the point of resuming.+ expect(stageOf(steps, 'setup')).toBeDefined();+ expect(stageOf(steps, 'deps')).toBeDefined();+ expect(stageOf(steps, 'utils3d')).toBeDefined();+ });+});++describe('nattenWorkerCount', () => {+ it('uses half the cores, bounded, and never returns zero', () => {+ expect(nattenWorkerCount(16)).toBe(8);+ expect(nattenWorkerCount(64)).toBe(8); // capped+ expect(nattenWorkerCount(2)).toBe(1);+ expect(nattenWorkerCount(1)).toBe(1); // floor(0.5) === 0 must not escape+ expect(nattenWorkerCount(0)).toBeGreaterThan(0);+ expect(nattenWorkerCount(NaN)).toBeGreaterThan(0);+ });+});++describe('selectPixal3dRenderBudget', () => {+ it('gives a big card standard mode at full resolution', () => {+ expect(selectPixal3dRenderBudget(PIXAL3D_STANDARD_MODE_MIN_VRAM_GB)).toEqual({ lowVram: false, resolution: 1536 });+ expect(selectPixal3dRenderBudget(80)).toEqual({ lowVram: false, resolution: 1536 });+ });++ it('gives a mid card full resolution WITH offload', () => {+ expect(selectPixal3dRenderBudget(PIXAL3D_HIGH_RES_MIN_VRAM_GB)).toEqual({ lowVram: true, resolution: 1536 });+ expect(selectPixal3dRenderBudget(35)).toEqual({ lowVram: true, resolution: 1536 });+ });++ it('drops a small card to the 1024 floor', () => {+ expect(selectPixal3dRenderBudget(12)).toEqual({ lowVram: true, resolution: 1024 });+ expect(selectPixal3dRenderBudget(23)).toEqual({ lowVram: true, resolution: 1024 });+ });++ it('degrades an unknown card to the floor rather than overcommitting it', () => {+ // A card we failed to size must never be handed the 36 GB lane (sentinel rule).+ for (const unknown of [null, undefined, NaN, 'lots']) {+ expect(selectPixal3dRenderBudget(unknown)).toEqual({ lowVram: true, resolution: 1024 });+ }+ });+});++describe('buildPixal3dGenerateArgs', () => {+ const args = (over = {}) => buildPixal3dGenerateArgs({+ imagePath: '/img/src.png', base: BASE, python: CONDA_PY, ...over,+ }).args;++ it('targets upstream inference.py with the image as a FLAG', () => {+ const built = buildPixal3dGenerateArgs({ imagePath: '/img/src.png', base: BASE, python: CONDA_PY });+ expect(built.command).toBe(CONDA_PY);+ expect(built.args[0]).toBe(INFERENCE);+ expect(built.args).toContain('--image');+ expect(built.args[built.args.indexOf('--image') + 1]).toBe('/img/src.png');+ });++ it('passes outputPath THROUGH as a full .glb path, never reduced to a stem', () => {+ const out = join('/data', 'image-to-3d', 'abc', 'model.glb');+ const built = args({ outputPath: out });+ // inference.py writes exactly the path it is given; handing it a stem would+ // silently produce an extension-less file.+ expect(built[built.indexOf('--output') + 1]).toBe(out);+ });++ it('emits --low_vram only when the tier asks for it', () => {+ expect(args({ lowVram: true })).toContain('--low_vram');+ expect(args({ lowVram: false })).not.toContain('--low_vram');+ });++ it('emits the resolution and rejects one upstream does not accept', () => {+ expect(args({ resolution: 1536 })).toEqual(expect.arrayContaining(['--resolution', '1536']));+ expect(() => args({ resolution: 2048 })).toThrow(/resolution must be one of/);+ });++ it('requires an image', () => {+ expect(() => buildPixal3dGenerateArgs({ base: BASE })).toThrow(/imagePath is required/);+ });++ it('emits --seed but drops --steps, while still validating both', () => {+ expect(args({ seed: 7 })).toEqual(expect.arrayContaining(['--seed', '7']));+ // inference.py has no per-phase step override; an unrecognized flag would make+ // argparse abort a job we already queued.+ expect(args({ steps: 12 })).not.toContain('--steps');+ // Validation still happens at the same boundary as the other lanes.+ expect(() => args({ steps: 9999 })).toThrow(/steps must be an integer/);+ expect(() => args({ seed: -1 })).toThrow(/seed must be an integer/);+ });++});++describe('parsePixal3dProgress', () => {+ it('maps upstream banners to monotonically increasing percents', () => {+ const seq = [+ '[Pipeline] Loading from TencentARC/Pixal3D...',+ '[ImageCond] Building DinoV3ProjFeatureExtractor models...',+ '[NAF] Pre-loading NAF upsampler model...',+ '[Pipeline] Low-VRAM mode enabled.',+ '[Inference] Processing image: /img/src.png',+ '[MoGe-2] Loading model for camera estimation...',+ '[Inference] Estimating camera parameters...',+ '[Inference] Running 3D generation pipeline...',+ '[Inference] Using pipeline_type=1536_cascade',+ '[Inference] Extracting GLB...',+ ].map((l) => parsePixal3dProgress(l));+ expect(seq.every(Boolean)).toBe(true);+ const percents = seq.map((f) => f.percent);+ expect(percents).toEqual([...percents].sort((a, b) => a - b));+ });++ it('treats the saved .glb line as the terminal export frame', () => {+ const out = join('/data', 'image-to-3d', 'abc', 'model.glb');+ const frame = parsePixal3dProgress(`[Done] GLB saved to: ${out}`);+ expect(frame.stage).toBe('export');+ expect(frame.assetPath).toBe(out);+ });++ it('does NOT mistake "Extracting GLB" for a written .glb path', () => {+ // Regression guard: the export matcher looks for `<something>.glb`, and this line+ // must land on the texturing banner instead of resolving the render early.+ const frame = parsePixal3dProgress('[Inference] Extracting GLB...');+ expect(frame.stage).toBe('texturing');+ expect(frame.assetPath).toBeUndefined();+ });++ it('scales a bare tqdm percentage into the shared sampling band', () => {+ const frame = parsePixal3dProgress(' 50%|##### | 6/12');+ expect(frame.stage).toBe('generating');+ // Band is [10,50]; a per-phase bar at 50% must not fill the whole render.+ expect(frame.percent).toBeGreaterThanOrEqual(10);+ expect(frame.percent).toBeLessThanOrEqual(50);+ });++ it('returns null for noise', () => {+ expect(parsePixal3dProgress('')).toBeNull();+ expect(parsePixal3dProgress(' ')).toBeNull();+ expect(parsePixal3dProgress('some unrelated chatter')).toBeNull();+ });+});++describe('probePixal3dModules', () => {+ const okProbe = (payload) => (_py, _args, _opts, cb) => cb(null, JSON.stringify(payload));++ it('reports NAF available when natten resolves', async () => {+ const res = await probePixal3dModules({+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ execFileImpl: okProbe({ o_voxel: true, flex_gemm: true, natten: true }),+ });+ expect(res.naf).toBe('available');+ expect(res.missing).toEqual([]);+ expect(res.help).toBeUndefined();+ // The raw find_spec map is deliberately NOT returned — nothing consumed it, and it+ // reached the client as `target.modules.modules`.+ expect(res.modules).toBeUndefined();+ });++ it('reports NAF unavailable with actionable help when natten is absent', async () => {+ const res = await probePixal3dModules({+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ execFileImpl: okProbe({ o_voxel: true, flex_gemm: true, natten: false }),+ });+ expect(res.naf).toBe('unavailable');+ expect(res.help).toBe(PIXAL3D_NAF_FALLBACK_HELP);+ });++ it('separates a broken install from a degraded one', async () => {+ const res = await probePixal3dModules({+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ execFileImpl: okProbe({ o_voxel: false, flex_gemm: true, natten: true }),+ });+ expect(res.missing).toEqual(['o_voxel']);+ });++ it('says unknown — never "unavailable" — when the probe itself fails', async () => {+ // "Failed to determine" must not render as "determined to be bad".+ const failed = await probePixal3dModules({+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ execFileImpl: (_py, _args, _opts, cb) => cb(new Error('boom')),+ });+ expect(failed.naf).toBe('unknown');++ const garbage = await probePixal3dModules({+ base: BASE,+ exists: INSTALLED,+ env: CONDA_ENV,+ execFileImpl: (_py, _args, _opts, cb) => cb(null, 'not json'),+ });+ expect(garbage.naf).toBe('unknown');++ const noEnv = await probePixal3dModules({ base: BASE, exists: () => false, env: CONDA_ENV });+ expect(noEnv.naf).toBe('unknown');+ });+});++describe('pixal3d error classifiers', () => {+ it('recognizes a NATTEN/NAF build problem', () => {+ expect(isPixal3dNafError("ModuleNotFoundError: No module named 'natten'")).toBe(true);+ expect(isPixal3dNafError('AttributeError: natten.HAS_LIBNATTEN')).toBe(true);+ expect(isPixal3dNafError('some other crash')).toBe(false);+ });++ it('recognizes the WSL2 NAF driver fault distinctly from a build problem', () => {+ const wsl = 'RuntimeError: CUDA driver error: device not ready';+ expect(isPixal3dWslNafError(wsl)).toBe(true);+ // Must NOT also match the NATTEN classifier, or the user gets told to rebuild+ // NATTEN for a fault a rebuild cannot fix (upstream #31).+ expect(isPixal3dNafError(wsl)).toBe(false);+ });+});++describe('runPixal3dCudaGenerate', () => {+ it('refuses to run when the environment is absent (no cold-bootstrap)', async () => {+ const { promise } = runPixal3dCudaGenerate({+ imagePath: '/img/src.png', base: BASE, exists: () => false, env: CONDA_ENV,+ });+ await expect(promise).rejects.toMatchObject({ code: 'PIXAL3D_CUDA_NOT_INSTALLED' });+ });++ it('refuses when the env exists but upstream entrypoint does not', async () => {+ const { promise } = runPixal3dCudaGenerate({+ imagePath: '/img/src.png', base: BASE, exists: existsFor(CONDA_PY), env: CONDA_ENV,+ });+ await expect(promise).rejects.toMatchObject({ code: 'PIXAL3D_CUDA_NOT_INSTALLED' });+ });++ it('spawns inference.py from the Pixal3D checkout with the VRAM-selected tier', async () => {+ const child = makeChild();+ const spawnImpl = vi.fn(() => child);+ const { promise } = runPixal3dCudaGenerate({+ imagePath: '/img/src.png',+ outputPath: join('/data', 'model.glb'),+ base: BASE,+ vramGb: 48,+ exists: INSTALLED,+ env: CONDA_ENV,+ spawnImpl,+ postprocessGlb: () => {},+ });+ await flush();+ const [command, args, opts] = spawnImpl.mock.calls[0];+ expect(command).toBe(CONDA_PY);+ expect(args[0]).toBe(INFERENCE);+ // A 48 GB card gets standard mode at 1536.+ expect(args).toEqual(expect.arrayContaining(['--resolution', '1536']));+ expect(args).not.toContain('--low_vram');+ // cwd is load-bearing: inference.py imports its own package relative to the+ // checkout and writes its flex_gemm autotune cache beside the script.+ expect(opts.cwd).toBe(REPO);++ child.stdout.emit('data', Buffer.from(`[Done] GLB saved to: ${join('/data', 'model.glb')}\n`));+ child.emit('close', 0);+ await expect(promise).resolves.toMatchObject({ assetPath: join('/data', 'model.glb') });+ });++ it('drops an unsized card to the low-VRAM floor', async () => {+ const child = makeChild();+ const spawnImpl = vi.fn(() => child);+ runPixal3dCudaGenerate({+ imagePath: '/img/src.png', base: BASE, vramGb: null,+ exists: INSTALLED, env: CONDA_ENV, spawnImpl, postprocessGlb: () => {},+ });+ await flush();+ const args = spawnImpl.mock.calls[0][1];+ expect(args).toEqual(expect.arrayContaining(['--resolution', '1024']));+ expect(args).toContain('--low_vram');+ });++ it('is killable mid-render', async () => {+ const child = makeChild();+ const { kill } = runPixal3dCudaGenerate({+ imagePath: '/img/src.png', base: BASE, exists: INSTALLED, env: CONDA_ENV,+ spawnImpl: () => child, postprocessGlb: () => {},+ });+ await flush();+ kill();+ expect(child.kill).toHaveBeenCalled();+ });+});diff --git a/server/services/imageTo3d/registry.test.js b/server/services/imageTo3d/registry.test.jsnew file mode 100644index 0000000000..f55a988670--- /dev/null+++ b/server/services/imageTo3d/registry.test.js@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import { IMAGE_TO_3D_TARGETS, IMAGE_TO_3D_TARGET_IDS, EXECUTION_LANES, OUTPUT_KINDS } from './targets.js';+import { TARGET_ADAPTERS } from './adapters.js';++// Registry-wide invariants, asserted by LOOPING over the registry rather than by a+// hand-written block per target. The per-target blocks in targets.test.js only cover+// the targets someone remembered to write them for, so a newly registered target+// inherits no checks at all — which is how a descriptor can reach production missing a+// field that only fails at generate time (a 501 from models.js), never in CI.+describe('image-to-3D registry invariants', () => {+ it('registers an adapter for exactly the declared targets', () => {+ // A descriptor with no adapter resolves, renders a card, accepts a generate+ // request, and only then 501s in models.js — so this pairing must fail in CI.+ expect(Object.keys(TARGET_ADAPTERS).sort()).toEqual([...IMAGE_TO_3D_TARGET_IDS].sort());+ });++ for (const id of IMAGE_TO_3D_TARGET_IDS) {+ describe(id, () => {+ const target = IMAGE_TO_3D_TARGETS[id];+ const adapter = TARGET_ADAPTERS[id];++ it('carries the descriptor fields every consumer reads', () => {+ expect(target.id).toBe(id);+ expect(target.label).toBeTruthy();+ expect(target.description).toBeTruthy();+ expect(EXECUTION_LANES).toContain(target.executionLane);+ expect(OUTPUT_KINDS).toContain(target.outputKind);+ expect(Object.isFrozen(target)).toBe(true);+ });++ it('satisfies the adapter contract', () => {+ expect(typeof adapter.isInstalled).toBe('function');+ expect(typeof adapter.run).toBe('function');+ for (const optional of ['install', 'resolveEnv', 'describeInstallState']) {+ if (adapter[optional] !== undefined) expect(typeof adapter[optional]).toBe('function');+ }+ });++ it('supplies install copy when it has an install step', () => {+ // The install modal is shared by every target and has no per-target copy of its+ // own, so a target with an installer MUST bring its own prose or the modal+ // silently falls back to a generic description.+ if (adapter.install) expect(typeof target.installNotes).toBe('string');+ });++ it('declares only boolean render-option support, when it declares any', () => {+ if (target.supportsRenderOptions === undefined) return;+ for (const [knob, supported] of Object.entries(target.supportsRenderOptions)) {+ expect(['steps', 'seed', 'keyBackground']).toContain(knob);+ expect(typeof supported).toBe('boolean');+ }+ });++ it('states a hardware floor matching its execution lane', () => {+ const req = target.requires || {};+ if (target.executionLane === 'local-mps') expect(req.appleSilicon).toBe(true);+ if (target.executionLane === 'local-cuda') {+ expect(req.cuda).toBe(true);+ expect(req.minVramGb).toBeGreaterThan(0);+ }+ });+ });+ }+});diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.jsindex f35407df4f..4b1fce9766 100644--- a/server/services/imageTo3d/renderOptions.js+++ b/server/services/imageTo3d/renderOptions.js@@ -69,14 +69,48 @@ export function normalizeRenderOptions(input = {}) {* @returns {string[]}*/export function renderOptionArgs(label, { steps = null, seed = null } = {}) {+ validateRenderOptions(label, { steps, seed });+ return [+ ...(seed !== null ? ['--seed', String(seed)] : []),+ ...(steps !== null ? ['--steps', String(steps)] : []),+ ];+}++/**+ * The bounds half of `renderOptionArgs`, for a lane that must validate an option it+ * cannot emit. Pixal3D is the case: upstream's `inference.py` has no per-phase step+ * override, so its builder has to reject an out-of-range `steps` at the same boundary+ * as the other lanes while emitting no `--steps` flag. Calling `renderOptionArgs` and+ * discarding the result would work, but it reads like a dropped return value AND+ * tempts the caller into re-spelling `--seed` locally — which is exactly the flag-name+ * drift this module exists to prevent. Throws with the caller's label.+ * @param {string} label+ * @param {{steps?: number|null, seed?: number|null}} [opts]+ */+export function validateRenderOptions(label, { steps = null, seed = null } = {}) {if (steps !== null && !isValidRenderSteps(steps)) {throw new Error(`${label}: steps must be an integer in [${RENDER_STEPS_MIN}, ${RENDER_STEPS_MAX}]`);}if (seed !== null && !isValidRenderSeed(seed)) {throw new Error(`${label}: seed must be an integer in [0, ${RENDER_SEED_MAX}]`);}- return [- ...(seed !== null ? ['--seed', String(seed)] : []),- ...(steps !== null ? ['--steps', String(steps)] : []),- ];+}++/**+ * Drop the options a target's runner will not honor, so the persisted run entry+ * records what the subprocess ACTUALLY received rather than what the user asked for.+ *+ * This module's contract is that a run entry holds "the concrete values the subprocess+ * received (the truthful, reproducible record)" — a target whose runner silently drops+ * an option would otherwise break that invariant and log a quality setting that never+ * applied. `support` is the target descriptor's `supportsRenderOptions`; absent means+ * everything is honored, so existing targets need no entry.+ *+ * @param {{steps: number|null, seed: number|null, keyBackground: boolean}} options+ * @param {{steps?: boolean}} [support]+ * @returns {{steps: number|null, seed: number|null, keyBackground: boolean}}+ */+export function honorTargetRenderSupport(options, support) {+ if (!support) return options;+ return { ...options, ...(support.steps === false ? { steps: null } : {}) };}diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.jsindex e8634dd432..90b54a0f48 100644--- a/server/services/imageTo3d/renderOptions.test.js+++ b/server/services/imageTo3d/renderOptions.test.js@@ -8,6 +8,8 @@ import {normalizeRenderOptions,randomRenderSeed,renderOptionArgs,+ validateRenderOptions,+ honorTargetRenderSupport,} from './renderOptions.js';describe('normalizeRenderOptions', () => {@@ -67,3 +69,43 @@ describe('validators', () => {expect(isValidRenderSeed(RENDER_SEED_MAX + 1)).toBe(false);});});++describe('validateRenderOptions', () => {+ it('enforces the same bounds as renderOptionArgs without emitting flags', () => {+ expect(() => validateRenderOptions('x', { steps: 0 })).toThrow(/steps must be an integer/);+ expect(() => validateRenderOptions('x', { steps: 65 })).toThrow(/steps must be an integer/);+ expect(() => validateRenderOptions('x', { seed: -1 })).toThrow(/seed must be an integer/);+ expect(() => validateRenderOptions('x', { seed: 2147483648 })).toThrow(/seed must be an integer/);+ expect(validateRenderOptions('x', { steps: 12, seed: 7 })).toBeUndefined();+ expect(validateRenderOptions('x')).toBeUndefined();+ });++ it('names the caller in the error, so a lane-specific builder reads as the thrower', () => {+ expect(() => validateRenderOptions('buildPixal3dGenerateArgs', { steps: 999 }))+ .toThrow(/^buildPixal3dGenerateArgs:/);+ });+});++describe('honorTargetRenderSupport', () => {+ const opts = { steps: 24, seed: 7, keyBackground: true };++ it('passes everything through for a target that declares no limits', () => {+ // Absent support must mean "honors everything", so existing targets need no entry.+ expect(honorTargetRenderSupport(opts, undefined)).toBe(opts);+ expect(honorTargetRenderSupport(opts, null)).toBe(opts);+ });++ it('nulls only the unsupported knob, leaving the rest intact', () => {+ expect(honorTargetRenderSupport(opts, { steps: false }))+ .toEqual({ steps: null, seed: 7, keyBackground: true });+ });++ it('leaves a knob alone when support is explicitly true', () => {+ expect(honorTargetRenderSupport(opts, { steps: true })).toEqual(opts);+ });++ it('does not mutate its input', () => {+ honorTargetRenderSupport(opts, { steps: false });+ expect(opts.steps).toBe(24);+ });+});diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.jsindex ddc98675db..7308b18bc0 100644--- a/server/services/imageTo3d/targets.js+++ b/server/services/imageTo3d/targets.js@@ -49,6 +49,19 @@ export const OUTPUT_KINDS = Object.freeze(Object.values(OUTPUT_KIND));* `requires` states the hardware floor for the target's declared lane; the pure* resolvers below read it. A target's installer/runner is wired in `adapters.js`,* keyed by this registry's `id` (not imported here — see the file header).+ *+ * Beyond `id`/`label`/`description`/`executionLane`/`outputKind`/`requires`, a+ * descriptor carries:+ * - `installNotes` — prose for the shared install modal. **Required for a target with+ * an install step**, because that modal is shared by every target and has no+ * per-target copy of its own; `registry.test.js` enforces it.+ * - `gatedRepos` — Hugging Face repos whose terms the user must accept. Omit when the+ * target pulls only ungated weights; the auth-failure help reads it.+ * - `supportsRenderOptions` — per-run knobs the target's runner does NOT honor, e.g.+ * `{ steps: false }`. Absent means all of them are honored. This is what stops the+ * UI offering a control that does nothing and stops the run ledger recording a+ * value the subprocess never received.+ * - `upstream` / `port` / `weightsRepo` — links surfaced on the target card.*/export const IMAGE_TO_3D_TARGETS = Object.freeze({trellis2: Object.freeze({@@ -71,6 +84,14 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({// Community MPS port that makes the CUDA-only upstream run on Apple Silicon.port: 'https://github.com/shivampkumar/trellis-mac',weightsRepo: 'microsoft/TRELLIS.2-4B',+ // Fresh-install copy for the shared install modal. Lives on the descriptor, not+ // in the page, so registering a target does not mean editing UI prose — the page+ // would otherwise show TRELLIS.2's text for every target.+ installNotes:+ 'Cloning the TRELLIS.2 (Apple Silicon) port and installing its Python '+ + 'environment (~15 GB on first run). Missing build dependencies (the Xcode '+ + "Metal Toolchain, the mesh baker's Eigen submodule) are fetched first, so "+ + 'textures bake at full quality.',// Optional user-actionable prerequisites. The target descriptor is the source// for both the API/UI notice and runner auth guidance, so new targets do not// need their gated Hugging Face dependencies duplicated in either consumer.@@ -108,6 +129,11 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({}),upstream: 'https://github.com/microsoft/TRELLIS.2',weightsRepo: 'microsoft/TRELLIS.2-4B',+ installNotes:+ 'Cloning microsoft/TRELLIS.2 with its CUDA extension submodules and running '+ + 'upstream setup.sh, which builds flash-attn, nvdiffrast, nvdiffrec and cumesh '+ + 'from source into a new `trellis2` conda environment (~15 GB, and the compile '+ + 'takes a while).',// 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.@@ -118,6 +144,47 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({}),]),}),+ pixal3dCuda: Object.freeze({+ id: 'pixal3dCuda',+ label: 'Pixal3D (CUDA)',+ description:+ 'TencentARC Pixal3D — pixel-aligned single image to a PBR-textured GLB mesh, run '+ + 'on-device on an NVIDIA GPU. Built on the TRELLIS.2 backbone, with higher '+ + 'geometry fidelity at a longer render time.',+ executionLane: EXECUTION_LANE.LOCAL_CUDA,+ outputKind: OUTPUT_KIND.GLB_MESH,+ // The floor is DELIBERATELY lower than the TRELLIS.2 CUDA lane's 24 GB, not an+ // oversight: upstream's merged low-VRAM mode loads one pipeline stage onto the GPU+ // at a time, bringing peak to ~10-12 GB at 1024 (Pixal3D issue #12). Full-quality 1536+ // wants up to ~36 GB, but that is a QUALITY tier the runner selects from the card's+ // actual VRAM (`selectPixal3dRenderBudget`) — not an availability gate, because a+ // 12 GB card still produces a real mesh. `diskGb` covers ~24 GB of Pixal3D weights+ // plus its own TRELLIS.2 checkout and conda env.+ requires: Object.freeze({+ cuda: true,+ minVramGb: 12,+ linuxHost: true,+ diskGb: 40,+ python: '3.10',+ }),+ upstream: 'https://github.com/TencentARC/Pixal3D',+ weightsRepo: 'TencentARC/Pixal3D',+ // Upstream's `inference.py` has no per-phase step override, so its runner validates+ // `steps` and drops it. Declared here so the UI disables the Quality control rather+ // than offering a setting that silently does nothing, and so the run entry records+ // `steps: null` instead of a value that never applied.+ supportsRenderOptions: Object.freeze({ steps: false }),+ installNotes:+ 'Creating a dedicated `pixal3d` conda environment (kept separate so Pixal3D\u2019s '+ + 'pinned dependencies cannot disturb the TRELLIS.2 target), cloning both repos, '+ + 'building the CUDA extensions and NATTEN for this GPU, then fetching ~24 GB of '+ + 'weights. Budget ~40 GB of disk and a long first build.',+ // No `gatedRepos`, and that is verified rather than assumed: `inference.py` loads+ // DINOv3 from the ungated `camenduru/dinov3-vitl16-pretrain-lvd1689m` mirror and+ // MoGe from `Ruicheng/moge-2-vitl`, so unlike `trellis2Cuda` nothing here needs+ // terms accepted. A Hugging Face token still helps with download rate limits,+ // which is why the adapter still resolves one.+ }),});/** Registry keys, for Zod enums and iteration. */@@ -176,6 +243,18 @@ export function unavailableReason(target, caps = {}) {return null;}+/**+ * Which per-run render options a target's runner does NOT honor, or null when it honors+ * all of them. Pure. Read by the record route so a detail view (which loads a record,+ * not the target list) can disable a control the runner would silently ignore, and by+ * `beginRender` so the run ledger records what the subprocess actually received.+ * @param {string} targetId+ * @returns {object|null}+ */+export function renderOptionSupportFor(targetId) {+ return getTarget(targetId)?.supportsRenderOptions || null;+}+/*** Is this target runnable on a host with the given capabilities? Pure.* @param {string|object} target@@ -198,10 +277,13 @@ export function isTargetAvailable(target, caps = {}) {* adding a code without a label fails CI instead of rendering as the generic* "Unsupported on this host" fallback.*- * The GB figures restate the registry floors (`minUnifiedMemoryGb` /- * `minVramGb`, both 24) as prose rather than interpolating them: the labels are- * mirrored to the client, which has no registry to read, and both lanes would- * have to move for the numbers to diverge.+ * These labels are mirrored to the client, which has no registry to read, so they are+ * prose rather than interpolated values. **Only mention a GB figure when every target+ * that can produce the code shares it.** `insufficient-memory` names 24 GB because one+ * MPS target produces it; `insufficient-vram` names none, because the CUDA lanes'+ * floors have diverged (24 GB for TRELLIS.2, 12 GB for Pixal3D) and a single number+ * would be wrong for one of them. The per-target figure travels to the client on the+ * descriptor (`requires.minVramGb`) for any UI that wants to name it.*/export const UNAVAILABLE_REASONS = Object.freeze({'unknown-target': 'Unavailable',@@ -211,8 +293,17 @@ export const UNAVAILABLE_REASONS = Object.freeze({// 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.+ // Caveat this label cannot express (it is per-CODE, not per-target): WSL2 gets the+ // TRELLIS.2 lane running, but Pixal3D has a known NAF-upsampler driver fault there+ // (Pixal3D issue #31). That one surfaces at render time via+ // `PIXAL3D_CUDA_NAF_DEVICE_NOT_READY`, whose help text names native Linux.'requires-linux-host': 'Requires a Linux host (use WSL2 on Windows)',- 'insufficient-vram': 'Needs a 24 GB+ NVIDIA GPU',+ // Deliberately carries NO GB figure. It used to read "Needs a 24 GB+ NVIDIA GPU"+ // when every CUDA target shared that floor; `pixal3dCuda` runs from 12 GB, so a+ // single number here would be wrong for one lane or the other. The per-target+ // requirement travels to the client on the descriptor (`requires.minVramGb`) for a+ // UI that wants to name it.+ 'insufficient-vram': 'This NVIDIA GPU has too little VRAM',// The probe itself failed — say so rather than claiming the GPU isn't there.'cuda-probe-failed': 'Could not detect this host’s GPU',});diff --git a/server/services/imageTo3d/targets.test.js b/server/services/imageTo3d/targets.test.jsindex 040b670b4f..b51b46f0d4 100644--- a/server/services/imageTo3d/targets.test.js+++ b/server/services/imageTo3d/targets.test.js@@ -11,6 +11,7 @@ import {resolveTarget,listTargets,detectHostCapabilities,+ renderOptionSupportFor,} from './targets.js';// A host that can run TRELLIS.2's local-MPS lane, and one that can't.@@ -175,8 +176,25 @@ describe('listTargets', () => {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']);+ // Silicon chip than a Mac is to grow a GPU, so neither gets a dead card. Asserted+ // as "no MPS target" rather than an exact list, so registering another CUDA target+ // doesn't churn this test — the property under test is the hiding, not the roster.+ const ids = listTargets(CUDA_BOX).map((t) => t.id);+ expect(ids).not.toContain('trellis2');+ expect(ids).toContain('trellis2Cuda');+ });++ it('lists the CUDA targets independently, per their diverged VRAM floors', () => {+ // The two CUDA lanes no longer share a floor: TRELLIS.2 needs 24 GB, while+ // Pixal3D's low-VRAM mode renders from 12. A 16 GB card must therefore see+ // exactly one of them — the whole reason `insufficient-vram` stopped naming a+ // single GB figure.+ const small = listTargets({ ...CUDA_BOX, cudaVramGb: 16 }).map((t) => t.id);+ expect(small).toContain('pixal3dCuda');+ expect(small).not.toContain('trellis2Cuda');++ const big = listTargets({ ...CUDA_BOX, cudaVramGb: 48 }).map((t) => t.id);+ expect(big).toEqual(expect.arrayContaining(['trellis2Cuda', 'pixal3dCuda']));});it('still SHOWS a target when the blocker is one the user can fix', () => {@@ -308,3 +326,20 @@ describe('detectHostCapabilities', () => {expect(caps.cudaVramGb).toBeNull();});});++describe('renderOptionSupportFor', () => {+ it('reports the unsupported knobs a target declares', () => {+ // Pixal3D's runner drops `steps`; the descriptor is what tells the UI to disable+ // the control and `beginRender` to record null instead of the requested value.+ expect(renderOptionSupportFor('pixal3dCuda')).toEqual({ steps: false });+ });++ it('returns null for a target that honors every knob, and for an unknown id', () => {+ // Absent must mean "all supported", so existing targets need no descriptor entry+ // and an unknown id can't be mistaken for "supports nothing".+ expect(renderOptionSupportFor('trellis2')).toBeNull();+ expect(renderOptionSupportFor('trellis2Cuda')).toBeNull();+ expect(renderOptionSupportFor('nope')).toBeNull();+ expect(renderOptionSupportFor(undefined)).toBeNull();+ });+});diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex 18dc424da3..e893952700 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -25,7 +25,12 @@ import { fileURLToPath } from 'node:url';import { spawn, execFile } from '../../lib/childProcess.js';import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import { getTarget } from './targets.js';-import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';+import {+ textMatcher,+ runInstallSteps,+ runGenerateSubprocess,+ probePythonModules,+} from './laneRunner.js';import { renderOptionArgs } from './renderOptions.js';const HOME = homedir();@@ -125,10 +130,6 @@ export const TRELLIS2_FALLBACK_BAKE_HELP = 'TRELLIS.2 is installed, but its Meta+ 'install fetches the missing build dependencies and rebuilds the Metal backends — '+ 'your downloaded models are kept.';-/** The shell probe that reports which bake modules resolve inside the venv. */-const BAKE_PROBE_SOURCE = 'import importlib.util as u,json,sys;'- + 'print(json.dumps({m: u.find_spec(m) is not None for m in sys.argv[1:]}))';-/*** Probe whether the venv can take `generate.py`'s Metal texture-baking path.*@@ -156,16 +157,17 @@ export async function probeTrellis2TextureBake({if (!exists(python)) {return { quality: 'unknown', modules: {}, missing: [], degradedQuality: [] };}- const probed = [...TRELLIS2_METAL_BAKE_MODULES, ...TRELLIS2_BAKE_QUALITY_MODULES];- // Subprocess boundary outside the request lifecycle — a probe failure must degrade- // to 'unknown', never reject into the route (CLAUDE.md child-process exception).- const modules = await new Promise((resolve) => {- execFileImpl(python, ['-c', BAKE_PROBE_SOURCE, ...probed], { timeout: 15000 }, (err, stdout) => {- if (err) return resolve(null);- const parsed = JSON.parse(String(stdout || '').trim() || 'null');- resolve(parsed && typeof parsed === 'object' ? parsed : null);- });- }).catch(() => null);+ // Shared spawn + parse (`probePythonModules`). Was an inline copy whose `JSON.parse`+ // ran INSIDE the execFile callback, where a throw escapes the enclosing promise —+ // the `.catch()` fires on a later tick and cannot see it — and reaches the event+ // loop, killing the process. Any non-JSON on stdout from a healthy venv (a+ // `sitecustomize`/`.pth` print, a conda activation hook) turned a `/3d` page load+ // into a server restart. The shared helper parses after the callback resolves.+ const modules = await probePythonModules({+ python,+ modules: [...TRELLIS2_METAL_BAKE_MODULES, ...TRELLIS2_BAKE_QUALITY_MODULES],+ execFileImpl,+ });if (!modules) return { quality: 'unknown', modules: {}, missing: [], degradedQuality: [] };@@ -714,11 +716,20 @@ export const isHfAuthError = textMatcher([* @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 '+ const target = getTarget(targetId);+ const name = target?.label || 'This model';+ const repos = target?.gatedRepos ?? [];+ // A target with NO gated repos still reaches here on an auth failure — but telling+ // that user to "accept the terms" for an unnamed model is advice they cannot act on.+ // For those targets the realistic cause is an unauthenticated rate limit, so say so.+ if (!repos.length) {+ return `${name} could not download a model from Hugging Face. It has no gated `+ + 'dependencies, so this is most likely an unauthenticated rate limit — add your '+ + 'Hugging Face token on the 3D page (or set HF_TOKEN / run `huggingface-cli login`) '+ + 'and try again.';+ }+ const repoHelp = repos.map(({ label, url }) => `${label} at ${url}`).join(' and ');+ return `${name} 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.';diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex e31601ae69..86d486dd5a 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -34,6 +34,7 @@ import {TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB,selectTrellis2PipelineType,selectTrellis2TextureSize,+ hfGatedRepoHelp,} from './trellis2.js';import { getTarget } from './targets.js';@@ -1045,3 +1046,33 @@ describe('installTrellis2', () => {expect(i).toBe(1); // the second step never spawned});});++describe('hfGatedRepoHelp', () => {+ it('names the target whose auth failed, not always TRELLIS.2', () => {+ // It takes a target id, so it must not hardcode one product's name: a Pixal3D+ // auth failure previously read "TRELLIS.2 could not download…".+ expect(hfGatedRepoHelp('trellis2')).toContain('TRELLIS.2');+ expect(hfGatedRepoHelp('pixal3dCuda')).toContain('Pixal3D (CUDA)');+ expect(hfGatedRepoHelp('pixal3dCuda')).not.toContain('TRELLIS.2');+ });++ it('lists the gated repos to accept when the target has them', () => {+ const help = hfGatedRepoHelp('trellis2');+ expect(help).toContain('facebook/dinov3-vitl16-pretrain-lvd1689m');+ expect(help).toContain('briaai/RMBG-2.0');+ expect(help).toContain('Accept the terms');+ });++ it('gives rate-limit advice — not "accept the terms" — for a target with no gated repos', () => {+ // Pixal3D loads DINOv3 from an ungated mirror, so there are no terms to accept;+ // telling the user to accept terms for an unnamed model is advice they cannot act on.+ const help = hfGatedRepoHelp('pixal3dCuda');+ expect(help).toContain('rate limit');+ expect(help).not.toContain('Accept the terms');+ expect(help).toContain('HF_TOKEN');+ });++ it('degrades to a generic name for an unknown target id', () => {+ expect(hfGatedRepoHelp('nope')).toContain('This model');+ });+});diff --git a/server/services/imageTo3d/trellis2Cuda.js b/server/services/imageTo3d/trellis2Cuda.jsindex cbc51164a6..eacb7d8528 100644--- a/server/services/imageTo3d/trellis2Cuda.js+++ b/server/services/imageTo3d/trellis2Cuda.js@@ -17,8 +17,10 @@* 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.+ * for `envs/trellis2/bin/python` instead of a fixed path under the repo — via the+ * shared `resolveCondaEnvPython` (`lib/condaEnv.js`), which the Pixal3D CUDA+ * lane uses too. (Distinct from that file's venv resolvers like+ * `resolveFlux2Python`, which probe a different layout entirely.)** 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@@ -37,6 +39,7 @@ import { homedir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { spawn } from '../../lib/childProcess.js';+import { resolveCondaEnvPython } from '../../lib/condaEnv.js';import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import {hfGatedRepoHelp,@@ -71,44 +74,15 @@ function trellis2CudaPackageDir(base) {}/**- * 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.+ * The conda Python upstream's `setup.sh --new-env` built, or null when its env doesn't+ * exist. A one-line wrapper over the shared resolver (`lib/condaEnv.js`), which owns+ * the conda-root candidate list and the `CONDA_PREFIX` walk-up both CUDA lanes need.* `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;+ return resolveCondaEnvPython(TRELLIS2_CUDA_CONDA_ENV, { exists, env });}/** PortOS's own generate entrypoint (upstream ships only a hard-coded `example.py`). */diff --git a/server/services/imageTo3d/trellis2Cuda.test.js b/server/services/imageTo3d/trellis2Cuda.test.jsindex 68222b8734..dbdd8adb1e 100644--- a/server/services/imageTo3d/trellis2Cuda.test.js+++ b/server/services/imageTo3d/trellis2Cuda.test.js@@ -13,7 +13,6 @@ import {TRELLIS2_CUDA_HIGH_QUALITY_MIN_VRAM_GB,trellis2CudaRoot,trellis2CudaPython,- trellis2CudaPythonCandidates,trellis2CudaGenerateRunnerScript,isTrellis2CudaInstalled,buildCudaInstallSteps,@@ -54,18 +53,12 @@ describe('trellis2Cuda path resolution', () => {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);+ // The candidate-list shape and the CONDA_PREFIX walk-up now live with the shared+ // resolver (`lib/pythonSetup.test.js`); what matters here is that this lane asks for+ // its OWN env name.+ it('resolves the env setup.sh --new-env creates', () => {+ expect(trellis2CudaPython({ exists: existsFor(CONDA_PY), env: CONDA_ENV })).toBe(CONDA_PY);+ expect(CONDA_PY).toContain(join('envs', TRELLIS2_CUDA_CONDA_ENV));});it('returns the first existing candidate, or null when none is present', () => {