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 Apple Silicon image-to-3D target
[._.]/ Adam Eivybf945867fb86
diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.jsindex 5484422530..aec9359f96 100644--- a/server/services/imageTo3d/adapters.js+++ b/server/services/imageTo3d/adapters.js@@ -82,6 +82,13 @@ import {probePixal3dModules,PIXAL3D_INCOMPLETE_INSTALL_HELP,} from './pixal3dCuda.js';+import {+ isPixal3dMpsInstalled,+ installPixal3dMps,+ runPixal3dMpsGenerate,+ describePixal3dMpsInstallState,+ probeMetalToolchain as probePixal3dMpsToolchain,+} from './pixal3dMps.js';import { describeDegradedInstall } from './degradedInstall.js';import { detectCudaComputeCapability } from '../../lib/cudaCapability.js';@@ -142,6 +149,25 @@ export const TARGET_ADAPTERS = Object.freeze({};},}),+ pixal3dMps: Object.freeze({+ isInstalled: isPixal3dMpsInstalled,+ // The Apple port downloads public Hugging Face artifacts, but a configured token+ // avoids anonymous rate limits during its first explicit render.+ resolveEnv: hfChildEnv,+ async install({ onEvent = () => {}, env } = {}) {+ // The fork's setup script refuses to start unless `xcrun metal` is available.+ // Reuse the existing toolchain preflight so a full-Xcode host can fetch the+ // optional component before the native packages compile, while a Command-Line-+ // Tools-only host receives the same actionable Xcode guidance as TRELLIS.2.+ const toolchain = await probePixal3dMpsToolchain();+ if (toolchain.blocker) onEvent({ type: 'log', stage: 'preflight', message: `⚠️ ${toolchain.hint}` });+ const installMetalToolchain = toolchain.available === false && toolchain.installable === true;+ if (installMetalToolchain) onEvent({ type: 'log', stage: 'preflight', message: `ℹ️ ${toolchain.hint}` });+ return installPixal3dMps({ onEvent, env, installMetalToolchain });+ },+ run: runPixal3dMpsGenerate,+ describeInstallState: describePixal3dMpsInstallState,+ }),trellis2Cuda: Object.freeze({isInstalled: isTrellis2CudaInstalled,// Upstream's 4B pipeline conditions on the gated DINOv3 repo, so this lane needsdiff --git a/server/services/imageTo3d/pixal3dMps.js b/server/services/imageTo3d/pixal3dMps.jsnew file mode 100644index 0000000000..416a9b0496--- /dev/null+++ b/server/services/imageTo3d/pixal3dMps.js@@ -0,0 +1,412 @@+/**+ * Pixal3D (local Apple Silicon / MPS) target — install detection, pure command+ * builders, progress parsing, and a guarded generate runner.+ *+ * The official TencentARC/Pixal3D entrypoint is CUDA-only. This lane uses the+ * complete community Apple Silicon port, which replaces Pixal3D's CUDA extension+ * stack with vendored Metal packages and ships `generate_mps.py` as its own CLI.+ * It is deliberately isolated from both the TRELLIS.2 MPS environment and the+ * Pixal3D CUDA environment: the fork pins Python/dependency versions and compiles+ * native extensions into its own `.venv`.+ *+ * The subprocess machinery is shared through `laneRunner.js`. No install or render+ * starts at module load; both are reached only from explicit user actions.+ */++import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { execFile, spawn } from '../../lib/childProcess.js';+import { appendMissingModules, describeDegradedInstall } from './degradedInstall.js';+import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';+import {+ hfGatedRepoHelp,+ isHfAuthError,+ isTransientInstallError,+ parseGenerateProgress,+} from './trellis2.js';+import {+ TRELLIS2_METAL_TOOLCHAIN_STEP,+ probeMetalToolchain,+} from './trellis2.js';+import {+ probePythonModules, runGenerateSubprocess, runInstallSteps, textMatcher,+} from './laneRunner.js';+import { renderOptionArgs, validateRenderOptions } from './renderOptions.js';++const HOME = homedir();+const CODE_PREFIX = 'PIXAL3D_MPS';+const LABEL = 'Pixal3D (Apple Silicon)';++/** The complete Apple Silicon / Metal port used by this target. */+export const PIXAL3D_MPS_REPO = 'https://github.com/pawel-mazurkiewicz/Pixal3D-mac.git';++/** Python version required by the port's pinned Mac dependency set. */+export const PIXAL3D_MPS_PYTHON_VERSION = '3.10';++/** Torch versions the fork pins; bootstrapped before pip resolves natten. */+export const PIXAL3D_MPS_TORCH_VERSION = '2.12.0';+export const PIXAL3D_MPS_TORCHVISION_VERSION = '0.27.0';+export const PIXAL3D_MPS_NATTEN_VERSION = '0.21.0';++/** Clone/install root. `base` is overridable so the entire lane is unit-testable. */+export function pixal3dMpsRoot(base = join(HOME, '.portos')) {+ return join(base, 'pixal3d-mps');+}++/** The port's private virtual-environment interpreter. */+export function pixal3dMpsVenvPython(base) {+ return join(pixal3dMpsRoot(base), '.venv', 'bin', 'python');+}++/** The port's Apple-native inference entrypoint. */+export function pixal3dMpsGenerateScript(base) {+ return join(pixal3dMpsRoot(base), 'generate_mps.py');+}++/** Installed ⇔ the private venv and the port's entrypoint both exist. */+export function isPixal3dMpsInstalled({ base, exists = existsSync } = {}) {+ return exists(pixal3dMpsVenvPython(base)) && exists(pixal3dMpsGenerateScript(base));+}++/**+ * The MPS port's two supported pipeline types. PortOS starts at 1024: the fork's+ * 1536 cascade can take up to roughly an hour on a high-memory Mac, so exposing it+ * as an automatic default would turn a normal Generate click into an unexpectedly+ * long job. A future target-specific detail control can opt into 1536 explicitly.+ */+export const PIXAL3D_MPS_PIPELINE_TYPES = Object.freeze(['1024_cascade', '1536_cascade']);+export const PIXAL3D_MPS_DEFAULT_PIPELINE_TYPE = PIXAL3D_MPS_PIPELINE_TYPES[0];++/** Native packages the port's setup smoke check imports for the full Metal path. */+export const PIXAL3D_MPS_REQUIRED_MODULES = Object.freeze([+ 'torch', 'moge', 'cumesh', 'flex_gemm', 'mtlbvh', 'mtldiffrast', 'o_voxel',+ 'natten', 'natten_mps',+]);++/** Remedy text for a venv that exists but did not finish its native installs. */+export const PIXAL3D_MPS_INCOMPLETE_INSTALL_HELP = 'Pixal3D is installed but its '+ + 'Apple-native Python or Metal packages are incomplete. Repair install reruns the '+ + 'pinned setup and rebuilds the native packages; downloaded models are kept.';++/**+ * The fork's requirements list contains `natten`, whose build metadata imports torch.+ * Pip resolves all requirements before installing them, so a one-shot requirements+ * install fails on a fresh venv: the isolated natten build cannot see torch yet. Create+ * the venv and install the torch pair first, then install natten without build+ * isolation; the fork's setup script can subsequently resolve the remaining pins.+ */+export function buildPixal3dMpsBootstrapScript() {+ return [+ 'set -euo pipefail',+ 'PY="${PYTHON_BIN:-}"',+ 'if [[ -z "$PY" ]]; then',+ ' for cand in /opt/homebrew/opt/[email protected]/bin/python3.10 "$(command -v python3.10 2>/dev/null || true)"; do',+ ' if [[ -n "$cand" && -x "$cand" ]]; then PY="$cand"; break; fi',+ ' done',+ 'fi',+ '[[ -n "$PY" && -x "$PY" ]] || { echo "Python 3.10 not found; install [email protected] or set PYTHON_BIN." >&2; exit 1; }',+ 'if [[ ! -x .venv/bin/python ]]; then "$PY" -m venv .venv; fi',+ 'VPY=.venv/bin/python',+ `"$VPY" -m pip install "torch==${PIXAL3D_MPS_TORCH_VERSION}" "torchvision==${PIXAL3D_MPS_TORCHVISION_VERSION}"`,+ `"$VPY" -m pip install --no-build-isolation "natten==${PIXAL3D_MPS_NATTEN_VERSION}"`,+ ].join('\n');+}++/**+ * Build the idempotent install plan for the Apple port.+ *+ * The upstream fork owns its setup script because it pins the Python dependency graph+ * and compiles six vendored Metal packages. Keeping that script intact is safer than+ * re-spelling its package order here. The optional toolchain step is placed before it,+ * because `setup_mac.sh` checks for `xcrun metal` before starting any build.+ *+ * @param {string} [base]+ * @param {{exists?: (path: string) => boolean, installMetalToolchain?: boolean}} [opts]+ * @returns {Array<{stage: string, command: string, args: string[], cwd?: string, optional?: boolean}>}+ */+export function buildPixal3dMpsInstallSteps(+ base,+ { exists = existsSync, installMetalToolchain = false } = {},+) {+ const root = pixal3dMpsRoot(base);+ const steps = [];+ if (installMetalToolchain) {+ steps.push({+ ...TRELLIS2_METAL_TOOLCHAIN_STEP,+ args: [...TRELLIS2_METAL_TOOLCHAIN_STEP.args],+ });+ }+ if (!exists(join(root, '.git'))) {+ steps.push({+ stage: 'clone',+ command: 'git',+ args: ['clone', '--depth', '1', PIXAL3D_MPS_REPO, root],+ });+ }+ steps.push({+ stage: 'bootstrap',+ command: 'bash',+ args: ['-c', buildPixal3dMpsBootstrapScript()],+ cwd: root,+ });+ steps.push({+ stage: 'setup',+ command: 'bash',+ args: ['scripts/setup_mac.sh'],+ cwd: root,+ });+ return steps;+}++/**+ * Probe the installed venv without importing torch or allocating Metal buffers.+ * `unknown: true` is distinct from an observed missing module so a failed probe does+ * not falsely label a possibly healthy install as broken.+ */+export async function probePixal3dMpsModules({+ base,+ exists = existsSync,+ execFileImpl = execFile,+} = {}) {+ const python = pixal3dMpsVenvPython(base);+ if (!exists(python)) return { unknown: true, missing: [] };+ const modules = await probePythonModules({+ python,+ modules: [...PIXAL3D_MPS_REQUIRED_MODULES],+ execFileImpl,+ });+ if (!modules) return { unknown: true, missing: [] };+ return {+ unknown: false,+ missing: PIXAL3D_MPS_REQUIRED_MODULES.filter((module) => !modules[module]),+ };+}++/**+ * Install the fork as a killable, event-emitting job. The setup script does not pull+ * model weights, so installation is expensive but does not cold-start inference; the+ * first explicit render downloads the Hugging Face models.+ */+export function installPixal3dMps({+ base,+ onEvent = () => {},+ spawnImpl = spawn,+ maxRetries = 3,+ sleep,+ exists = existsSync,+ env,+ installMetalToolchain = false,+ probeModules = probePixal3dMpsModules,+} = {}) {+ // The setup script's requirements command must inherit no-build-isolation as well:+ // if a future pin makes natten look unsatisfied, it should reuse the bootstrapped+ // torch rather than re-enter the same fresh-venv failure.+ const installEnv = {+ ...(env ?? process.env),+ PIP_NO_BUILD_ISOLATION: '1',+ };+ return runInstallSteps({+ steps: buildPixal3dMpsInstallSteps(base, { exists, installMetalToolchain }),+ label: LABEL,+ codePrefix: CODE_PREFIX,+ isTransient: isTransientInstallError,+ onEvent,+ spawnImpl,+ maxRetries,+ sleep,+ env: installEnv,+ verify: async (emit) => {+ if (!isPixal3dMpsInstalled({ base, exists })) {+ const error = new Error(+ `${LABEL} setup finished but its Python environment or generate_mps.py is missing.`,+ );+ error.code = `${CODE_PREFIX}_INSTALL_INCOMPLETE`;+ error.stage = 'verify';+ throw error;+ }+ const probe = await probeModules({ base, exists });+ if (probe.missing?.length) {+ emit({+ type: 'log',+ stage: 'verify',+ message: `⚠️ ${appendMissingModules(PIXAL3D_MPS_INCOMPLETE_INSTALL_HELP, probe.missing)}`,+ });+ } else if (!probe.unknown) {+ emit({ type: 'log', stage: 'verify', message: '✅ Pixal3D Apple Silicon environment is present.' });+ }+ },+ });+}++/**+ * Build the Apple-port CLI invocation. The fork accepts a full output path and+ * exposes the shared seed/steps controls directly, unlike the CUDA-only entrypoint.+ */+export function buildPixal3dMpsGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ pipelineType = PIXAL3D_MPS_DEFAULT_PIPELINE_TYPE,+ steps = null,+ seed = null,+} = {}) {+ if (!imagePath) throw new Error('buildPixal3dMpsGenerateArgs: imagePath is required');+ if (!PIXAL3D_MPS_PIPELINE_TYPES.includes(pipelineType)) {+ throw new Error(+ `buildPixal3dMpsGenerateArgs: pipelineType must be one of ${PIXAL3D_MPS_PIPELINE_TYPES.join(', ')}`,+ );+ }+ validateRenderOptions('buildPixal3dMpsGenerateArgs', { steps, seed });+ const args = [+ pixal3dMpsGenerateScript(base),+ imagePath,+ '--device', 'mps',+ '--pipeline-type', pipelineType,+ ];+ if (outputPath) args.push('--output', outputPath);+ args.push(...renderOptionArgs('buildPixal3dMpsGenerateArgs', { steps, seed }));+ return { command: python || pixal3dMpsVenvPython(base) || 'python3', args };+}++/** Apple-port stage banners, mapped into PortOS's shared progress vocabulary. */+const PIXAL3D_MPS_STAGE_SIGNATURES = [+ { re: /^\[Pipeline\] Loading/i, stage: 'loading', percent: 2 },+ { re: /^\[ImageCond\]/i, stage: 'loading', percent: 3 },+ { re: /^\[NAF\]/i, stage: 'loading', percent: 4 },+ { re: /^\[MoGe\]/i, stage: 'loading', percent: 7 },+ { re: /^\[Generate\]/i, stage: 'generating', percent: 10 },+ { re: /^\[Mesh\]/i, stage: 'meshing', percent: 55 },+ { re: /^\[Export\]/i, stage: 'texturing', percent: 65 },+ { re: /^\[Timing\]/i, stage: 'texturing', percent: 72 },+];++/** Parse one line of `generate_mps.py` output, or return null when it carries no signal. */+export function parsePixal3dMpsProgress(line) {+ const shared = parseGenerateProgress(line);+ if (shared) return shared;+ const text = String(line ?? '').trim();+ if (!text) return null;+ for (const signature of PIXAL3D_MPS_STAGE_SIGNATURES) {+ if (signature.re.test(text)) {+ return {+ stage: signature.stage,+ percent: signature.percent,+ message: text,+ };+ }+ }+ return null;+}++/** Apple Metal watchdog / empty-mesh failure signatures from the port's own help. */+export const isPixal3dMpsWatchdogError = textMatcher([+ 'decoder produced an empty mesh',+ 'macOS GPU watchdog',+ 'kIOGPUCommandBufferCallbackErrorImpactingInteractivity',+ 'BVH needs at least 8 triangles',+]);++export const PIXAL3D_MPS_WATCHDOG_HELP = 'The macOS GPU watchdog stopped this Pixal3D '+ + 'render during a long Metal dispatch. Nothing is wrong with the install. Put the '+ + 'display to sleep, close display-heavy apps, or retry at a lower pipeline tier.';++export const isPixal3dMpsOutOfMemoryError = textMatcher([+ 'MPS backend out of memory',+ 'MPSAllocator',+ 'out of memory',+ 'not enough memory',+]);++export const PIXAL3D_MPS_OUT_OF_MEMORY_HELP = 'Pixal3D ran out of Apple unified memory '+ + 'during this render. Close other GPU-heavy apps and retry; use the 1024 cascade '+ + 'rather than the 1536 cascade if you are running it directly.';++/**+ * Run one Apple-native image→GLB generation. This is guarded on the private venv and+ * entrypoint so a fresh boot cannot silently install or invoke the model.+ */+export function runPixal3dMpsGenerate({+ imagePath,+ outputPath,+ base,+ pipelineType,+ steps = null,+ seed = null,+ onProgress,+ spawnImpl = spawn,+ exists = existsSync,+ env,+ postprocessGlb = rewriteGlbMaterialsOpaque,+} = {}) {+ const python = pixal3dMpsVenvPython(base);+ if (!exists(python) || !exists(pixal3dMpsGenerateScript(base))) {+ const error = new Error(`${LABEL} is not installed — install it before generating.`);+ error.code = `${CODE_PREFIX}_NOT_INSTALLED`;+ return { promise: Promise.reject(error), kill: () => {} };+ }+ const { command, args } = buildPixal3dMpsGenerateArgs({+ imagePath,+ outputPath,+ base,+ python,+ pipelineType,+ steps,+ seed,+ });+ // `generate_mps.py` uses tqdm and plain prints; without this flag a pipe buffers+ // the first several minutes of progress, leaving the shared render card looking+ // idle while MPS is actively sampling.+ const renderEnv = {+ ...(env ?? process.env),+ PYTHONUNBUFFERED: '1',+ };+ return runGenerateSubprocess({+ command,+ args,+ cwd: pixal3dMpsRoot(base),+ env: renderEnv,+ label: LABEL,+ codePrefix: CODE_PREFIX,+ parseProgress: parsePixal3dMpsProgress,+ assetPath: outputPath || null,+ onProgress,+ spawnImpl,+ postprocessGlb,+ classifiers: [+ { test: isPixal3dMpsWatchdogError, code: `${CODE_PREFIX}_MPS_WATCHDOG`, help: PIXAL3D_MPS_WATCHDOG_HELP },+ { test: isHfAuthError, code: `${CODE_PREFIX}_HF_AUTH_REQUIRED`, help: () => hfGatedRepoHelp('pixal3dMps') },+ { test: isPixal3dMpsOutOfMemoryError, code: `${CODE_PREFIX}_OUT_OF_MEMORY`, help: PIXAL3D_MPS_OUT_OF_MEMORY_HELP },+ ],+ });+}++/**+ * Resolve the card's extra install diagnostics for the generic target card.+ * Kept as a helper for the adapter and direct tests; it never imports the native+ * packages itself.+ */+export async function describePixal3dMpsInstallState({+ base,+ exists = existsSync,+ execFileImpl = execFile,+} = {}) {+ const probe = await probePixal3dMpsModules({ base, exists, execFileImpl });+ const projection = probe.missing?.length+ ? describeDegradedInstall({+ label: 'incomplete install',+ help: PIXAL3D_MPS_INCOMPLETE_INSTALL_HELP,+ missing: probe.missing,+ })+ : null;+ return {+ fields: {+ ...(projection ? { degraded: projection.degraded } : {}),+ },+ warnings: projection?.warnings ?? [],+ };+}++/** Exported for the adapter's async preflight. */+export { probeMetalToolchain };diff --git a/server/services/imageTo3d/pixal3dMps.test.js b/server/services/imageTo3d/pixal3dMps.test.jsnew file mode 100644index 0000000000..d4fc99e231--- /dev/null+++ b/server/services/imageTo3d/pixal3dMps.test.js@@ -0,0 +1,222 @@+import { EventEmitter } from 'node:events';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import {+ PIXAL3D_MPS_DEFAULT_PIPELINE_TYPE,+ PIXAL3D_MPS_NATTEN_VERSION,+ PIXAL3D_MPS_PIPELINE_TYPES,+ PIXAL3D_MPS_REPO,+ PIXAL3D_MPS_REQUIRED_MODULES,+ PIXAL3D_MPS_TORCH_VERSION,+ PIXAL3D_MPS_TORCHVISION_VERSION,+ buildPixal3dMpsGenerateArgs,+ buildPixal3dMpsBootstrapScript,+ buildPixal3dMpsInstallSteps,+ isPixal3dMpsInstalled,+ isPixal3dMpsOutOfMemoryError,+ isPixal3dMpsWatchdogError,+ parsePixal3dMpsProgress,+ pixal3dMpsGenerateScript,+ pixal3dMpsRoot,+ pixal3dMpsVenvPython,+ probePixal3dMpsModules,+ runPixal3dMpsGenerate,+} from './pixal3dMps.js';++const BASE = join('/tmp', 'portos-test-home');+const ROOT = join(BASE, 'pixal3d-mps');+const VENV = join(ROOT, '.venv', 'bin', 'python');+const SCRIPT = join(ROOT, 'generate_mps.py');+const existsFor = (...paths) => (path) => paths.includes(path);++const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++describe('pixal3dMps path and install plan', () => {+ it('keeps the Apple port isolated from the other image-to-3D lanes', () => {+ expect(pixal3dMpsRoot(BASE)).toBe(ROOT);+ expect(pixal3dMpsVenvPython(BASE)).toBe(VENV);+ expect(pixal3dMpsGenerateScript(BASE)).toBe(SCRIPT);+ });++ it('requires both the private venv and generate_mps.py', () => {+ expect(isPixal3dMpsInstalled({ base: BASE, exists: existsFor(VENV, SCRIPT) })).toBe(true);+ expect(isPixal3dMpsInstalled({ base: BASE, exists: existsFor(VENV) })).toBe(false);+ expect(isPixal3dMpsInstalled({ base: BASE, exists: existsFor(SCRIPT) })).toBe(false);+ });++ it('clones the MPS fork and delegates dependency/native builds to setup_mac.sh', () => {+ const steps = buildPixal3dMpsInstallSteps(BASE, { exists: () => false });+ expect(steps[0]).toEqual({+ stage: 'clone',+ command: 'git',+ args: ['clone', '--depth', '1', PIXAL3D_MPS_REPO, ROOT],+ });+ expect(steps[1]).toMatchObject({ stage: 'bootstrap', command: 'bash', cwd: ROOT });+ expect(steps[1].args[0]).toBe('-c');+ expect(steps[1].args[1]).toContain(`torch==${PIXAL3D_MPS_TORCH_VERSION}`);+ expect(steps[1].args[1]).toContain(`torchvision==${PIXAL3D_MPS_TORCHVISION_VERSION}`);+ expect(steps[1].args[1]).toContain(`natten==${PIXAL3D_MPS_NATTEN_VERSION}`);+ expect(steps[2]).toEqual({+ stage: 'setup',+ command: 'bash',+ args: ['scripts/setup_mac.sh'],+ cwd: ROOT,+ });+ expect(buildPixal3dMpsBootstrapScript()).toContain('set -euo pipefail');+ });++ it('puts the optional Metal toolchain fetch before setup', () => {+ const steps = buildPixal3dMpsInstallSteps(BASE, {+ exists: () => false,+ installMetalToolchain: true,+ });+ expect(steps[0]).toMatchObject({+ stage: 'metal-toolchain',+ command: 'xcodebuild',+ args: ['-downloadComponent', 'MetalToolchain'],+ optional: true,+ });+ expect(steps[1].stage).toBe('clone');+ expect(steps[2].stage).toBe('bootstrap');+ expect(steps[3].stage).toBe('setup');+ });++ it('resumes a cloned checkout without issuing a second clone', () => {+ const steps = buildPixal3dMpsInstallSteps(BASE, {+ exists: existsFor(join(ROOT, '.git')),+ });+ expect(steps.map((step) => step.stage)).toEqual(['bootstrap', 'setup']);+ });+});++describe('pixal3dMps command builder', () => {+ it('emits the fork CLI contract and shared seed/steps flags', () => {+ const built = buildPixal3dMpsGenerateArgs({+ imagePath: '/tmp/source.png',+ outputPath: '/tmp/model.glb',+ base: BASE,+ python: VENV,+ pipelineType: '1536_cascade',+ steps: 24,+ seed: 7,+ });+ expect(built).toEqual({+ command: VENV,+ args: [+ SCRIPT,+ '/tmp/source.png',+ '--device', 'mps',+ '--pipeline-type', '1536_cascade',+ '--output', '/tmp/model.glb',+ '--seed', '7',+ '--steps', '24',+ ],+ });+ });++ it('defaults to the safe 1024 cascade and validates the pipeline enum', () => {+ expect(PIXAL3D_MPS_PIPELINE_TYPES).toEqual(['1024_cascade', '1536_cascade']);+ expect(PIXAL3D_MPS_DEFAULT_PIPELINE_TYPE).toBe('1024_cascade');+ expect(buildPixal3dMpsGenerateArgs({ imagePath: '/tmp/source.png', base: BASE }).args)+ .toContain('1024_cascade');+ expect(() => buildPixal3dMpsGenerateArgs({+ imagePath: '/tmp/source.png', base: BASE, pipelineType: '512',+ })).toThrow(/pipelineType must be one of/);+ expect(() => buildPixal3dMpsGenerateArgs({+ imagePath: '/tmp/source.png', base: BASE, steps: 65,+ })).toThrow(/steps must be an integer/);+ });+});++describe('pixal3dMps module probe', () => {+ it('reports missing native packages without importing them', async () => {+ const execFileImpl = vi.fn((_python, _args, _options, callback) => {+ callback(null, JSON.stringify({+ ...Object.fromEntries(PIXAL3D_MPS_REQUIRED_MODULES.map((module) => [module, true])),+ o_voxel: false,+ }));+ });+ const result = await probePixal3dMpsModules({+ base: BASE,+ exists: existsFor(VENV),+ execFileImpl,+ });+ expect(result).toEqual({ unknown: false, missing: ['o_voxel'] });+ expect(execFileImpl).toHaveBeenCalledOnce();+ });++ it('keeps a failed probe distinct from a missing package', async () => {+ const execFileImpl = vi.fn((_python, _args, _options, callback) => callback(new Error('probe failed')));+ await expect(probePixal3dMpsModules({+ base: BASE,+ exists: existsFor(VENV),+ execFileImpl,+ })).resolves.toEqual({ unknown: true, missing: [] });+ });+});++describe('pixal3dMps progress and error classification', () => {+ it('maps the fork banners and preserves the shared GLB terminal signal', () => {+ expect(parsePixal3dMpsProgress('[Pipeline] Loading from TencentARC/Pixal3D...'))+ .toMatchObject({ stage: 'loading', percent: 2 });+ expect(parsePixal3dMpsProgress('[Generate] pipeline=1024_cascade, seed=7'))+ .toMatchObject({ stage: 'generating', percent: 10 });+ expect(parsePixal3dMpsProgress('[Done] GLB saved to /tmp/model.glb'))+ .toMatchObject({ stage: 'export', percent: 92, assetPath: '/tmp/model.glb' });+ });++ it('recognizes the fork-specific watchdog and memory failures', () => {+ expect(isPixal3dMpsWatchdogError('ERROR: The decoder produced an empty mesh')).toBe(true);+ expect(isPixal3dMpsOutOfMemoryError('MPS backend out of memory')).toBe(true);+ expect(isPixal3dMpsWatchdogError('ordinary Python failure')).toBe(false);+ });+});++describe('runPixal3dMpsGenerate', () => {+ it('refuses to spawn when the isolated runtime is absent', async () => {+ const spawnImpl = vi.fn();+ const result = runPixal3dMpsGenerate({+ base: BASE,+ imagePath: '/tmp/source.png',+ outputPath: '/tmp/model.glb',+ exists: () => false,+ spawnImpl,+ });+ await expect(result.promise).rejects.toMatchObject({ code: 'PIXAL3D_MPS_NOT_INSTALLED' });+ expect(spawnImpl).not.toHaveBeenCalled();+ });++ it('spawns from the fork checkout and resolves the produced GLB', async () => {+ const child = makeChild();+ const spawnImpl = vi.fn(() => child);+ const postprocessGlb = vi.fn();+ const result = runPixal3dMpsGenerate({+ base: BASE,+ imagePath: '/tmp/source.png',+ outputPath: '/tmp/model.glb',+ steps: 12,+ seed: 42,+ exists: existsFor(VENV, SCRIPT),+ spawnImpl,+ postprocessGlb,+ });+ expect(spawnImpl).toHaveBeenCalledWith(+ VENV,+ expect.arrayContaining(['--device', 'mps', '--pipeline-type', '1024_cascade']),+ expect.objectContaining({+ cwd: ROOT,+ env: expect.objectContaining({ PYTHONUNBUFFERED: '1' }),+ }),+ );+ child.stdout.emit('data', '[Done] GLB saved to /tmp/model.glb\n');+ child.emit('close', 0);+ await expect(result.promise).resolves.toEqual({ assetPath: '/tmp/model.glb' });+ expect(postprocessGlb).toHaveBeenCalledWith('/tmp/model.glb');+ });+});diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.jsindex 5259cb4bba..93a4a88997 100644--- a/server/services/imageTo3d/targets.js+++ b/server/services/imageTo3d/targets.js@@ -119,6 +119,41 @@ export const IMAGE_TO_3D_TARGETS = Object.freeze({}),]),}),+ pixal3dMps: Object.freeze({+ id: 'pixal3dMps',+ label: 'Pixal3D (Apple Silicon)',+ description:+ 'TencentARC Pixal3D — pixel-aligned single image to a textured GLB mesh, run '+ + 'locally through the community Apple Silicon MPS/Metal port.',+ executionLane: EXECUTION_LANE.LOCAL_MPS,+ outputKind: OUTPUT_KIND.GLB_MESH,+ // The Mac port is designed for Apple Silicon and uses the same conservative+ // 24 GB floor as the existing TRELLIS.2 MPS lane. Its 1024 cascade is the safe+ // PortOS default; the native port also has a slower 1536 cascade for direct use.+ requires: Object.freeze({+ appleSilicon: true,+ minUnifiedMemoryGb: 24,+ diskGb: 40,+ python: '3.10',+ }),+ // PortOS starts the fork at its 1024 cascade. The 1536 cascade is intentionally+ // not exposed through the shared detail control yet: the community port documents+ // runs that can take up to roughly an hour on a high-memory Mac, and the shared+ // labels describe TRELLIS.2's different tier vocabulary.+ supportsRenderOptions: Object.freeze({ detail: false, alphaMode: false, normalMap: false }),+ upstream: 'https://github.com/TencentARC/Pixal3D',+ port: 'https://github.com/pawel-mazurkiewicz/Pixal3D-mac',+ weightsRepo: 'TencentARC/Pixal3D',+ installNotes:+ 'Cloning the Apple Silicon Pixal3D port and creating its isolated Python 3.10 '+ + 'environment, then compiling the vendored Metal mesh, sparse-GEMM, rasterizer, '+ + 'BVH and neighborhood-attention packages. The first render downloads the model '+ + 'weights from Hugging Face; budget roughly 40 GB of disk and several minutes per '+ + '1024-cascade render.',+ // The Mac port uses public mirrors for its DINOv3 and MoGe dependencies. A token is+ // still passed to the child for Hugging Face rate-limit headroom, but no terms need+ // to be accepted in the install card.+ }),trellis2Cuda: Object.freeze({id: 'trellis2Cuda',label: 'TRELLIS.2 (CUDA)',diff --git a/server/services/imageTo3d/targets.test.js b/server/services/imageTo3d/targets.test.jsindex d78a37f608..3b0e8a8458 100644--- a/server/services/imageTo3d/targets.test.js+++ b/server/services/imageTo3d/targets.test.js@@ -68,6 +68,21 @@ describe('image-to-3d target registry', () => {.toEqual(['facebook/dinov3-vitl16-pretrain-lvd1689m', 'briaai/RMBG-2.0']);});+ it('registers the Apple Silicon Pixal3D port as a separate local-MPS target', () => {+ expect(IMAGE_TO_3D_TARGET_IDS).toContain('pixal3dMps');+ const t = getTarget('pixal3dMps');+ expect(t).toMatchObject({+ id: 'pixal3dMps',+ label: 'Pixal3D (Apple Silicon)',+ executionLane: EXECUTION_LANE.LOCAL_MPS,+ outputKind: OUTPUT_KIND.GLB_MESH,+ upstream: 'https://github.com/TencentARC/Pixal3D',+ port: 'https://github.com/pawel-mazurkiewicz/Pixal3D-mac',+ });+ expect(t.requires).toMatchObject({ appleSilicon: true, minUnifiedMemoryGb: 24 });+ expect(t.gatedRepos).toBeUndefined();+ });+it('leaves trellis2 (MPS) as the default target', () => {// Adding the CUDA lane must not change which target an unqualified request gets.expect(DEFAULT_IMAGE_TO_3D_TARGET).toBe('trellis2');@@ -175,7 +190,7 @@ describe('listTargets', () => {it('hides a target blocked for hardware the host simply does not have', () => {// A Mac has no NVIDIA GPU and never will — a permanently-red CUDA card is noise.- expect(listTargets(APPLE_128GB).map((t) => t.id)).toEqual(['trellis2']);+ expect(listTargets(APPLE_128GB).map((t) => t.id)).toEqual(['trellis2', 'pixal3dMps']);});it('applies that hiding symmetrically, not just to the newer lane', () => {@@ -340,6 +355,10 @@ describe('renderOptionSupportFor', () => {// choice could hand a 12 GB card a config that OOMs mid-render.expect(renderOptionSupportFor('pixal3dCuda')).toEqual({ steps: false, detail: false, alphaMode: false, normalMap: false });+ // The Apple port has a shared 1024 default and no alpha/normal-map CLI controls;+ // sampler steps remain supported and therefore are intentionally absent here.+ expect(renderOptionSupportFor('pixal3dMps'))+ .toEqual({ detail: false, alphaMode: false, normalMap: false });// Upstream's CUDA entrypoint takes no pipeline-type override at all.expect(renderOptionSupportFor('trellis2Cuda')).toEqual({ detail: false, alphaMode: false, normalMap: false });