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: floor Three.js part scale at 1e-4 so a zero or negative component can't render a part inside-out (#3484)

[._.]/ Adam Eivyf2d725051e33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9f9fc7fcc9..fa2ad47ff5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -72,4 +72,6 @@
- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read, a destructure off a namespace handle, and the three deferred spellings of the same reaches — including `const { completeAgent } = await import('./cos.js')`, the exact pattern this change deleted. Each bypass-probed.
+- **A Three.js part could be scaled inside-out or flat to nothing, and the schema called it valid.** Every geometry dimension in the scene spec is bounded to a positive number, but `partSchema.scale` reused the plain `finite` triple — so a provider-authored `[1, -1, 1]` reversed the winding order and the part rendered inside-out (you see its far interior wall, lit from within, silhouette unchanged), while `[1, 0, 1]` collapsed it to an invisible plane. Both validated, both exported, and neither throws at render time, so the failure survives a color or silhouette check and is indistinguishable from a modeling choice in the preview — the debugging cycle it costs is spent looking anywhere but the number. `scale` now takes its own tuple floored at `1e-4`, so zero, negative, and near-degenerate components are all rejected with a `parts.N.scale.M` path, and the generation prompt states the bound alongside the parts shape rather than letting the model discover it through a rejected generation. Mirroring belongs in `rotationDegrees`, which is unbounded in sign and always was. Nothing in the pipeline computes a scale — the value only ever comes from the provider's JSON, and the schema is the only place it can be caught. Tightening an accepted range does strand specs an older install already stored, though: they are re-validated on export, so a model generated since v2.34.0 with a bad scale would have started 500ing the download button with no in-app remedy. DB migration 008 normalizes those rows first — a negative component takes its magnitude (the size was the intent, the sign was the bug), a zero rises to the floor rather than popping a hidden part back to full size — without bumping `updated_at`, since a derived repair should not reorder the models list (#3484).
+
- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar, and the fetched lists are dropped on close so a reopen can't filter fresh images against stale membership. Sidecars are unvalidated JSON that also arrive from peers, so a tag that isn't a usable string is skipped rather than crashing the render — which surfaced a latent bug in the shared `humanizeCategory`: its label lookup wasn't `hasOwn`-guarded, so a user-authored category keyed `constructor` or `toString` resolved to an inherited function and handed every caller a label that throws on the next string method (#3479).
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 1642ef3421..40868f8f80 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -15,6 +15,16 @@ const finite = z.number().finite().min(-10_000).max(10_000);
const positive = z.number().finite().positive().max(10_000);
const vec3Schema = z.tuple([finite, finite, finite]);
+// A part `scale` is a multiplier, never a mirror. A negative component reverses
+// the winding order, so the part renders inside-out — lit from within, silhouette
+// unchanged, nothing thrown — and a component at (or near) zero collapses it to an
+// invisible plane. Both are indistinguishable from a modeling choice in the preview,
+// so a plain `finite` triple lets either through as a silent normals/geometry bug.
+// Mirroring belongs in `rotationDegrees`.
+const MIN_PART_SCALE = 1e-4;
+const scaleComponent = positive.min(MIN_PART_SCALE);
+const scale3Schema = z.tuple([scaleComponent, scaleComponent, scaleComponent]);
+
const boxGeometrySchema = z.object({
type: z.literal('box'),
width: positive,
@@ -272,7 +282,7 @@ partSchema = z.lazy(() => z.object({
material: idSchema.optional(),
position: vec3Schema.default([0, 0, 0]),
rotationDegrees: vec3Schema.default([0, 0, 0]),
- scale: vec3Schema.default([1, 1, 1]),
+ scale: scale3Schema.default([1, 1, 1]),
castShadow: z.boolean().default(true),
receiveShadow: z.boolean().default(true),
children: z.array(partSchema).max(40).default([]),
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index a7e19a1888..6b58c6772c 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -110,6 +110,43 @@ describe('threejsSculptSpecSchema', () => {
});
});
+ it('defaults an omitted part scale to an untouched [1, 1, 1]', () => {
+ const spec = validSpec();
+ delete spec.parts[0].scale;
+ delete spec.parts[0].children[0].scale;
+ const parsed = threejsSculptSpecSchema.parse(spec);
+ expect(parsed.parts[0].scale).toEqual([1, 1, 1]);
+ expect(parsed.parts[0].children[0].scale).toEqual([1, 1, 1]);
+ });
+
+ // A negative component flips the winding order (the part renders inside-out) and a
+ // zero collapses it to an invisible plane — neither throws at render time, so the
+ // schema is the only place they can be caught.
+ it('rejects a negative or zero part scale component, at any depth', () => {
+ for (const bad of [[1, -1, 1], [1, 0, 1], [-1, -1, -1]]) {
+ const spec = validSpec();
+ spec.parts[0].scale = bad;
+ const result = threejsSculptSpecSchema.safeParse(spec);
+ expect(result.success).toBe(false);
+ expect(result.error.issues.some((issue) => issue.path.join('.') === 'parts.0.scale.1'
+ || issue.path.join('.') === 'parts.0.scale.0')).toBe(true);
+
+ const nested = validSpec();
+ nested.parts[0].children[0].scale = bad;
+ expect(threejsSculptSpecSchema.safeParse(nested).success).toBe(false);
+ }
+ });
+
+ it('rejects a near-zero part scale below the floor but accepts the floor itself', () => {
+ const tooSmall = validSpec();
+ tooSmall.parts[0].scale = [1, 5e-5, 1];
+ expect(threejsSculptSpecSchema.safeParse(tooSmall).success).toBe(false);
+
+ const atFloor = validSpec();
+ atFloor.parts[0].scale = [1, 1e-4, 1];
+ expect(threejsSculptSpecSchema.parse(atFloor).parts[0].scale).toEqual([1, 1e-4, 1]);
+ });
+
it('rejects out-of-range physical material channels', () => {
const spec = validSpec();
spec.materials.trim.ior = 4;
diff --git a/server/scripts/db-migrations/008-threejs-part-scale-positive.js b/server/scripts/db-migrations/008-threejs-part-scale-positive.js
new file mode 100644
index 0000000000..b17712989a
--- /dev/null
+++ b/server/scripts/db-migrations/008-threejs-part-scale-positive.js
@@ -0,0 +1,86 @@
+/**
+ * Repair non-positive `parts[].scale` components on Three.js model specs already
+ * in Postgres (#3484).
+ *
+ * `partSchema.scale` used to be a plain `finite` triple, so a provider-authored
+ * `[1, -1, 1]` validated and stored: a negative component reverses the winding
+ * order, which renders the part inside-out (lit from within, silhouette intact)
+ * rather than erroring, and `[1, 0, 1]` collapses it to an invisible plane. The
+ * schema now floors every component at 1e-4, which fixes new generations but
+ * would turn an already-stored spec into a hard parse failure the next time
+ * `buildThreejsFactorySource()` runs — i.e. the download button on a model an
+ * older install generated between v2.34.0 and now would start 500ing, with no
+ * in-app remedy short of regenerating. This normalizes those rows instead.
+ *
+ * The repair is deliberately conservative — it makes the stored spec
+ * representable without restyling the model:
+ * - a negative component takes its magnitude (`Math.abs`). The size was the
+ * intent; the sign was the normals bug, and dropping it un-flips the part.
+ * - a zero or sub-floor component is raised to the floor, which keeps it
+ * visually degenerate exactly as it renders today rather than popping a
+ * hidden part back to full size.
+ *
+ * The floor is a frozen point-in-time copy of `MIN_PART_SCALE` in
+ * `server/lib/threejsModel.js` rather than an import: a migration is a
+ * point-in-time transform and must not shift if that bound is later retuned.
+ *
+ * `updated_at` is deliberately NOT bumped — this is a derived normalization, not
+ * a user edit, and the models list orders by it. Three.js models are not
+ * federated (no `schemaVersions` entry, no peer-sync fan-out), so there is no LWW
+ * clock or checksum to disturb either.
+ *
+ * Tombstoned models are included: they can be restored, and a restored model
+ * should not be the one record whose export still throws.
+ *
+ * Idempotent: a spec whose scales are already positive is skipped, so a re-run
+ * writes nothing.
+ */
+
+const MIN_PART_SCALE = 1e-4;
+
+const repairComponent = (value) => {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return value;
+ return Math.max(Math.abs(value), MIN_PART_SCALE);
+};
+
+/**
+ * Rewrite one part subtree, returning the SAME reference when nothing changed so
+ * the caller can tell a repaired row from an untouched one.
+ */
+const repairPart = (part) => {
+ if (!part || typeof part !== 'object') return part;
+
+ const scale = Array.isArray(part.scale) ? part.scale.map(repairComponent) : part.scale;
+ const scaleChanged = Array.isArray(part.scale)
+ && scale.some((value, index) => value !== part.scale[index]);
+
+ const children = Array.isArray(part.children) ? part.children.map(repairPart) : part.children;
+ const childrenChanged = Array.isArray(part.children)
+ && children.some((child, index) => child !== part.children[index]);
+
+ if (!scaleChanged && !childrenChanged) return part;
+ return { ...part, scale, children };
+};
+
+export async function up(client) {
+ const { rows } = await client.query(
+ `SELECT id, data FROM threejs_models
+ WHERE jsonb_typeof(data->'spec'->'parts') = 'array'
+ AND jsonb_array_length(data->'spec'->'parts') > 0`,
+ );
+ let touched = 0;
+ for (const row of rows) {
+ const parts = row.data?.spec?.parts;
+ if (!Array.isArray(parts)) continue;
+ const repaired = parts.map(repairPart);
+ if (repaired.every((part, index) => part === parts[index])) continue;
+ await client.query(
+ `UPDATE threejs_models
+ SET data = jsonb_set(data, '{spec,parts}', $1::jsonb, false)
+ WHERE id = $2`,
+ [JSON.stringify(repaired), row.id],
+ );
+ touched += 1;
+ }
+ console.log(`🧊 three.js part scale: repaired ${touched} of ${rows.length} model${rows.length === 1 ? '' : 's'} with a scene spec`);
+}
diff --git a/server/scripts/db-migrations/008-threejs-part-scale-positive.test.js b/server/scripts/db-migrations/008-threejs-part-scale-positive.test.js
new file mode 100644
index 0000000000..f236c2ccec
--- /dev/null
+++ b/server/scripts/db-migrations/008-threejs-part-scale-positive.test.js
@@ -0,0 +1,98 @@
+import { describe, it, expect, vi } from 'vitest';
+import { up } from './008-threejs-part-scale-positive.js';
+import { threejsSculptSpecSchema } from '../../lib/threejsModel.js';
+
+const makeClient = (rows) => {
+ const updates = [];
+ const query = vi.fn(async (sql, params) => {
+ if (sql.startsWith('SELECT')) return { rows };
+ updates.push({ sql, params });
+ return { rows: [] };
+ });
+ return { client: { query }, updates };
+};
+
+const modelRow = (id, parts) => ({ id, data: { spec: { parts } } });
+
+describe('db-migration 008 — non-positive Three.js part scale', () => {
+ it('takes the magnitude of a negative component and floors a zero, writing only the parts path', async () => {
+ const { client, updates } = makeClient([
+ modelRow('threejs-a', [{ id: 'body', scale: [2, -3, 1], children: [{ id: 'trim', scale: [1, 0, 1], children: [] }] }]),
+ ]);
+
+ await up(client);
+
+ expect(updates).toHaveLength(1);
+ expect(updates[0].sql).toContain("jsonb_set(data, '{spec,parts}'");
+ // Never bumps updated_at — a derived normalization must not reorder the models list.
+ expect(updates[0].sql).not.toContain('updated_at');
+ expect(updates[0].params[1]).toBe('threejs-a');
+ const repaired = JSON.parse(updates[0].params[0]);
+ expect(repaired[0].scale).toEqual([2, 3, 1]);
+ expect(repaired[0].children[0].scale).toEqual([1, 1e-4, 1]);
+ });
+
+ it('writes nothing for specs whose scales are already positive (idempotent re-run)', async () => {
+ const { client, updates } = makeClient([
+ modelRow('threejs-b', [{ id: 'body', scale: [1, 1, 1], children: [{ id: 'trim', scale: [0.5, 2, 1e-4], children: [] }] }]),
+ ]);
+
+ await up(client);
+
+ expect(updates).toEqual([]);
+ });
+
+ it('leaves a part with no scale key alone', async () => {
+ const { client, updates } = makeClient([modelRow('threejs-c', [{ id: 'body', children: [] }])]);
+
+ await up(client);
+
+ expect(updates).toEqual([]);
+ });
+
+ it('skips a row whose spec parts are not an array', async () => {
+ const { client, updates } = makeClient([
+ { id: 'threejs-d', data: { spec: { parts: null } } },
+ { id: 'threejs-e', data: { spec: null } },
+ { id: 'threejs-f', data: {} },
+ ]);
+
+ await up(client);
+
+ expect(updates).toEqual([]);
+ });
+
+ it('produces parts the tightened schema now accepts', async () => {
+ const spec = {
+ schemaVersion: 1,
+ name: 'Example Beacon',
+ summary: 'A two-part beacon stored before the scale bound existed.',
+ subjectType: 'object',
+ background: '#111827',
+ camera: { position: [3, 2, 4], target: [0, 0, 0] },
+ materials: { shell: { type: 'standard', color: '#8b5a2b' } },
+ lights: [{ type: 'ambient', color: '#ffffff', intensity: 0.4 }],
+ parts: [{
+ id: 'shell',
+ name: 'Shell',
+ geometry: { type: 'box', width: 1, height: 1, depth: 1 },
+ material: 'shell',
+ scale: [1, -1, 0],
+ children: [],
+ }],
+ detailInventory: [{
+ feature: 'Ribbed shell',
+ evidence: 'Vertical ribs run the visible face.',
+ implementationPartIds: ['shell'],
+ }],
+ };
+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);
+
+ const { client, updates } = makeClient([{ id: 'threejs-g', data: { spec } }]);
+ await up(client);
+
+ spec.parts = JSON.parse(updates[0].params[0]);
+ const parsed = threejsSculptSpecSchema.parse(spec);
+ expect(parsed.parts[0].scale).toEqual([1, 1, 1e-4]);
+ });
+});
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index d0bf1e2f49..e58b750ce2 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -55,7 +55,7 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
"id":"stablePartId","name":"Readable part name",
"geometry": { ...one allowed geometry... },
"material":"materialId",
- "position":[x,y,z],"rotationDegrees":[x,y,z],"scale":[x,y,z],
+ "position":[x,y,z],"rotationDegrees":[x,y,z],"scale":[sx,sy,sz],
"castShadow":true,"receiveShadow":true,
"children":[ ...same part shape... ]
}],
@@ -67,6 +67,11 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
"priority":"identity" | "major" | "minor"
}]
}
+
+Every part "scale" component (sx, sy, sz) must be a strictly positive multiplier of at
+least 0.0001. Zero collapses the part to an invisible plane, and a negative component
+reverses the winding order so the part renders inside-out — both are rejected. Mirror a
+part with "rotationDegrees", never with a negative scale.
`;
export function buildThreejsGenerationPrompt({