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
make the normal-map bake opt-in and stop claiming it cannot fail a render
Adam Eivycaa72a876ca0
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsxindex db2371d4be..225737f881 100644--- a/client/src/components/media/ImageTo3dRenderOptions.jsx+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx@@ -143,15 +143,16 @@ export default function ImageTo3dRenderOptions({/>Key out solid background</label>- {/* Defaults on: it recovers shading detail the bake decimation discards- for ~2s on a multi-minute render, and cannot fail the render. The- control exists so a bad map is recoverable, not because it is a- routine choice. */}+ {/* Opt-in, not default-on. It recovers shading detail the decimation+ discards, but the bake runs before the GLB is written and builds a BVH+ over a mesh larger than its dependency's tests cover — a hard crash+ there (segfault / OOM / GPU watchdog) loses the whole render, which no+ Python guard can catch. */}<labelhtmlFor="image-to-3d-normal-map"className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300"title={normalMapSupported- ? 'Bake a normal map from the full-resolution mesh so lighting keeps detail the exported triangles no longer carry'+ ? 'Recover shading detail the decimation discards, by baking a normal map from the full-resolution mesh. Adds time, and on a very large mesh can crash the render outright — retry without it if a render dies during texture baking.': 'This model does not bake a normal map'}><inputdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 93a57d4165..175ed5877b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -65,7 +65,7 @@ grep -i "what you want to do" client/src/lib/README.md| `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. || `imageGenResolutions.js` | Shared resolution presets for image generation. || `imageTo3dReasons.js` | Client mirror of the image-to-3D unavailable-reason labels in `server/services/imageTo3d/targets.js`: `UNAVAILABLE_REASONS` (reason code → user-facing label), `UNAVAILABLE_REASON_FALLBACK`, and `unavailableReasonLabel(code, fallback?)`. Use this anywhere a target's `unavailableReason` is rendered — never re-declare the codes. Parity + code coverage enforced by `server/services/imageTo3d/unavailableReasons.parity.test.js`. |-| `imageTo3dRenderOptions.js` | Pure helpers for the image-to-3D per-run render options: `SEED_MAX` (client mirror of the server's `RENDER_SEED_MAX`, parity-pinned by `server/services/imageTo3d/renderOptions.parity.test.js`), `STEPS_PRESETS`, `renderOptionsBody(fields)` (field state → request body, unset keys omitted), and `fieldsFromRun(run)` (latest run → field state; seed stays blank so re-renders keep rolling fresh seeds). |+| `imageTo3dRenderOptions.js` | Image-to-3D per-run render options — the client mirror of the server bounds (`SEED_MAX`), the `STEPS_PRESETS` / `DETAIL_PRESETS` / `ALPHA_MODE_PRESETS` select options, `renderOptionsBody` (fields → API body), `fieldsFromRun` (carry-over from the last run), and `runWantsTransparency` (mirrors the server's alpha gating — the viewer's force-opaque pass must agree with it). Pinned by `renderOptions.parity.test.js`. || `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. || `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. || `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |diff --git a/client/src/lib/imageTo3dRenderOptions.js b/client/src/lib/imageTo3dRenderOptions.jsindex cc364c2cfb..908a0046ea 100644--- a/client/src/lib/imageTo3dRenderOptions.js+++ b/client/src/lib/imageTo3dRenderOptions.js@@ -72,8 +72,10 @@ export function renderOptionsBody({ steps, seed, keyBackground, detail, alphaMod// they are, unlike alphaMode below....(detail && detail !== 'auto' && { detail }),...(alphaMode !== '' && alphaMode != null && { alphaMode }),- // Sent always, not omitted-when-default: the server default is TRUE, so omitting- // it could not express "off".+ // Sent always rather than omitted-when-default. The server default is `false`, so+ // omitting it would happen to work today — but the whole point of this mapping is+ // that the wire body states what the run asked for, and a future default flip+ // must not silently change what an existing client means.normalMap,};}@@ -96,8 +98,8 @@ export function fieldsFromRun(run) {// the same defaults a fresh form starts at.detail: DETAIL_PRESETS.some((p) => p.value === run?.detail) ? run.detail : 'auto',alphaMode: typeof run?.alphaMode === 'string' ? run.alphaMode : '',- // A run predating the field has none; default to on, matching the server.- normalMap: typeof run?.normalMap === 'boolean' ? run.normalMap : true,+ // A run predating the field has none; default to OFF, matching the server.+ normalMap: typeof run?.normalMap === 'boolean' ? run.normalMap : false,};}diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex ab4d0c080a..9e5a800298 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -202,7 +202,7 @@ export default function Media3D() {const [keyBackground, setKeyBackground] = useState(true);const [detail, setDetail] = useState('auto');const [alphaMode, setAlphaMode] = useState('');- const [normalMap, setNormalMap] = useState(true);+ const [normalMap, setNormalMap] = useState(false);// Existing image-to-3D records (newest-first) so the page doubles as a library:// each links to its `/3d/:id` detail view.const [records, setRecords] = useState([]);diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsxindex ae297f4426..9b43471054 100644--- a/client/src/pages/Media3DDetail.jsx+++ b/client/src/pages/Media3DDetail.jsx@@ -37,7 +37,7 @@ export default function Media3DDetail() {const [keyBackground, setKeyBackground] = useState(true);const [detail, setDetail] = useState('auto');const [alphaMode, setAlphaMode] = useState('');- const [normalMap, setNormalMap] = useState(true);+ const [normalMap, setNormalMap] = useState(false);const optionsSeededFor = useRef(null);const load = useCallback(async ({ initial = false } = {}) => {diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex 96f19ac511..379657032c 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -530,9 +530,11 @@ describe('image-to-3d model records', () => {expect(res.body?.error?.code || res.body?.code).toBe('FULL_MESH_MISSING');});- it('does not let /full-mesh be swallowed by the /models/:id route', async () => {- // Route-order regression: `/models/:id` would happily match `full-mesh` as an- // id and return JSON instead of a download.+ it('routes /full-mesh to its own handler with the record id', async () => {+ // Deliberately NOT claiming this proves route ordering: Express's `:id` matches a+ // single path segment, so `/models/x/full-mesh` can never match `/models/:id`+ // regardless of registration order. What it does pin is that the id is parsed+ // from the right segment and reaches the handler.models.getModelFullMesh.mockRejectedValue(new Error('boom'));await request(makeApp()).get('/api/image-to-3d/models/image3d-1/full-mesh');expect(models.getModelFullMesh).toHaveBeenCalledWith('image3d-1');diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.jsindex 9d4475c90d..86861bdb80 100644--- a/server/services/imageTo3d/renderOptions.js+++ b/server/services/imageTo3d/renderOptions.js@@ -17,8 +17,9 @@* what every lane did before the knob existed.* - `alphaMode: null` → don't instruct the exporter, and keep PortOS's* force-opaque normalization.- * - `normalMap: true` (the default) → bake a tangent-space normal map from the- * pre-decimation mesh, so shading keeps detail the triangles no longer carry.+ * - `normalMap: false` (the default) → skip the normal-map bake. Opt in to recover+ * shading detail the decimation discards, accepting the hard-crash risk noted+ * below.*/import { randomInt } from 'node:crypto';@@ -104,11 +105,17 @@ export function normalizeRenderOptions(input = {}) {// `alphaMode` stays null-when-unset, because "don't ask the exporter" is a// genuinely different instruction from any of the concrete modes.alphaMode: isValidAlphaMode(input.alphaMode) ? input.alphaMode : null,- // Defaults ON, unlike every other knob here. It recovers shading detail the bake- // decimation discards, measured at ~2s against a multi-minute render, and it- // cannot fail a render (the bake is wrapped and degrades to no map). So the- // useful default is on, with this as the escape hatch if a map ever looks wrong.- normalMap: input.normalMap !== false,+ // Opt-IN, for the same reason `--fill-holes` is. The bake builds a BVH over a+ // mesh far larger than anything mtlbvh's regression tests cover, and it runs+ // INSIDE `to_glb` — i.e. before generate.py has exported the GLB. Its Python+ // guard catches a raise, but NOT a segfault, an abort, an OOM kill, or the macOS+ // GPU watchdog killing a long Metal dispatch (the failure this branch's own+ // `isMpsWatchdogError` exists for). Any of those loses a 13-20 minute render that+ // had already produced a correct mesh and texture.+ //+ // An earlier revision defaulted this ON and claimed it "cannot fail a render".+ // That was false as written, and it was the claim the opt-out decision rested on.+ normalMap: input.normalMap === true,};}@@ -179,14 +186,18 @@ export function validateRenderOptions(label, { steps = null, seed = null } = {})*/export function honorTargetRenderSupport(options, support) {if (!support) return options;- return {- ...options,- ...(support.steps === false ? { steps: null } : {}),- // Reset to the same sentinel `normalizeRenderOptions` uses for "unset", so a- // dropped option records as not-requested rather than as a value the- // subprocess never received.- ...(support.detail === false ? { detail: DEFAULT_DETAIL_TIER } : {}),- ...(support.alphaMode === false ? { alphaMode: null } : {}),- ...(support.normalMap === false ? { normalMap: false } : {}),- };+ // Derived from the unset shape rather than an enumerated list of keys. The previous+ // per-key version handled 4 of the 6 keys `RENDER_OPTION_KEYS` accepts, so a+ // descriptor declaring `seed: false` or `keyBackground: false` passed the registry+ // invariant and was then silently ignored here — recording a value the subprocess+ // never received, the exact thing this function exists to prevent. Reset to the same+ // sentinel `normalizeRenderOptions` produces for "unset", whatever that key's+ // sentinel happens to be (`null`, `'auto'`, `true`, or `false`).+ const unset = normalizeRenderOptions();+ const dropped = Object.fromEntries(+ Object.entries(support)+ .filter(([key, supported]) => supported === false && key in unset)+ .map(([key]) => [key, unset[key]]),+ );+ return { ...options, ...dropped };}diff --git a/server/services/imageTo3d/renderOptions.parity.test.js b/server/services/imageTo3d/renderOptions.parity.test.jsindex a86c169416..ec30f397d9 100644--- a/server/services/imageTo3d/renderOptions.parity.test.js+++ b/server/services/imageTo3d/renderOptions.parity.test.js@@ -9,7 +9,10 @@* the client mirror is a pure module that loads fine under the node runner.*/+import { readFileSync } from 'node:fs';import { describe, it, expect } from 'vitest';+import { trellis2GenerateRunnerScript } from './trellis2.js';+import { TRELLIS2_ALPHA_MODES } from './trellis2MeshQuality.js';import {ALPHA_MODES,DETAIL_TIERS,@@ -42,6 +45,26 @@ describe('image-to-3D render-option parity (server bounds ↔ client mirror)', (expect(values.filter((v) => v !== '').sort()).toEqual([...ALPHA_MODES].sort());});+ it('the two server-side alpha-mode lists agree', () => {+ // ALPHA_MODES gates the route; TRELLIS2_ALPHA_MODES gates arg building. Adding a+ // mode to only the first means the route 202s the render and then the arg builder+ // throws — a failure after the job was already accepted.+ expect([...TRELLIS2_ALPHA_MODES].sort()).toEqual([...ALPHA_MODES].sort());+ });++ it('the runner’s argparse choices match the server alpha-mode list', () => {+ // The fourth copy lives in Python. Read it out of the source rather than restating+ // it, so a drift in either direction fails here instead of at render time.+ const src = readFileSync(trellis2GenerateRunnerScript(), 'utf8');+ const block = src.slice(src.indexOf('"--alpha-mode"'));+ const choices = block.slice(block.indexOf('choices=['), block.indexOf(']') + 1);+ for (const mode of ALPHA_MODES) {+ expect(choices, `argparse choices missing ${mode}`).toContain(`"${mode}"`);+ }+ // And nothing extra: count the quoted entries.+ expect((choices.match(/"/g) || []).length / 2).toBe(ALPHA_MODES.length);+ });+it('every non-default client steps preset is a value the server accepts', () => {const numeric = CLIENT_STEPS_PRESETS.map((preset) => preset.value)diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.jsindex aa25b6b3fb..7e3ead2734 100644--- a/server/services/imageTo3d/renderOptions.test.js+++ b/server/services/imageTo3d/renderOptions.test.js@@ -18,17 +18,17 @@ import {describe('normalizeRenderOptions', () => {it('defaults to unset steps/seed with keying enabled', () => {- expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });- expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });+ expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: false });+ expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: false });});it('keeps valid values and collapses invalid ones to the unset sentinel', () => {expect(normalizeRenderOptions({ steps: 24, seed: 0, keyBackground: false }))- .toEqual({ steps: 24, seed: 0, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: true });+ .toEqual({ steps: 24, seed: 0, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });expect(normalizeRenderOptions({ steps: RENDER_STEPS_MAX + 1, seed: RENDER_SEED_MAX + 1 }))- .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });+ .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: false });expect(normalizeRenderOptions({ steps: 12.5, seed: '42' }))- .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: true });+ .toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: false });});});@@ -122,21 +122,25 @@ describe('detail tier and alpha mode', () => {});describe('normalMap', () => {- it('is the one option that defaults ON', () => {- // Every other knob defaults to "unset" so the subprocess picks. This one defaults- // on because it recovers detail the bake decimation discards for ~2s on a- // multi-minute render, and cannot fail the render.- expect(normalizeRenderOptions().normalMap).toBe(true);+ it('defaults OFF, like every other quality knob that can lose a render', () => {+ // Opt-in for the same reason --fill-holes is: the bake runs before the GLB is+ // exported and builds a BVH beyond its dependency's tested sizes, so a segfault /+ // OOM / GPU-watchdog kill there destroys a multi-minute render. No Python guard+ // catches those. An earlier revision defaulted this ON on the strength of a+ // "cannot fail a render" claim that was false.+ expect(normalizeRenderOptions().normalMap).toBe(false);});- it('honors an explicit false — the only way to express "off"', () => {+ it('requires an explicit true — the only way to opt in', () => {+ expect(normalizeRenderOptions({ normalMap: true }).normalMap).toBe(true);expect(normalizeRenderOptions({ normalMap: false }).normalMap).toBe(false);});- it('treats a non-boolean as the default rather than as off', () => {- // A missing/garbage value must not silently disable a quality default.- for (const bad of [undefined, null, 'false', 0]) {- expect(normalizeRenderOptions({ normalMap: bad }).normalMap).toBe(true);+ it('treats a non-boolean as off rather than as opted-in', () => {+ // Fail safe: a garbage or truthy-string value must not enable a pass that can+ // take the render down with it.+ for (const bad of [undefined, null, 'true', 1, {}]) {+ expect(normalizeRenderOptions({ normalMap: bad }).normalMap).toBe(false);}});});diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex 95164dab0a..f716afad61 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -36,6 +36,7 @@ import {selectTrellis2DecimationTarget,trellis2MeshQualityArgs,trellis2FillHolesStep,+ TRELLIS2_NORMAL_SOURCE_FACE_CAP,} from './trellis2MeshQuality.js';const HOME = homedir();@@ -858,7 +859,36 @@ export const TRELLIS2_WATCHDOG_HELP = 'The macOS GPU watchdog stopped this rende+ 'window-server load. Merely unplugging external displays, running headless over '+ 'SSH, or lowering sampler steps are all reported NOT to help, because the kill '+ 'targets one long dispatch rather than the render as a whole. Dropping to a lower '- + 'Detail tier does shorten that dispatch.'+ + 'Detail tier does shorten that dispatch. One caveat: a blank or over-keyed source '+ + 'image also decodes to an empty mesh and prints the same message, so if this fails '+ + 'immediately rather than minutes in, check the input before the GPU.'++/**+ * Which GLB post-process a run should apply — extracted so the decision is testable+ * on its own rather than as a side effect of a spawn.+ *+ * Three layers can flatten alpha (the exporter's `alpha_mode`, this rewrite, and the+ * viewer's `forceOpaque` prop). They have to agree, or a mesh exported as BLEND still+ * renders solid and reads as a broken exporter.+ *+ * - `override !== undefined` wins outright, and **an explicit `null` therefore means+ * "run nothing"**. That is not incidental: a parameter default only applies to+ * `undefined`, so `null` already meant this before the fallback became computed,+ * and using `??` here would quietly turn it back into force-opaque — absent vs.+ * explicitly-empty, per CLAUDE.md.+ * - Otherwise force-opaque applies unless the caller asked the exporter for a+ * transparent material. The rewrite still defaults on because an older o_voxel+ * promoted to BLEND off a single low-alpha texel, which is what it was written for.+ *+ * @param {string|null} alphaMode+ * @param {Function|null|undefined} override+ * @returns {Function|undefined}+ */+export function resolveGlbPostprocess(alphaMode, override) {+ if (override !== undefined) return override ?? undefined;+ const wantsTransparency = alphaMode !== null && alphaMode !== undefined && alphaMode !== 'OPAQUE';+ return wantsTransparency ? undefined : rewriteGlbMaterialsOpaque;+}/*** Run a single image→GLB generation. The one real-subprocess boundary — GUARDED:@@ -919,6 +949,7 @@ export function runTrellis2Generate({remesh = false,alphaMode = null,normalMap = false,+ normalMapMaxSourceFaces = TRELLIS2_NORMAL_SOURCE_FACE_CAP,onProgress,spawnImpl = spawn,exists = existsSync,@@ -950,6 +981,11 @@ export function runTrellis2Generate({remesh,alphaMode,normalMap,+ // Emitted only alongside --normal-map, but ALWAYS passed when it is: the Python+ // side has its own default, and leaving this unset meant the JS constant was+ // dead config — lowering it in response to a crash report would have changed+ // nothing while its tests kept passing.+ ...(normalMap ? { normalMapMaxSourceFaces } : {}),},});// Force-opaque normalization is skipped exactly when the caller asked the@@ -957,9 +993,7 @@ export function runTrellis2Generate({// default (`null`) keeps the historical force-opaque behaviour, which still// matters for installs carrying an older o_voxel that auto-promoted to BLEND// off a single low-alpha texel.- const wantsTransparency = alphaMode !== null && alphaMode !== 'OPAQUE';- const resolvedPostprocess = postprocessGlb- ?? (wantsTransparency ? undefined : rewriteGlbMaterialsOpaque);+ const resolvedPostprocess = resolveGlbPostprocess(alphaMode, postprocessGlb);return runGenerateSubprocess({command,args,diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.jsindex 6194162baa..146cfa5e34 100644--- a/server/services/imageTo3d/trellis2.test.js+++ b/server/services/imageTo3d/trellis2.test.js@@ -19,6 +19,9 @@ import {isTransientInstallError,isHfAuthError,isMpsWatchdogError,+ resolveTrellis2PipelineType,+ resolveGlbPostprocess,+ getTarget,TRELLIS2_WATCHDOG_HELP,probeTrellis2TextureBake,probeMetalToolchain,@@ -38,9 +41,11 @@ import {selectTrellis2TextureSize,hfGatedRepoHelp,} from './trellis2.js';+import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';import {TRELLIS2_DECIMATION_BASELINE,TRELLIS2_DECIMATION_HIGH,+ TRELLIS2_NORMAL_SOURCE_FACE_CAP,} from './trellis2MeshQuality.js';import { getTarget } from './targets.js';@@ -814,6 +819,119 @@ describe('isHfAuthError', () => {});});+describe('resolveTrellis2PipelineType', () => {+ // This is the entire server-side resolution of the detail knob and it had no tests:+ // nothing pinned the descriptor lookup, the 'auto' passthrough, or the deliberate+ // no-throw fallback the docstring spends a paragraph justifying.+ it("'auto' defers to the host-derived choice", () => {+ expect(resolveTrellis2PipelineType('auto', 24)).toBe(selectTrellis2PipelineType(24));+ expect(resolveTrellis2PipelineType('auto', 64)).toBe(selectTrellis2PipelineType(64));+ });++ it('maps each tier through the target descriptor, not a local table', () => {+ const tiers = getTarget('trellis2').detailTiers;+ for (const [tier, expected] of Object.entries(tiers)) {+ expect(resolveTrellis2PipelineType(tier, 64), tier).toBe(expected);+ }+ });++ it('lets a small host opt UP past what its memory would have chosen', () => {+ // The override is the whole point of the knob — PortOS's 48 GB threshold is an+ // admitted guess, so a 24 GB host asking for max must get max.+ expect(selectTrellis2PipelineType(24)).toBe(TRELLIS2_BASELINE_PIPELINE_TYPE);+ expect(resolveTrellis2PipelineType('max', 24)).toBe(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ });++ it('lets a large host opt DOWN to a fast preview', () => {+ expect(selectTrellis2PipelineType(64)).toBe(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ expect(resolveTrellis2PipelineType('fast', 64)).toBe(TRELLIS2_BASELINE_PIPELINE_TYPE);+ });++ it('falls back to the host choice on an unmapped tier instead of throwing', () => {+ // Reaching this means a registry edit went wrong; degrading to the tier the host+ // would have picked beats failing a render the user already waited on.+ expect(resolveTrellis2PipelineType('bogus', 64)).toBe(selectTrellis2PipelineType(64));+ expect(resolveTrellis2PipelineType('', 24)).toBe(selectTrellis2PipelineType(24));+ });+});++describe('runTrellis2Generate render-option wiring', () => {+ const installed = () => true;+ const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+ };+ const argvFor = (opts) => {+ const child = makeChild();+ const spawnImpl = vi.fn(() => child);+ const { promise } = runTrellis2Generate({+ imagePath: 'a.png', base: BASE, unifiedMemoryGb: 24, exists: installed, spawnImpl, ...opts,+ });+ promise.catch(() => {}); // settle; we only care about argv+ child.emit('close', null);+ return spawnImpl.mock.calls[0][1];+ };++ it('translates a detail tier into the pipeline type the runner receives', () => {+ // Nothing previously pinned that `detail` reaches argv at all.+ expect(argvFor({ detail: 'max' })).toContain(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);+ expect(argvFor({ detail: 'fast' })).toContain(TRELLIS2_BASELINE_PIPELINE_TYPE);+ });++ it('passes alphaMode and the normal-map flags through to the adapter', () => {+ const argv = argvFor({ alphaMode: 'BLEND', normalMap: true });+ expect(argv).toContain('--alpha-mode');+ expect(argv).toContain('BLEND');+ expect(argv).toContain('--normal-map');+ // The source cap must actually be emitted — it was dead config, so lowering it+ // changed nothing while its own tests kept passing.+ expect(argv).toContain('--normal-map-max-source-faces');+ expect(argv).toContain(String(TRELLIS2_NORMAL_SOURCE_FACE_CAP));+ });++ it('emits neither normal-map flag when the bake is off', () => {+ const argv = argvFor({ normalMap: false });+ expect(argv).not.toContain('--normal-map');+ expect(argv).not.toContain('--normal-map-max-source-faces');+ });++ it.each([+ [null, true],+ [undefined, true],+ ['OPAQUE', true],+ ['MASK', false],+ ['BLEND', false],+ ['auto', false],+ ])('force-opaque with alphaMode=%s -> applied=%s', (alphaMode, applied) => {+ // The layer that rewrites the GLB on disk had no test, only the viewer's. A+ // regression re-enabling it for BLEND would ship a silently-solid mesh.+ expect(resolveGlbPostprocess(alphaMode, undefined) === rewriteGlbMaterialsOpaque)+ .toBe(applied);+ });++ it('lets an explicit override win, and treats null as "run nothing"', () => {+ const custom = async () => {};+ expect(resolveGlbPostprocess(null, custom)).toBe(custom);+ // `??` would have turned this back into force-opaque.+ expect(resolveGlbPostprocess(null, null)).toBeUndefined();+ });++ it('honors an explicit null postprocess as "run nothing"', async () => {+ // `??` would have turned an explicit null back into force-opaque.+ const child = makeChild();+ const { promise } = runTrellis2Generate({+ imagePath: 'a.png', outputPath: '/out/a.glb', base: BASE, unifiedMemoryGb: 24,+ exists: installed, spawnImpl: () => child, postprocessGlb: null,+ });+ child.stdout.emit('data', ' Saved: /out/a.glb\n');+ child.emit('close', 0);+ await expect(promise).resolves.toEqual({ assetPath: '/out/a.glb' });+ });+});+describe('isMpsWatchdogError', () => {// Local copies: the equivalents in the runTrellis2Generate block are scoped to it.const installed = () => true;diff --git a/server/services/imageTo3d/trellis2GenerateRunner.py b/server/services/imageTo3d/trellis2GenerateRunner.pyindex 09879212c9..75a6dafd57 100644--- a/server/services/imageTo3d/trellis2GenerateRunner.py+++ b/server/services/imageTo3d/trellis2GenerateRunner.py@@ -209,6 +209,16 @@ def _patch_decimation_target(target):def to_glb(*args, **kwargs):incoming = kwargs.get("decimation_target")+ if not isinstance(incoming, int):+ # This file's premise is that upstream drift breaks loudly — the+ # texture-size patch raises on exactly this class of change. Silently+ # no-opping here would keep the render alive while discarding every bit+ # of the geometry the override exists to preserve.+ raise AdapterContractError(+ "to_glb was called without an integer decimation_target "+ f"(got {incoming!r}); upstream changed its bake call and the PortOS "+ "decimation override needs updating"+ )# Raise ANY lower target, rather than matching upstream's constant exactly.# An equality check against 200000 looked tighter but was silently fragile:# generate.py passes `min(200000, len(faces))`, so it already sends a smaller@@ -267,6 +277,17 @@ def _patch_capture_source_mesh():fast_simplification.simplify = simplify+def _require_texture_size(kwargs):+ """The atlas size `to_glb` was called with, or a loud failure."""+ size = kwargs.get("texture_size")+ if not isinstance(size, int):+ raise AdapterContractError(+ f"to_glb was called without an integer texture_size (got {size!r}); "+ "the PortOS normal-map bake cannot infer the atlas size"+ )+ return size++def _patch_normal_map(max_source_faces, verbose=True):"""Bake a tangent-space normal map onto the exported mesh after `to_glb`.@@ -287,8 +308,10 @@ def _patch_normal_map(max_source_faces, verbose=True):glb = original_to_glb(*args, **kwargs)source = _CAPTURED.get("source")if source is None:- print("[portos] normal map skipped - no pre-decimation mesh was captured "- "(the render never went through the simplify path)", flush=True)+ print("[portos] normal map skipped - the exported mesh IS the decoder mesh, "+ "so there is no discarded detail to recover (decimation no-opped "+ "because the decoded mesh was already at or under the target)",+ flush=True)return glbtry:# INSIDE the guard, deliberately. The bake module pulls numpy, torch,@@ -302,7 +325,10 @@ def _patch_normal_map(max_source_faces, verbose=True):glb,source[0],source[1],- texture_size=kwargs.get("texture_size", 2048),+ # No silent default: baking the normal map at a different size than+ # the base colour would misalign the atlas, and a wrong-but-plausible+ # map is worse than no map.+ texture_size=_require_texture_size(kwargs),max_source_faces=max_source_faces or DEFAULT_MAX_SOURCE_FACES,simplify=_CAPTURED.get("simplify"),verbose=verbose,