Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: improve TRELLIS texture rendering
[._.]/ Adam Eivy3e25dc897a2d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a8cee7917a..cd0d12e220 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## 3D+- **TRELLIS.2 models no longer render with transparent holes, and high-memory Macs use the sharper texture pipeline** — existing generated meshes now display as solid in the 3D viewer, while new downloads are normalized to the opaque material mode TRELLIS intended. Macs with at least 48 GB of unified memory now use 1024-cascade generation for better surface-detail placement; supported 24 GB systems stay on the proven lower-memory lane.- **[issue-3041] Installing TRELLIS.2 now fetches the Apple toolchain it needs, instead of telling you to run a command** — #2952 made the "correct shape, confetti surface" problem *visible*, but the fix was still a terminal command you had to copy out of a warning and run yourself — leaving every new install one manual step away from bad-looking renders. Installing (or repairing) TRELLIS.2 now downloads Apple's Xcode Metal Toolchain itself when it's missing, before the setup that needs it, so a fresh install produces properly textured meshes with nothing extra to do. No password is required and the download is skipped entirely when you already have it. **Repair install** on an existing degraded copy now genuinely fixes it rather than re-running the same broken setup. Two honest edge cases: if the download fails the install continues anyway (your geometry is unaffected, and the finished install tells you textures will be reduced), and on a Mac with only the Command Line Tools — where nothing PortOS runs can fetch the toolchain — you get a note naming Xcode as the prerequisite and no Repair button that would only fail.- **[issue-2952] The 3D page now catches the install problem that made meshes come out as colorful static** — a TRELLIS.2 render could produce a perfectly accurate 3D shape wrapped in a scrambled, speckled surface, with nothing anywhere saying why. The cause is an install that only *looked* finished: TRELLIS.2's setup builds its high-quality texture painter from Metal source, and on a Mac without Apple's Xcode Metal Toolchain that build quietly fails, the setup still reports success, and every later render silently falls back to a low-resolution painter that can't cover a detailed mesh — so the shape is right and the paint job is confetti. PortOS now checks for the Metal Toolchain **before** you commit to the multi-hour install and warns you if it's missing, verifies after installing whether the good texture painter actually landed, and shows any already-installed copy as **Ready · degraded textures** with a plain explanation and a one-click **Repair install** that rebuilds just the missing piece (your downloaded models are kept). Renders also now bake textures at the highest resolution TRELLIS.2 offers, so surfaces hold more detail either way.- **[issue-3032] The 3D page now uses the Hugging Face token you already saved — and lets you add one right there** — if you'd already given PortOS a Hugging Face token (for gated image models or local model downloads), the 3D page ignored it: it never handed the token to the render, so TRELLIS.2's first run still failed on the two gated models it downloads, and the page kept telling you to go authenticate in a terminal. Your saved token now travels into the render, and the notice reads your actual setup: with a token in place it collapses to a one-line confirmation telling you where that token came from, and with none it offers a paste-and-save field instead of terminal instructions. Either way the two gated models stay linked, since their terms still have to be accepted on your Hugging Face account — a token alone doesn't grant access.diff --git a/client/src/components/media/GlbViewer.jsx b/client/src/components/media/GlbViewer.jsxindex 83f0588636..711f7e4121 100644--- a/client/src/components/media/GlbViewer.jsx+++ b/client/src/components/media/GlbViewer.jsx@@ -1,4 +1,4 @@-import { Suspense } from 'react';+import { Suspense, useEffect, useMemo } from 'react';import { Canvas } from '@react-three/fiber';import { Bounds, OrbitControls, useGLTF } from '@react-three/drei';import { Download, Rotate3d } from 'lucide-react';@@ -17,20 +17,65 @@ function filenameFromSrc(src) {return tail && tail.toLowerCase().endsWith('.glb') ? tail : 'model.glb';}-function GlbModel({ src }) {+const opaqueMaterial = (material) => {+ if (!material?.clone) return material;+ const clone = material.clone();+ clone.transparent = false;+ clone.opacity = 1;+ clone.alphaTest = 0;+ clone.depthWrite = true;+ clone.needsUpdate = true;+ return clone;+};++// GLBs generated before the server-side opaque-export fix remain in users'+// libraries. Clone before overriding their materials so drei's URL-keyed cache+// stays pristine for any other consumer that intentionally wants alpha.+export function cloneGlbSceneWithOpaqueMaterials(scene) {+ const clone = scene.clone(true);+ clone.traverse((object) => {+ if (!object?.isMesh || !object.material) return;+ object.material = Array.isArray(object.material)+ ? object.material.map(opaqueMaterial)+ : opaqueMaterial(object.material);+ });+ return clone;+}++function GlbModel({ src, forceOpaque }) {// `useGLTF` keys drei's global cache on the URL, so a new generation (a new// `src`) parses fresh while revisiting the same mesh reuses the cache — no// manual cache-clear needed (clearing on unmount would force a full multi-MB// re-fetch every time the viewer remounts for the same URL).const { scene } = useGLTF(src);- return <primitive object={scene} />;+ const renderedScene = useMemo(+ () => (forceOpaque ? cloneGlbSceneWithOpaqueMaterials(scene) : scene),+ [forceOpaque, scene],+ );+ useEffect(() => {+ if (!forceOpaque) return undefined;+ return () => {+ renderedScene.traverse((object) => {+ if (!object?.isMesh || !object.material) return;+ const materials = Array.isArray(object.material) ? object.material : [object.material];+ materials.forEach((material) => material.dispose?.());+ });+ };+ }, [forceOpaque, renderedScene]);+ return <primitive object={renderedScene} />;}// `downloadHref` (optional) overrides where the Download button points — pass a// dedicated asset endpoint that sets its own `Content-Disposition` filename, so// the server owns the name instead of the client re-deriving it. Falls back to// `src` with a filename inferred from the URL.-export default function GlbViewer({ src, downloadHref, downloadName, className = '' }) {+export default function GlbViewer({+ src,+ downloadHref,+ downloadName,+ className = '',+ forceOpaque = false,+}) {if (!src) return null;const href = downloadHref || src;// With an explicit download endpoint the server's Content-Disposition wins, so@@ -48,7 +93,7 @@ export default function GlbViewer({ src, downloadHref, downloadName, className =<directionalLight position={[-4, -2, -5]} intensity={0.4} /><Suspense fallback={null}><Bounds fit clip observe margin={1.2}>- <GlbModel src={src} />+ <GlbModel src={src} forceOpaque={forceOpaque} /></Bounds></Suspense><OrbitControls makeDefault enablePan enableZoom enableRotate />diff --git a/client/src/components/media/GlbViewer.test.jsx b/client/src/components/media/GlbViewer.test.jsxindex 6a7cf29a49..79da0347d7 100644--- a/client/src/components/media/GlbViewer.test.jsx+++ b/client/src/components/media/GlbViewer.test.jsx@@ -1,5 +1,6 @@import { render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';+import { BoxGeometry, Group, Mesh, MeshStandardMaterial } from 'three';// The three.js stack can't run in jsdom (no WebGL context) and none of it is// under test here — this file covers the chrome AROUND the canvas (the download@@ -14,7 +15,7 @@ vi.mock('@react-three/drei', () => ({useGLTF: Object.assign(() => ({ scene: {} }), { clear: vi.fn() }),}));-import GlbViewer from './GlbViewer';+import GlbViewer, { cloneGlbSceneWithOpaqueMaterials } from './GlbViewer';describe('GlbViewer', () => {it('renders nothing without a src', () => {@@ -39,4 +40,27 @@ describe('GlbViewer', () => {render(<GlbViewer src="/data/models3d/streaming-endpoint" />);expect(screen.getByRole('link', { name: /Download \.glb/i })).toHaveAttribute('download', 'model.glb');});++ it('clones and makes legacy generated materials opaque without mutating the cached scene', () => {+ const scene = new Group();+ const material = new MeshStandardMaterial({+ opacity: 0.2,+ transparent: true,+ depthWrite: false,+ alphaTest: 0.5,+ });+ scene.add(new Mesh(new BoxGeometry(1, 1, 1), material));++ const clone = cloneGlbSceneWithOpaqueMaterials(scene);+ const clonedMaterial = clone.children[0].material;+ expect(clone).not.toBe(scene);+ expect(clonedMaterial).not.toBe(material);+ expect(clonedMaterial).toMatchObject({+ transparent: false,+ opacity: 1,+ alphaTest: 0,+ depthWrite: true,+ });+ expect(material).toMatchObject({ transparent: true, opacity: 0.2, depthWrite: false });+ });});diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsxindex bd8d89a1c7..9e0f0b991b 100644--- a/client/src/pages/Media3DDetail.jsx+++ b/client/src/pages/Media3DDetail.jsx@@ -162,7 +162,11 @@ export default function Media3DDetail() {<div><span className="mb-1 block text-xs text-gray-400">Mesh</span>{record.status === 'ready' && record.assetPath ? (- <GlbViewer src={record.assetPath} downloadHref={imageTo3dAssetUrl(record.id)} />+ <GlbViewer+ src={record.assetPath}+ downloadHref={imageTo3dAssetUrl(record.id)}+ forceOpaque+ />) : (<div className="flex aspect-square items-center justify-center rounded-xl border border-dashed border-port-border bg-port-bg text-center text-sm text-gray-500">{isGenerating ? (diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsxindex f7d613a54d..09b38a5654 100644--- a/client/src/pages/Media3DDetail.test.jsx+++ b/client/src/pages/Media3DDetail.test.jsx@@ -15,7 +15,9 @@ vi.mock('../services/api', () => ({// GlbViewer wraps a WebGL canvas jsdom can't render — stub to a marker echoing src.vi.mock('../components/media/GlbViewer', () => ({- default: ({ src }) => <div data-testid="glb-viewer">{src}</div>,+ default: ({ src, forceOpaque }) => (+ <div data-testid="glb-viewer" data-force-opaque={String(forceOpaque)}>{src}</div>+ ),}));vi.mock('../components/MediaImage', () => ({ default: ({ alt, src }) => <img alt={alt} src={src} /> }));vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));@@ -51,6 +53,7 @@ describe('Media3DDetail', () => {renderAt();expect(await screen.findByText('Example Beacon')).toBeInTheDocument();expect(screen.getByTestId('glb-viewer')).toHaveTextContent('/data/image-to-3d/image3d-1/model.glb');+ expect(screen.getByTestId('glb-viewer')).toHaveAttribute('data-force-opaque', 'true');expect(screen.getByAltText('Source image')).toBeInTheDocument();});diff --git a/server/services/imageTo3d/glbMaterials.js b/server/services/imageTo3d/glbMaterials.jsnew file mode 100644index 0000000000..4af69c25d1--- /dev/null+++ b/server/services/imageTo3d/glbMaterials.js@@ -0,0 +1,83 @@+import { readFile, writeFile } from 'node:fs/promises';++const GLB_MAGIC = 0x46546c67;+const GLB_VERSION = 2;+const JSON_CHUNK_TYPE = 0x4e4f534a;+const GLB_HEADER_BYTES = 12;+const CHUNK_HEADER_BYTES = 8;++function invalidGlb(message) {+ const error = new Error(`Invalid GLB: ${message}`);+ error.code = 'INVALID_GLB';+ return error;+}++/**+ * Rewrite every explicitly transparent glTF material to OPAQUE while preserving+ * the binary payload byte-for-byte.+ *+ * TRELLIS predicts an alpha channel as one of its PBR surface attributes. The+ * Apple-Silicon exporter currently auto-promotes a material to BLEND when even+ * one baked texel falls below alpha 250, despite upstream TRELLIS documenting+ * OPAQUE as the default export mode. For ordinary image-to-3D objects that turns+ * harmless alpha noise into holes across whichever UV islands sample it.+ *+ * @param {Buffer|Uint8Array} input+ * @returns {Buffer}+ */+export function forceOpaqueGlbMaterials(input) {+ const source = Buffer.from(input);+ if (source.length < GLB_HEADER_BYTES + CHUNK_HEADER_BYTES) {+ throw invalidGlb('file is shorter than its header');+ }+ if (source.readUInt32LE(0) !== GLB_MAGIC) throw invalidGlb('bad magic');+ if (source.readUInt32LE(4) !== GLB_VERSION) throw invalidGlb('unsupported version');+ if (source.readUInt32LE(8) !== source.length) throw invalidGlb('declared length does not match file size');++ const jsonLength = source.readUInt32LE(GLB_HEADER_BYTES);+ const jsonType = source.readUInt32LE(GLB_HEADER_BYTES + 4);+ const jsonStart = GLB_HEADER_BYTES + CHUNK_HEADER_BYTES;+ const jsonEnd = jsonStart + jsonLength;+ if (jsonType !== JSON_CHUNK_TYPE) throw invalidGlb('first chunk is not JSON');+ if (jsonEnd > source.length) throw invalidGlb('JSON chunk exceeds file size');++ const document = JSON.parse(source.toString('utf8', jsonStart, jsonEnd).replace(/\0+$/, '').trimEnd());+ let changed = false;+ for (const material of Array.isArray(document.materials) ? document.materials : []) {+ // An absent alphaMode already means OPAQUE in glTF. Only rewrite an explicit+ // BLEND/MASK so a no-op pass leaves an already-correct file byte-identical.+ if (material?.alphaMode === 'BLEND' || material?.alphaMode === 'MASK') {+ material.alphaMode = 'OPAQUE';+ changed = true;+ }+ }+ if (!changed) return source;++ const json = Buffer.from(JSON.stringify(document));+ const paddedJsonLength = Math.ceil(json.length / 4) * 4;+ const rest = source.subarray(jsonEnd);+ const output = Buffer.alloc(jsonStart + paddedJsonLength + rest.length, 0x20);++ source.copy(output, 0, 0, GLB_HEADER_BYTES);+ output.writeUInt32LE(output.length, 8);+ output.writeUInt32LE(paddedJsonLength, GLB_HEADER_BYTES);+ output.writeUInt32LE(JSON_CHUNK_TYPE, GLB_HEADER_BYTES + 4);+ json.copy(output, jsonStart);+ rest.copy(output, jsonStart + paddedJsonLength);+ return output;+}++/**+ * Apply the opaque-material normalization to a generated GLB on disk.+ *+ * @param {string} path+ * @param {{readFileImpl?: typeof readFile, writeFileImpl?: typeof writeFile}} [deps]+ */+export async function rewriteGlbMaterialsOpaque(+ path,+ { readFileImpl = readFile, writeFileImpl = writeFile } = {},+) {+ const source = await readFileImpl(path);+ const output = forceOpaqueGlbMaterials(source);+ if (output !== source && !output.equals(source)) await writeFileImpl(path, output);+}diff --git a/server/services/imageTo3d/glbMaterials.test.js b/server/services/imageTo3d/glbMaterials.test.jsnew file mode 100644index 0000000000..10b855914c--- /dev/null+++ b/server/services/imageTo3d/glbMaterials.test.js@@ -0,0 +1,97 @@+import { describe, expect, it, vi } from 'vitest';+import { forceOpaqueGlbMaterials, rewriteGlbMaterialsOpaque } from './glbMaterials.js';++const JSON_CHUNK_TYPE = 0x4e4f534a;+const BIN_CHUNK_TYPE = 0x004e4942;++function makeGlb(document, bin = Buffer.from([1, 2, 3, 4])) {+ const json = Buffer.from(JSON.stringify(document));+ const jsonLength = Math.ceil(json.length / 4) * 4;+ const binLength = Math.ceil(bin.length / 4) * 4;+ const output = Buffer.alloc(12 + 8 + jsonLength + 8 + binLength, 0);+ output.writeUInt32LE(0x46546c67, 0);+ output.writeUInt32LE(2, 4);+ output.writeUInt32LE(output.length, 8);+ output.writeUInt32LE(jsonLength, 12);+ output.writeUInt32LE(JSON_CHUNK_TYPE, 16);+ output.fill(0x20, 20, 20 + jsonLength);+ json.copy(output, 20);+ const binHeader = 20 + jsonLength;+ output.writeUInt32LE(binLength, binHeader);+ output.writeUInt32LE(BIN_CHUNK_TYPE, binHeader + 4);+ bin.copy(output, binHeader + 8);+ return output;+}++function readDocument(glb) {+ const jsonLength = glb.readUInt32LE(12);+ return JSON.parse(glb.toString('utf8', 20, 20 + jsonLength).trimEnd());+}++function readBinaryChunk(glb) {+ const jsonLength = glb.readUInt32LE(12);+ return glb.subarray(20 + jsonLength);+}++describe('forceOpaqueGlbMaterials', () => {+ it('rewrites BLEND and MASK materials while preserving the binary chunk', () => {+ const source = makeGlb({+ asset: { version: '2.0' },+ materials: [+ { name: 'predicted-alpha', alphaMode: 'BLEND' },+ { name: 'cutout', alphaMode: 'MASK', alphaCutoff: 0.4 },+ { name: 'already-solid', alphaMode: 'OPAQUE' },+ { name: 'implicit-solid' },+ ],+ });++ const output = forceOpaqueGlbMaterials(source);+ expect(readDocument(output).materials.map((material) => material.alphaMode)).toEqual([+ 'OPAQUE', 'OPAQUE', 'OPAQUE', undefined,+ ]);+ expect(readBinaryChunk(output)).toEqual(readBinaryChunk(source));+ expect(output.readUInt32LE(8)).toBe(output.length);+ });++ it('keeps an already-opaque GLB byte-identical', () => {+ const source = makeGlb({+ asset: { version: '2.0' },+ materials: [{ alphaMode: 'OPAQUE' }, {}],+ });+ expect(forceOpaqueGlbMaterials(source)).toEqual(source);+ });++ it('rejects malformed input instead of corrupting an unknown file', () => {+ expect(() => forceOpaqueGlbMaterials(Buffer.from('not a glb')))+ .toThrow(/Invalid GLB/);+ });+});++describe('rewriteGlbMaterialsOpaque', () => {+ it('writes the normalized GLB back to the same path', async () => {+ const source = makeGlb({+ asset: { version: '2.0' },+ materials: [{ alphaMode: 'BLEND' }],+ });+ const writeFileImpl = vi.fn(async () => {});+ await rewriteGlbMaterialsOpaque('/tmp/model.glb', {+ readFileImpl: vi.fn(async () => source),+ writeFileImpl,+ });+ expect(writeFileImpl).toHaveBeenCalledWith(+ '/tmp/model.glb',+ expect.any(Buffer),+ );+ expect(readDocument(writeFileImpl.mock.calls[0][1]).materials[0].alphaMode).toBe('OPAQUE');+ });++ it('does not write when no material needs normalization', async () => {+ const source = makeGlb({ asset: { version: '2.0' }, materials: [{}] });+ const writeFileImpl = vi.fn(async () => {});+ await rewriteGlbMaterialsOpaque('/tmp/model.glb', {+ readFileImpl: vi.fn(async () => source),+ writeFileImpl,+ });+ expect(writeFileImpl).not.toHaveBeenCalled();+ });+});diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex fb974ef7c6..4da5414305 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -19,10 +19,11 @@*/import { existsSync } from 'node:fs';-import { homedir, platform } from 'node:os';+import { homedir, platform, totalmem } from 'node:os';import { join } from 'node:path';import { spawn, execFile } from 'node:child_process';import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';const HOME = homedir();const IS_WIN = platform() === 'win32';@@ -314,6 +315,36 @@ export function trellis2OutputStem(outputPath) {*/export const TRELLIS2_TEXTURE_SIZES = [512, 1024, 2048];+/**+ * `generate.py` supports a fast 512 pipeline and two higher-resolution variants.+ * 1024-cascade keeps the proven 512 sparse-structure pass, then refines shape and+ * surface attributes against 1024px image conditioning. That is the useful quality+ * step for details landing on the right parts of a generated object.+ */+export const TRELLIS2_PIPELINE_TYPES = ['512', '1024', '1024_cascade'];+export const TRELLIS2_BASELINE_PIPELINE_TYPE = '512';+export const TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE = '1024_cascade';++/**+ * The Apple port documents an ~18 GB peak for its benchmarked 512 lane and does+ * not publish a 1024-cascade memory ceiling. Keep the supported 24 GB floor on the+ * known lane, and opt into the higher-resolution texture model only with a+ * conservative second 24 GB of headroom.+ */+export const TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB = 48;++/**+ * Pick the texture-generation lane from physical unified memory.+ *+ * @param {number} unifiedMemoryGb+ * @returns {'512'|'1024_cascade'}+ */+export function selectTrellis2PipelineType(unifiedMemoryGb) {+ return Number(unifiedMemoryGb) >= TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB+ ? TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE+ : TRELLIS2_BASELINE_PIPELINE_TYPE;+}+/*** PortOS asks for the largest atlas the port offers, overriding `generate.py`'s* 1024 default. The bake UV-unwraps a 200k-triangle mesh into a single atlas, so@@ -334,7 +365,8 @@ export const TRELLIS2_DEFAULT_TEXTURE_SIZE = 2048;* `outputPath` is the desired `.glb` disk path; it is reduced to the stem the port* expects (see `trellis2OutputStem`).*- * @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number}} opts+ * @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,+ * pipelineType?: string}} opts* @returns {{command: string, args: string[]}}*/export function buildGenerateArgs({@@ -342,6 +374,7 @@ export function buildGenerateArgs({outputPath,base,textureSize = TRELLIS2_DEFAULT_TEXTURE_SIZE,+ pipelineType = TRELLIS2_BASELINE_PIPELINE_TYPE,} = {}) {if (!imagePath) throw new Error('buildGenerateArgs: imagePath is required');if (!TRELLIS2_TEXTURE_SIZES.includes(textureSize)) {@@ -349,8 +382,14 @@ export function buildGenerateArgs({`buildGenerateArgs: textureSize must be one of ${TRELLIS2_TEXTURE_SIZES.join(', ')}`,);}+ if (!TRELLIS2_PIPELINE_TYPES.includes(pipelineType)) {+ throw new Error(+ `buildGenerateArgs: pipelineType must be one of ${TRELLIS2_PIPELINE_TYPES.join(', ')}`,+ );+ }const args = [trellis2GenerateScript(base), imagePath];if (outputPath) args.push('--output', trellis2OutputStem(outputPath));+ args.push('--pipeline-type', pipelineType);args.push('--texture-size', String(textureSize));return { command: trellis2VenvPython(base), args };}@@ -672,10 +711,16 @@ const HF_AUTH_HELP = 'TRELLIS.2 could not download a gated model dependency from* it in — this function stays synchronous so its `{ promise, kill }` contract holds.* Omitted → the child inherits `process.env` as before.*+ * A successful render is normalized to opaque before it resolves. The Apple port+ * auto-enables BLEND from isolated low-alpha texels, while upstream TRELLIS+ * documents OPAQUE as the default; leaving BLEND active turns prediction noise+ * into visible holes in both PortOS and downloaded GLBs.+ ** @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,+ * pipelineType?: string, unifiedMemoryGb?: number,* onProgress?: (frame: object) => void,* spawnImpl?: Function, exists?: (p: string) => boolean,- * env?: NodeJS.ProcessEnv}} opts+ * env?: NodeJS.ProcessEnv, postprocessGlb?: (path: string) => Promise<void>}} opts* @returns {{promise: Promise<{assetPath: string}>, kill: () => void}}*/export function runTrellis2Generate({@@ -683,17 +728,27 @@ export function runTrellis2Generate({outputPath,base,textureSize,+ pipelineType,+ unifiedMemoryGb = Math.round(totalmem() / 1024 ** 3),onProgress,spawnImpl = spawn,exists = existsSync,env,+ postprocessGlb = rewriteGlbMaterialsOpaque,} = {}) {if (!isTrellis2Installed({ base, exists })) {const err = new Error('TRELLIS.2 is not installed — install it before generating.');err.code = 'TRELLIS2_NOT_INSTALLED';return { promise: Promise.reject(err), kill: () => {} };}- const { command, args } = buildGenerateArgs({ imagePath, outputPath, base, textureSize });+ const resolvedPipelineType = pipelineType || selectTrellis2PipelineType(unifiedMemoryGb);+ const { command, args } = buildGenerateArgs({+ imagePath,+ outputPath,+ base,+ textureSize,+ pipelineType: resolvedPipelineType,+ });// Child-process boundary — errors surface via the 'error'/'close' events, not a// throw into the request lifecycle (CLAUDE.md child-process exception).const child = spawnImpl(command, args, { cwd: trellis2Root(base), ...(env ? { env } : {}) });@@ -720,7 +775,14 @@ export function runTrellis2Generate({child.on('error', reject);child.on('close', (code) => {if (code === 0 && assetPath) {- resolve({ assetPath });+ Promise.resolve()+ .then(() => postprocessGlb(assetPath))+ .then(() => resolve({ assetPath }))+ .catch((cause) => {+ const error = new Error(`TRELLIS.2 produced a GLB but material normalization failed: ${cause.message}`);+ error.code = 'TRELLIS2_GLB_POSTPROCESS_FAILED';+ reject(error);+ });return;}// A gated-dependency / HF-auth failure is a user-fixable setup problem, not adiff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex 5bff65c5c1..5105534d60 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -23,6 +23,11 @@ import {TRELLIS2_REQUIRES_XCODE_HINT,TRELLIS2_DEFAULT_TEXTURE_SIZE,TRELLIS2_TEXTURE_SIZES,+ TRELLIS2_PIPELINE_TYPES,+ TRELLIS2_BASELINE_PIPELINE_TYPE,+ TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE,+ TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB,+ selectTrellis2PipelineType,} from './trellis2.js';const flush = () => new Promise((resolve) => setTimeout(resolve, 0));@@ -127,6 +132,7 @@ describe('buildGenerateArgs', () => {expect(command).toBe(trellis2VenvPython(BASE));expect(args).toEqual([trellis2GenerateScript(BASE), '/data/images/x.png',+ '--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,'--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),]);});@@ -143,7 +149,11 @@ describe('buildGenerateArgs', () => {it('honors an explicit texture size', () => {const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 1024 });- expect(args).toEqual([trellis2GenerateScript(BASE), 'in.png', '--texture-size', '1024']);+ expect(args).toEqual([+ trellis2GenerateScript(BASE), 'in.png',+ '--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,+ '--texture-size', '1024',+ ]);});it('rejects a texture size outside the port\'s argparse choices instead of letting the render abort', () => {@@ -151,11 +161,34 @@ describe('buildGenerateArgs', () => {.toThrow(/textureSize must be one of/);});+ it('honors and validates the texture-generation pipeline type', () => {+ const { args } = buildGenerateArgs({+ imagePath: 'in.png',+ base: BASE,+ pipelineType: TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE,+ });+ expect(args).toContain(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, pipelineType: '4096' }))+ .toThrow(/pipelineType must be one of/);+ });+it('throws when no source image is given', () => {expect(() => buildGenerateArgs({ base: BASE })).toThrow(/imagePath is required/);});});+describe('selectTrellis2PipelineType', () => {+ it('keeps supported 24 GB hosts on the benchmarked 512 lane', () => {+ expect(selectTrellis2PipelineType(24)).toBe(TRELLIS2_BASELINE_PIPELINE_TYPE);+ });++ it('uses 1024-cascade when the host has conservative memory headroom', () => {+ expect(selectTrellis2PipelineType(TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB))+ .toBe(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ expect(TRELLIS2_PIPELINE_TYPES).toContain(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ });+});+describe('probeTrellis2TextureBake', () => {// The probe shells to the venv python with an importlib.util.find_spec one-liner.// Fake execFile lets us assert each outcome without a real venv.@@ -333,16 +366,23 @@ describe('runTrellis2Generate', () => {const child = makeChild();const spawnImpl = vi.fn(() => child);const frames = [];+ const postprocessGlb = vi.fn(async () => {});const { promise } = runTrellis2Generate({imagePath: 'a.png',base: BASE,+ unifiedMemoryGb: 24,exists: installed,spawnImpl,+ postprocessGlb,onProgress: (f) => frames.push(f),});expect(spawnImpl).toHaveBeenCalledWith(trellis2VenvPython(BASE),- [trellis2GenerateScript(BASE), 'a.png', '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE)],+ [+ trellis2GenerateScript(BASE), 'a.png',+ '--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,+ '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),+ ],{ cwd: trellis2Root(BASE) },);child.stdout.emit('data', 'Generating 3D model (pipeline=512, seed=42)...\n');@@ -350,6 +390,7 @@ describe('runTrellis2Generate', () => {child.stdout.emit('data', ' Saved: /out/a.glb\n');child.emit('close', 0);await expect(promise).resolves.toEqual({ assetPath: '/out/a.glb' });+ expect(postprocessGlb).toHaveBeenCalledWith('/out/a.glb');expect(frames).toEqual([{ stage: 'generating', percent: 10, message: 'Generating 3D model (pipeline=512, seed=42)...' },{ stage: 'generating', percent: 30, message: 'Sampling: 50%|█████ | 6/12' },@@ -363,12 +404,14 @@ describe('runTrellis2Generate', () => {// LAST (highest) frame, not the first — otherwise sampling under-reports.const child = makeChild();const frames = [];+ const postprocessGlb = vi.fn(async () => {});const { promise } = runTrellis2Generate({imagePath: 'a.png',outputPath: '/out/a.glb',base: BASE,exists: installed,spawnImpl: () => child,+ postprocessGlb,onProgress: (f) => frames.push(f),});child.stdout.emit('data', 'Sampling: 0%\rSampling: 50%\rSampling: 100%\r');@@ -379,6 +422,39 @@ describe('runTrellis2Generate', () => {expect(frames.map((f) => f.percent)).toEqual([10, 30, 50, 92]);});+ it('selects the 1024-cascade texture model on a high-memory host', async () => {+ const child = makeChild();+ const spawnImpl = vi.fn(() => child);+ const { promise } = runTrellis2Generate({+ imagePath: 'a.png',+ outputPath: '/out/a.glb',+ base: BASE,+ unifiedMemoryGb: 128,+ exists: installed,+ spawnImpl,+ postprocessGlb: vi.fn(async () => {}),+ });+ expect(spawnImpl.mock.calls[0][1]).toContain(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ child.emit('close', 0);+ await expect(promise).resolves.toEqual({ assetPath: '/out/a.glb' });+ });++ it('fails the run when the exported GLB cannot be normalized safely', async () => {+ const child = makeChild();+ const { promise } = runTrellis2Generate({+ imagePath: 'a.png',+ outputPath: '/out/a.glb',+ base: BASE,+ exists: installed,+ spawnImpl: () => child,+ postprocessGlb: vi.fn(() => {+ throw new Error('bad GLB');+ }),+ });+ child.emit('close', 0);+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GLB_POSTPROCESS_FAILED' });+ });+it('rejects on a non-zero exit', async () => {const child = makeChild();const { promise } = runTrellis2Generate({@@ -432,10 +508,21 @@ describe('runTrellis2Generate', () => {const child = makeChild();const spawnImpl = vi.fn(() => child);const env = { PATH: '/usr/bin', HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' };- const { promise } = runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: installed, spawnImpl, env });+ const { promise } = runTrellis2Generate({+ imagePath: 'a.png',+ base: BASE,+ unifiedMemoryGb: 24,+ exists: installed,+ spawnImpl,+ env,+ });expect(spawnImpl).toHaveBeenCalledWith(trellis2VenvPython(BASE),- [trellis2GenerateScript(BASE), 'a.png', '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE)],+ [+ trellis2GenerateScript(BASE), 'a.png',+ '--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,+ '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),+ ],{ cwd: trellis2Root(BASE), env },);child.emit('close', null); // settle the run so its rejection isn't left dangling