Skip to content

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

fix: stop keying image-to-3D sources by default, so RMBG-2.0 removes cast shadows (#4684)

[._.]/ Adam Eivy345f555e1647
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsx
index 225737f881..bd1e2db079 100644
--- a/client/src/components/media/ImageTo3dRenderOptions.jsx
+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx
@@ -23,6 +23,8 @@ import {
// - steps: '' = pipeline default, else a preset number string.
// - seed: '' = a fresh random seed every render; a value pins this run.
// - keyBackground: key a solid-color backdrop to transparency before render.
+// Off by default: writing an alpha channel makes the pipeline SKIP its own
+// learned matte, so keying is a downgrade on anything but a flat chroma backdrop.
// - detail: 'auto' = derive the pipeline tier from hardware, else a named tier.
// - alphaMode: '' = leave PortOS's force-opaque normalization on (the default);
// any explicit value turns it off so a transparent subject can stay transparent.
@@ -129,9 +131,14 @@ export default function ImageTo3dRenderOptions({
</FormField>
<div className="flex items-end pb-1.5">
<div className="flex flex-col gap-1.5">
+ {/* Opt-in, not default-on. Handing the pipeline an alpha channel makes it
+ skip its own learned matte, and a border flood fill can't remove a cast
+ shadow — which then becomes geometry. Only a flat chroma backdrop is
+ better keyed deterministically than matted. */}
<label
htmlFor="image-to-3d-key-background"
className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300"
+ title="For a source on a flat chroma backdrop (green/blue screen), where a deterministic key beats automatic matting. Leave off otherwise: keying replaces the model's own background removal, and a flood fill can't remove a cast shadow — which then gets built as geometry."
>
<input
id="image-to-3d-key-background"
@@ -141,7 +148,7 @@ export default function ImageTo3dRenderOptions({
disabled={disabled}
className="h-3.5 w-3.5 rounded border-port-border bg-port-bg accent-port-accent disabled:opacity-40"
/>
- Key out solid background
+ Key out flat backdrop
</label>
{/* 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
@@ -172,8 +179,9 @@ export default function ImageTo3dRenderOptions({
<span className="font-medium text-gray-400">Best source images:</span> one subject,
front or ¾ view, filling the frame, with no parts hidden behind others (tails, wings,
props) — the model has to guess anything it can’t see. A transparent PNG is used as-is;
- a solid-color backdrop is keyed out automatically when enabled here; busy backgrounds
- fall back to automatic matting, which can leave soft edges.
+ anything else is background-removed by the model itself, which also drops cast shadows.
+ Only turn on keying for a flat chroma backdrop — it replaces that automatic removal,
+ and a cast shadow it leaves behind gets built as geometry.
</p>
</div>
);
diff --git a/client/src/components/media/ImageTo3dRenderOptions.test.jsx b/client/src/components/media/ImageTo3dRenderOptions.test.jsx
index 2d0e2e8bd8..2dcb3a7a9a 100644
--- a/client/src/components/media/ImageTo3dRenderOptions.test.jsx
+++ b/client/src/components/media/ImageTo3dRenderOptions.test.jsx
@@ -35,7 +35,17 @@ describe('ImageTo3dRenderOptions', () => {
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', { name: /key out solid background/i })).toBeEnabled();
+ expect(screen.getByRole('checkbox', { name: /key out flat backdrop/i })).toBeEnabled();
+ });
+
+ // Off by default now: keying writes an alpha channel, which makes the pipeline skip
+ // its own learned matte (#4684). The control has to say what it is FOR, or nobody
+ // can tell when the non-default is the right choice.
+ it('says what the keying toggle is for, since it is no longer the common path', () => {
+ setup({ keyBackground: false });
+ const keying = screen.getByRole('checkbox', { name: /key out flat backdrop/i });
+ expect(keying).not.toBeChecked();
+ expect(keying.closest('label')).toHaveAttribute('title', expect.stringMatching(/chroma backdrop/i));
});
it('disables everything when the whole form is disabled', () => {
diff --git a/client/src/lib/imageTo3dRenderOptions.js b/client/src/lib/imageTo3dRenderOptions.js
index 908a0046ea..5f02880916 100644
--- a/client/src/lib/imageTo3dRenderOptions.js
+++ b/client/src/lib/imageTo3dRenderOptions.js
@@ -92,7 +92,10 @@ export function fieldsFromRun(run) {
return {
steps: Number.isInteger(run?.steps) ? String(run.steps) : '',
seed: '',
- keyBackground: typeof run?.keyBackground === 'boolean' ? run.keyBackground : true,
+ // A run predating the field has none; default to OFF, matching the server. Such a
+ // run DID key (the default was on then), but this seeds a NEW render's form, which
+ // should agree with the server default it will actually get.
+ keyBackground: typeof run?.keyBackground === 'boolean' ? run.keyBackground : false,
// Both carry over like `steps` does — they are deliberate quality choices, not
// per-run randomness. A run predating these fields has neither, so fall back to
// the same defaults a fresh form starts at.
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index 9e5a800298..58f0bc5b36 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -199,7 +199,7 @@ export default function Media3D() {
// Per-run sampler knobs (see ImageTo3dRenderOptions for the value conventions).
const [steps, setSteps] = useState('');
const [seed, setSeed] = useState('');
- const [keyBackground, setKeyBackground] = useState(true);
+ const [keyBackground, setKeyBackground] = useState(false);
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
const [normalMap, setNormalMap] = useState(false);
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index 9b43471054..773ca299fd 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -34,7 +34,7 @@ export default function Media3DDetail() {
// see fieldsFromRun.
const [steps, setSteps] = useState('');
const [seed, setSeed] = useState('');
- const [keyBackground, setKeyBackground] = useState(true);
+ const [keyBackground, setKeyBackground] = useState(false);
const [detail, setDetail] = useState('auto');
const [alphaMode, setAlphaMode] = useState('');
const [normalMap, setNormalMap] = useState(false);
diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
index 3ae11f1924..262f6025a4 100644
--- a/client/src/pages/Media3DDetail.test.jsx
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -99,7 +99,7 @@ describe('Media3DDetail', () => {
// normalMap is sent explicitly rather than omitted. It defaults OFF (the bake
// can lose a render outright), and stating it keeps the body honest about what
// the run asked for even if that default ever moves.
- { steps: 24, keyBackground: true, normalMap: false },
+ { steps: 24, keyBackground: false, normalMap: false },
{ silent: true },
));
});
@@ -117,7 +117,7 @@ describe('Media3DDetail', () => {
// Blank by design — echoing the run's concrete seed back would silently pin
// it, reintroducing the deterministic-re-render trap.
expect(screen.getByLabelText(/seed/i)).toHaveValue(null);
- expect(screen.getByLabelText(/key out solid background/i)).not.toBeChecked();
+ expect(screen.getByLabelText(/key out flat backdrop/i)).not.toBeChecked();
fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
@@ -147,7 +147,7 @@ describe('Media3DDetail', () => {
fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
'image3d-1',
- { keyBackground: true, detail: 'fast', alphaMode: 'auto', normalMap: false },
+ { keyBackground: false, detail: 'fast', alphaMode: 'auto', normalMap: false },
{ silent: true },
));
});
diff --git a/client/src/services/apiImageTo3d.js b/client/src/services/apiImageTo3d.js
index 41b3ba79f1..4a1d6d9503 100644
--- a/client/src/services/apiImageTo3d.js
+++ b/client/src/services/apiImageTo3d.js
@@ -23,7 +23,7 @@ export const createImageTo3dModel = (input, options) =>
// Re-run the render for an existing record (status → generating again).
// `input` carries the optional per-run knobs ({ steps, seed, keyBackground }) —
// they apply to this run only: absent steps → the pipeline default, absent
-// seed → the server rolls a fresh random one, absent keyBackground → enabled.
+// seed → the server rolls a fresh random one, absent keyBackground → no keying.
export const generateImageTo3dModel = (id, input = {}, options) =>
request(`/image-to-3d/models/${encodeURIComponent(id)}/generate`, {
method: 'POST',
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index 6af2724519..9ef236621a 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -27,7 +27,8 @@ const galleryFilenameSchema = z.string().trim().min(1).max(256)
// PER-RUN sampler knobs, shared by create and re-generate. Nothing persists
// between runs: absent steps → the pipeline default, absent seed → a fresh
-// random roll for that run, absent keyBackground → keying enabled.
+// random roll for that run, absent keyBackground → no keying (the pipeline's own
+// learned matte runs instead).
const renderOptionsSchema = z.object({
steps: z.number().int().min(RENDER_STEPS_MIN).max(RENDER_STEPS_MAX).optional(),
seed: z.number().int().min(0).max(RENDER_SEED_MAX).optional(),
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 1b3f613804..9d805b5058 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -158,12 +158,13 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio
let heavyClaim = null;
try {
await ensureDir(recordDir(id));
- // Key a solid background out of the source (into THIS record's render dir —
- // the shared gallery file is never touched) so the pipeline consumes a real
- // alpha channel instead of matting a green screen. Runs BEFORE the heavy-job
- // claim: it is CPU-only preprocessing, so other heavy jobs shouldn't queue
- // behind it and resident models shouldn't be evicted for it. Best-effort: a
- // keying failure must never fail a render the model could still attempt raw.
+ // Key a solid background out of the source (into THIS record's render dir — the
+ // shared gallery file is never touched). Opt-in, because handing the pipeline an
+ // alpha channel makes it consume that INSTEAD OF running its own learned matte —
+ // see sourceKeying.js. Runs BEFORE the heavy-job claim: it is CPU-only
+ // preprocessing, so other heavy jobs shouldn't queue behind it and resident models
+ // shouldn't be evicted for it. Best-effort: a keying failure must never fail a
+ // render the model could still attempt raw.
const keyedPath = keyBackground
? await prepareSourceImage({ sourcePath, targetPath: keyedSourcePath(id) })
.catch((err) => {
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index 9a27bea8dd..62eb5c1891 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -373,7 +373,7 @@ describe('render options and source keying', () => {
expect(generateArgs.seed).toBeLessThanOrEqual(2147483647);
// The run entry records the concrete values the subprocess received.
expect(current.runs.at(-1)).toMatchObject({
- seed: generateArgs.seed, steps: null, keyBackground: true,
+ seed: generateArgs.seed, steps: null, keyBackground: false,
});
});
@@ -419,7 +419,7 @@ describe('render options and source keying', () => {
it('a keyed source image is what the render consumes', async () => {
prepareSourceImage.mockImplementation(async ({ targetPath }) => targetPath);
- await createModel({ name: 'Beacon', filename: 'example.png' });
+ await createModel({ name: 'Beacon', filename: 'example.png', keyBackground: true });
await vi.waitFor(() => expect(current.status).toBe('ready'));
const [generateArgs] = runTrellis2Generate.mock.calls[0];
@@ -428,20 +428,29 @@ describe('render options and source keying', () => {
expect(current.runs.at(-1).sourceKeyed).toBe(true);
});
- it('keyBackground:false skips keying entirely', async () => {
- await createModel({ name: 'Beacon', filename: 'example.png', keyBackground: false });
+ // Keying writes an alpha channel, which makes TRELLIS.2 skip RMBG-2.0 — so the
+ // DEFAULT has to leave the source alone, or a cast shadow the flood fill can't
+ // reach survives into the mesh as geometry (#4684).
+ it.each([
+ ['omitted', {}],
+ ['explicitly false', { keyBackground: false }],
+ ])('keyBackground %s skips keying entirely', async (_label, options) => {
+ await createModel({ name: 'Beacon', filename: 'example.png', ...options });
await vi.waitFor(() => expect(current.status).toBe('ready'));
expect(prepareSourceImage).not.toHaveBeenCalled();
const [generateArgs] = runTrellis2Generate.mock.calls[0];
expect(posixPath(generateArgs.imagePath)).toBe('/mock/data/images/example.png');
expect(current.runs.at(-1).keyBackground).toBe(false);
+ // `sourceKeyed` stays truthful in BOTH directions — it records what the render
+ // consumed, not what was asked for.
+ expect(current.runs.at(-1).sourceKeyed).toBe(false);
});
it('a keying failure falls back to the raw source instead of failing the render', async () => {
prepareSourceImage.mockRejectedValue(new Error('unreadable image'));
- await createModel({ name: 'Beacon', filename: 'example.png' });
+ await createModel({ name: 'Beacon', filename: 'example.png', keyBackground: true });
await vi.waitFor(() => expect(current.status).toBe('ready'));
const [generateArgs] = runTrellis2Generate.mock.calls[0];
diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.js
index 86861bdb80..150672f415 100644
--- a/server/services/imageTo3d/renderOptions.js
+++ b/server/services/imageTo3d/renderOptions.js
@@ -17,6 +17,8 @@
* what every lane did before the knob existed.
* - `alphaMode: null` → don't instruct the exporter, and keep PortOS's
* force-opaque normalization.
+ * - `keyBackground: false` (the default) → hand the pipeline the untouched source
+ * so its own learned matte runs. Opt in only for a flat chroma backdrop.
* - `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.
@@ -98,7 +100,15 @@ export function normalizeRenderOptions(input = {}) {
return {
steps: isValidRenderSteps(input.steps) ? input.steps : null,
seed: isValidRenderSeed(input.seed) ? input.seed : null,
- keyBackground: input.keyBackground !== false,
+ // Opt-IN. Writing an alpha channel is not a free head start for the pipeline:
+ // TRELLIS.2's `preprocess_image` treats any non-opaque alpha as "already matted"
+ // and skips RMBG-2.0 entirely. So keying does not augment the learned matte, it
+ // REPLACES it with a border flood fill — which structurally cannot remove anything
+ // that isn't near the border color. A subject casting a shadow onto a surface keeps
+ // that shadow opaque, and the decoder reconstructs it as its own disconnected mass.
+ // `keySolidBackground` stays available for a synthetic image on a flat chroma
+ // backdrop, where the caller genuinely knows better than a segmentation model.
+ keyBackground: input.keyBackground === true,
// `detail` collapses to the explicit 'auto' sentinel rather than null: it is a
// choosable value, and a run entry recording 'auto' is what actually happened.
detail: isValidDetailTier(input.detail) ? input.detail : DEFAULT_DETAIL_TIER,
@@ -192,7 +202,7 @@ export function honorTargetRenderSupport(options, support) {
// 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`).
+ // sentinel happens to be (`null`, `'auto'`, or `false`).
const unset = normalizeRenderOptions();
const dropped = Object.fromEntries(
Object.entries(support)
diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.js
index 7e3ead2734..9d0cb6bb8b 100644
--- a/server/services/imageTo3d/renderOptions.test.js
+++ b/server/services/imageTo3d/renderOptions.test.js
@@ -17,18 +17,32 @@ import {
} from './renderOptions.js';
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: false });
- expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true, detail: 'auto', alphaMode: null, normalMap: false });
+ it('defaults to unset steps/seed with keying disabled', () => {
+ expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: false, 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: 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: false });
+ .toEqual({ steps: null, seed: null, keyBackground: false, 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: false });
+ .toEqual({ steps: null, seed: null, keyBackground: false, detail: 'auto', alphaMode: null, normalMap: false });
+ });
+
+ // Pinned on its own, not just as a field of a shape assertion, so flipping the
+ // default back is a deliberate test edit rather than a line noise diff. Keying
+ // writes an alpha channel, which makes TRELLIS.2's `preprocess_image` skip
+ // RMBG-2.0 — so default-on silently replaces a learned matte with a flood fill
+ // that cannot remove a cast shadow. See issue #4684.
+ it('leaves background keying OFF unless a run explicitly asks for it', () => {
+ expect(normalizeRenderOptions().keyBackground).toBe(false);
+ expect(normalizeRenderOptions({ keyBackground: undefined }).keyBackground).toBe(false);
+ expect(normalizeRenderOptions({ keyBackground: false }).keyBackground).toBe(false);
+ // Truthy-but-not-true must not enable it either — the wire value is a boolean.
+ expect(normalizeRenderOptions({ keyBackground: 'true' }).keyBackground).toBe(false);
+ expect(normalizeRenderOptions({ keyBackground: true }).keyBackground).toBe(true);
});
});
@@ -165,6 +179,13 @@ describe('honorTargetRenderSupport', () => {
.toEqual({ steps: null, seed: 7, keyBackground: true });
});
+ it('resets an unsupported knob to ITS OWN unset sentinel, not null', () => {
+ // keyBackground's sentinel is `false`, so a target that cannot key must record
+ // `false` — recording `null` would claim the subprocess got a value it never did.
+ expect(honorTargetRenderSupport(opts, { keyBackground: false }))
+ .toEqual({ steps: 24, seed: 7, keyBackground: false });
+ });
+
it('leaves a knob alone when support is explicitly true', () => {
expect(honorTargetRenderSupport(opts, { steps: true })).toEqual(opts);
});
diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.js
index 1b2757dda1..1626ea4d40 100644
--- a/server/services/imageTo3d/sourceKeying.js
+++ b/server/services/imageTo3d/sourceKeying.js
@@ -1,12 +1,19 @@
/**
* Solid-background keying for image-to-3D source images.
*
- * TRELLIS.2's own preprocessing uses a real alpha channel directly when one is
- * present and only falls back to RMBG-2.0 matting when there isn't — and matting a
- * flat green/blue screen is exactly where it produces soft, uncertain mattes (color
- * spill, fuzzy fur edges) that turn into hallucinated geometry. When the user's
- * source has NO alpha but sits on a detectably solid background, PortOS can key it
- * deterministically before the render and hand the pipeline a real alpha channel.
+ * OPT-IN, and deliberately so. TRELLIS.2's `preprocess_image` uses a real alpha
+ * channel directly when one is present and only falls back to RMBG-2.0 matting when
+ * there isn't — so keying a source does not *augment* the learned matte, it REPLACES
+ * it. That trade is a loss on any ordinary photo or render: a flood fill from the
+ * border cannot remove anything that isn't near the border color, so a cast shadow
+ * survives as opaque mid-grey and the decoder faithfully reconstructs it as its own
+ * disconnected mass of geometry. RMBG-2.0 removes it.
+ *
+ * What remains worth keying is the narrow case the caller knows and the segmentation
+ * model doesn't: a synthetic image on a flat chroma backdrop, where matting produces
+ * soft, uncertain edges (color spill, fuzzy fur) that turn into hallucinated geometry,
+ * and a deterministic key is strictly cleaner. Hence `keyBackground` defaults to
+ * false and this module runs only when a run asks for it.
*
* The pixel work is pure (raw RGBA buffers in/out) so it's unit-testable on tiny
* synthetic images; `prepareSourceImage` is the one sharp/file boundary. The keyed