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

feat([issue-3483]): explode + part picking in the Three.js model preview

[._.]/ Adam Eivyce89570c5d40
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9f9fc7fcc9..c867466b8c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -73,3 +73,7 @@
- **`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.
- **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).
+
+## Three.js Models
+
+- **[issue-3483] Take a generated model apart and click any piece to find out what it is.** The preview used to render a finished model as one inert lump — the only way to check it was actually built from parts, rather than fused into a single shape, was to export the source and read it. An Explode slider now separates the assembly, and clicking any surface names the part it belongs to and lights up that whole component. Separation scales the layout outward from the model's centre instead of shoving every piece the same distance, so parts that were touching genuinely come apart, pieces sitting at the centre still clear their neighbours, and the camera re-frames to whatever the disassembly actually grew to. Surface detail — serrations, stria, trim, port floors — rides the part it belongs to instead of shattering into loose slivers, and clicking it selects that part; models are now generated with that distinction marked, and exported models carry it too.
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index ad1e8e2928..d4a3c96681 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -1,12 +1,16 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useId, useMemo, useState } from 'react';
import { Canvas } from '@react-three/fiber';
-import { Bounds, OrbitControls } from '@react-three/drei';
+import { Bounds, OrbitControls, useBounds } from '@react-three/drei';
import * as THREE from 'three';
import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from '../../lib/threejsSculpt';
+import { buildPartSelectionIndex, computeExplodeLayout } from '../../lib/threejsExplode';
const radians = (degrees = 0) => THREE.MathUtils.degToRad(degrees);
const rotation = (degrees = [0, 0, 0]) => degrees.map(radians);
+const HIGHLIGHT_COLOR = '#38bdf8';
+const HIGHLIGHT_EMISSIVE_INTENSITY = 0.9;
+
const BACKGROUND_PRESETS = [
{ id: 'black', label: 'Black', value: '#000000' },
{ id: 'white', label: 'White', value: '#ffffff' },
@@ -55,34 +59,73 @@ function Geometry({ definition }) {
}
}
-function Material({ definition }) {
+function Material({ definition, highlighted = false }) {
const props = sculptMaterialProps(definition);
- if (definition.type === 'basic') return <meshBasicMaterial {...props} />;
- if (definition.type === 'physical') return <meshPhysicalMaterial {...props} />;
- return <meshStandardMaterial {...props} />;
+ // Basic materials are unlit and have no emissive channel, so the only way to
+ // show them as selected is the base color.
+ if (definition.type === 'basic') {
+ return <meshBasicMaterial {...props} color={highlighted ? HIGHLIGHT_COLOR : props.color} />;
+ }
+ const lit = highlighted
+ ? { ...props, emissive: HIGHLIGHT_COLOR, emissiveIntensity: HIGHLIGHT_EMISSIVE_INTENSITY }
+ : props;
+ if (definition.type === 'physical') return <meshPhysicalMaterial {...lit} />;
+ return <meshStandardMaterial {...lit} />;
}
-function Part({ part, materials }) {
+
+const offsetPosition = (position = [0, 0, 0], offset) =>
+ (offset ? position.map((value, axis) => value + offset[axis]) : position);
+
+function Part({ part, materials, offsets, selection, selectedId, onSelect }) {
const transform = {
name: part.name,
- position: part.position,
+ position: offsetPosition(part.position, offsets[part.id]),
rotation: rotation(part.rotationDegrees),
scale: part.scale,
};
+ // The whole selected subtree lights up, so selecting a container reads as one
+ // component rather than one lonely mesh inside it.
+ const highlighted = Boolean(selectedId) && (selection.ancestry[part.id] || []).includes(selectedId);
+ const select = (event) => {
+ // Without this the ray keeps going and every part behind the click selects too.
+ event.stopPropagation();
+ onSelect(selection.owners[part.id] || part.id);
+ };
return (
<group {...transform}>
{part.geometry && (
- <mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow}>
+ <mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow} onPointerDown={select}>
<Geometry definition={part.geometry} />
- <Material definition={materials[part.material]} />
+ <Material definition={materials[part.material]} highlighted={highlighted} />
</mesh>
)}
{part.children.map((child) => (
- <Part key={child.id} part={child} materials={materials} />
+ <Part
+ key={child.id}
+ part={child}
+ materials={materials}
+ offsets={offsets}
+ selection={selection}
+ selectedId={selectedId}
+ onSelect={onSelect}
+ />
))}
</group>
);
}
+// <Bounds> only measures its children when it is told to. Exploding moves parts
+// without remounting anything, so re-fit whenever the layout ACTUALLY grew —
+// measured from the moved parts, not guessed from the slider — and the camera
+// frames the disassembly instead of clipping it.
+function ExplodeRefit({ growth }) {
+ const bounds = useBounds();
+ useEffect(() => {
+ bounds?.refresh().clip().fit();
+ }, [bounds, growth]);
+ return null;
+}
+
function SceneLight({ light }) {
if (light.type === 'ambient') {
return <ambientLight color={light.color} intensity={light.intensity} />;
@@ -108,14 +151,26 @@ function SceneLight({ light }) {
return <directionalLight color={light.color} intensity={light.intensity} position={light.position} castShadow />;
}
-function ProceduralScene({ spec, background }) {
+function ProceduralScene({ spec, background, layout, selection, selectedId, onSelect }) {
return (
<>
{background && <color attach="background" args={[background]} />}
{spec.lights.map((light, index) => <SceneLight key={`${light.type}-${index}`} light={light} />)}
<Bounds fit clip observe margin={1.25}>
- <group name={spec.name}>
- {spec.parts.map((part) => <Part key={part.id} part={part} materials={spec.materials} />)}
+ <ExplodeRefit growth={layout.growth} />
+ {/* Clicking past the model clears the selection, the way a file list does. */}
+ <group name={spec.name} onPointerMissed={() => onSelect(null)}>
+ {spec.parts.map((part) => (
+ <Part
+ key={part.id}
+ part={part}
+ materials={spec.materials}
+ offsets={layout.offsets}
+ selection={selection}
+ selectedId={selectedId}
+ onSelect={onSelect}
+ />
+ ))}
</group>
</Bounds>
<gridHelper args={[20, 20, '#4b5563', '#252b38']} position={[0, -0.01, 0]} />
@@ -133,11 +188,23 @@ function ProceduralScene({ spec, background }) {
export default function ThreejsModelPreview({ spec, className = '' }) {
const [background, setBackground] = useState(() => spec?.background || '#000000');
+ const [explode, setExplode] = useState(0);
+ const [selectedId, setSelectedId] = useState(null);
+ const explodeSliderId = useId();
useEffect(() => {
setBackground(spec?.background || '#000000');
+ // A new model has different parts — a carried-over selection or explode
+ // amount would point at geometry that no longer exists.
+ setExplode(0);
+ setSelectedId(null);
}, [spec]);
+ const parts = spec?.parts;
+ const selection = useMemo(() => buildPartSelectionIndex(parts || []), [parts]);
+ const layout = useMemo(() => computeExplodeLayout(parts || [], explode), [parts, explode]);
+ const handleSelect = useCallback((partId) => setSelectedId(partId || null), []);
+
if (!spec) {
return (
<div className={`flex items-center justify-center bg-port-bg text-gray-500 ${className}`}>
@@ -159,7 +226,14 @@ export default function ThreejsModelPreview({ spec, className = '' }) {
dpr={[1, 2]}
gl={{ alpha: transparent }}
>
- <ProceduralScene spec={spec} background={background} />
+ <ProceduralScene
+ spec={spec}
+ background={background}
+ layout={layout}
+ selection={selection}
+ selectedId={selectedId}
+ onSelect={handleSelect}
+ />
</Canvas>
<div className="always-dark absolute left-2 top-2 flex max-w-[calc(100%-1rem)] flex-wrap items-center gap-1.5 rounded-lg bg-black/70 px-2 py-1.5 text-[10px] text-gray-300 backdrop-blur-sm">
<span className="mr-1 whitespace-nowrap text-gray-400">Background</span>
@@ -187,9 +261,48 @@ export default function ThreejsModelPreview({ spec, className = '' }) {
className="h-4 w-5 rounded border-0 bg-transparent p-0"
/>
</label>
+ <span className="mx-1 hidden h-3 w-px bg-white/20 sm:block" />
+ <label htmlFor={explodeSliderId} className="whitespace-nowrap text-gray-400">
+ Explode
+ </label>
+ <input
+ id={explodeSliderId}
+ type="range"
+ min="0"
+ max="1"
+ step="0.02"
+ value={explode}
+ disabled={layout.unitIds.length < 2}
+ onChange={(event) => setExplode(Number(event.target.value))}
+ className="h-1 w-20 cursor-pointer accent-port-accent disabled:cursor-not-allowed disabled:opacity-40 sm:w-28"
+ />
+ <span className="w-8 tabular-nums text-gray-400">{Math.round(explode * 100)}%</span>
+ {explode > 0 && (
+ <button
+ type="button"
+ onClick={() => setExplode(0)}
+ className="rounded px-1.5 py-1 hover:bg-white/15"
+ >
+ Reassemble
+ </button>
+ )}
</div>
+ {selectedId && (
+ <div className="always-dark absolute right-2 top-2 flex max-w-[calc(100%-1rem)] items-center gap-2 rounded-lg bg-black/70 px-2 py-1.5 text-[10px] text-gray-200 backdrop-blur-sm">
+ <span className="truncate font-medium text-white">{selection.names[selectedId] || selectedId}</span>
+ <code className="truncate text-gray-400">{selectedId}</code>
+ <button
+ type="button"
+ aria-label="Clear part selection"
+ onClick={() => setSelectedId(null)}
+ className="rounded px-1.5 py-0.5 hover:bg-white/15"
+ >
+ Clear
+ </button>
+ </div>
+ )}
<div className="always-dark pointer-events-none absolute bottom-2 left-2 rounded bg-black/60 px-2 py-1 text-[10px] text-gray-300">
- Drag to orbit · scroll to zoom
+ Drag to orbit · scroll to zoom · click a part to identify it
</div>
</div>
);
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
index b71d6cbf76..0c2802cd13 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
@@ -1,11 +1,21 @@
import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@react-three/fiber', () => ({
Canvas: ({ children, ...props }) => <div data-testid="threejs-canvas" data-alpha={String(props.gl?.alpha)}>{children}</div>,
}));
+// A chainable stand-in for drei's Bounds api, so the explode re-fit is
+// observable without a real renderer.
+const boundsApi = vi.hoisted(() => {
+ const api = {};
+ api.refresh = vi.fn(() => api);
+ api.clip = vi.fn(() => api);
+ api.fit = vi.fn(() => api);
+ return api;
+});
vi.mock('@react-three/drei', () => ({
Bounds: ({ children }) => children,
+ useBounds: () => boundsApi,
OrbitControls: () => null,
}));
@@ -58,7 +68,7 @@ const material = (overrides) => ({
...overrides,
});
-const part = (id, geometry, materialId) => ({
+const part = (id, geometry, materialId, overrides = {}) => ({
id,
name: id,
geometry,
@@ -69,8 +79,14 @@ const part = (id, geometry, materialId) => ({
castShadow: true,
receiveShadow: true,
children: [],
+ ...overrides,
});
+const box = { type: 'box', width: 1, height: 1, depth: 1 };
+const positionOf = (container, name) =>
+ container.querySelector(`group[name="${name}"]`).getAttribute('position').split(',').map(Number);
+const setExplode = (value) => fireEvent.change(screen.getByLabelText('Explode'), { target: { value: String(value) } });
+
describe('ThreejsModelPreview', () => {
it('offers preset and custom preview backgrounds without changing the scene spec', () => {
render(<ThreejsModelPreview spec={SPEC} />);
@@ -149,3 +165,89 @@ describe('ThreejsModelPreview', () => {
expect(standard.getAttribute('transmission')).toBeNull();
});
});
+
+// A knife: one blade carrying surface relief that must not fly off on its own,
+// plus a separate handle so there is something to separate FROM.
+const knifeSpec = () => ({
+ ...SPEC,
+ materials: { steel: material() },
+ parts: [
+ part('blade', box, 'steel', {
+ name: 'Blade',
+ position: [-1, 0, 0],
+ children: [part('serrations', box, 'steel', { name: 'Serrations', position: [0, 0.5, 0], explodeWithParent: true })],
+ }),
+ part('handle', box, 'steel', { name: 'Handle', position: [1, 0, 0] }),
+ ],
+});
+
+describe('ThreejsModelPreview disassembly', () => {
+ beforeEach(() => {
+ boundsApi.fit.mockClear();
+ });
+
+ it('separates the parts by scaling the layout about the centre, keeping relief on its part', () => {
+ const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+
+ expect(positionOf(container, 'Blade')).toEqual([-1, 0, 0]);
+ expect(positionOf(container, 'Handle')).toEqual([1, 0, 0]);
+
+ setExplode(1);
+
+ // Assembled spread is ±1, so a full explode puts each part at ±(2 + clearance) —
+ // a real gap opens between them rather than the pair sliding together.
+ const [bladeX] = positionOf(container, 'Blade');
+ const [handleX] = positionOf(container, 'Handle');
+ expect(bladeX).toBeCloseTo(-2.18, 6);
+ expect(handleX).toBeCloseTo(2.18, 6);
+
+ // Relief rides the blade — its own transform never changes.
+ expect(positionOf(container, 'Serrations')).toEqual([0, 0.5, 0]);
+ });
+
+ it('re-fits the camera when the layout actually grows', () => {
+ render(<ThreejsModelPreview spec={knifeSpec()} />);
+ boundsApi.fit.mockClear();
+
+ setExplode(0.5);
+ expect(boundsApi.refresh).toHaveBeenCalled();
+ expect(boundsApi.fit).toHaveBeenCalledTimes(1);
+
+ // Same layout, no wasted re-fit.
+ setExplode(0.5);
+ expect(boundsApi.fit).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables the explode control when there is only one part to move', () => {
+ render(<ThreejsModelPreview spec={{ ...SPEC, materials: { steel: material() }, parts: [part('solo', box, 'steel')] }} />);
+ expect(screen.getByLabelText('Explode')).toBeDisabled();
+ });
+
+ it('resolves a click on surface relief up to the part it belongs to and highlights that subtree', () => {
+ const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+
+ expect(screen.queryByRole('button', { name: 'Clear part selection' })).not.toBeInTheDocument();
+
+ fireEvent.pointerDown(container.querySelector('group[name="Serrations"] mesh'));
+
+ // The sliver is not the answer — the blade it rides is.
+ expect(screen.getByText('Blade')).toBeInTheDocument();
+ expect(screen.getByText('blade')).toBeInTheDocument();
+
+ const highlighted = container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]');
+ // Blade + its relief light up together; the handle stays as authored.
+ expect(highlighted).toHaveLength(2);
+ expect(container.querySelector('group[name="Handle"] meshStandardMaterial').getAttribute('emissive')).toBe('#000000');
+ });
+
+ it('selects a plain part on its own and clears the selection', () => {
+ const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+
+ fireEvent.pointerDown(container.querySelector('group[name="Handle"] mesh'));
+ expect(screen.getByText('Handle')).toBeInTheDocument();
+ expect(container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]')).toHaveLength(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Clear part selection' }));
+ expect(container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]')).toHaveLength(0);
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 02263c0cde..2e453560b6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -163,6 +163,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
+| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — with offsets returned in each part's own parent space and `growth` measuring how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it, a part whose descendants carry the geometry is a container that is descended through, everything else is a leaf that moves and selects on its own. |
| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`. Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. |
| `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. |
| `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 7dc3b2bb46..72286043e4 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -130,6 +130,7 @@ export * from './streakGlyph.js';
export * from './syncCounts.js';
export * from './tabNotation.js';
export * from './terminalTheme.js';
+export * from './threejsExplode.js';
export * from './threejsSculpt.js';
export * from './tribe.js';
export * from './quotaBurnPatch.js';
diff --git a/client/src/lib/threejsExplode.js b/client/src/lib/threejsExplode.js
new file mode 100644
index 0000000000..438f392ec8
--- /dev/null
+++ b/client/src/lib/threejsExplode.js
@@ -0,0 +1,176 @@
+/**
+ * Disassembly + part-picking maths for the procedural sculpt spec
+ * (`server/lib/threejsModel.js`), shared by the Three.js Models preview.
+ *
+ * Explode and the picker MUST agree on what "a part" is — if they disagree,
+ * both are wrong (you separate one thing and select another). That single
+ * definition lives here:
+ *
+ * - A part flagged `explodeWithParent` is **surface relief** (serrations, stria,
+ * trim, port floors). It rides its parent: it never moves on its own, and a
+ * click on it resolves up to the part it belongs to. Without this, a
+ * disassembly shatters into a comb of loose slivers.
+ * - A part whose (non-relief) descendants carry the geometry is a **container**:
+ * it is descended through, and its children are the things that move.
+ * - Anything else that is not relief is a **leaf**: it moves as one rigid unit
+ * (with its relief) and selects on its own.
+ *
+ * Separation is a layout **scale about the model centre**, not a uniform outward
+ * push: pushing every part the same distance slides the arrangement without ever
+ * opening a gap between neighbours, so parts that touched still touch. Each
+ * unit's offset from the centre is scaled (≈2x at full explode) plus a base
+ * clearance, so parts sitting near the centre — where the scaling term vanishes —
+ * still separate.
+ */
+
+import * as THREE from 'three';
+
+/** Layout size at full explode, as a multiple of the assembled layout. */
+export const EXPLODE_LAYOUT_SCALE = 2;
+
+/** Extra separation at full explode, as a fraction of the assembled radius. */
+export const EXPLODE_BASE_CLEARANCE = 0.18;
+
+const EPSILON = 1e-9;
+const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
+
+const clamp01 = (value) => (Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0);
+const childrenOf = (part) => (Array.isArray(part?.children) ? part.children : []);
+
+/** Surface relief: rides its parent for both movement and selection. */
+export const isReliefPart = (part) => part?.explodeWithParent === true;
+
+// Relief is deliberately invisible here: a leaf whose only geometry-bearing
+// children are relief is still a leaf, because that relief moves with it.
+const carriesMovableGeometry = (part) => {
+ if (isReliefPart(part)) return false;
+ if (part?.geometry) return true;
+ return childrenOf(part).some(carriesMovableGeometry);
+};
+
+/** True when a part is descended through rather than moved as one unit. */
+export const isContainerPart = (part) => childrenOf(part).some(carriesMovableGeometry);
+
+const localMatrix = (part) => {
+ const position = new THREE.Vector3(...(part?.position || [0, 0, 0]));
+ const euler = new THREE.Euler(...(part?.rotationDegrees || [0, 0, 0]).map((degrees) => THREE.MathUtils.degToRad(degrees)));
+ const scale = new THREE.Vector3(...(part?.scale || [1, 1, 1]));
+ return new THREE.Matrix4().compose(position, new THREE.Quaternion().setFromEuler(euler), scale);
+};
+
+/**
+ * Walk the tree to the parts that actually move, carrying each one's model-space
+ * position and the parent basis its offset has to be expressed in (offsets are
+ * applied to the part's own `position`, which lives in parent space).
+ */
+const collectExplodeUnits = (parts) => {
+ const units = [];
+ const walk = (list, parentMatrix) => {
+ for (const part of list || []) {
+ if (isReliefPart(part)) continue;
+ const matrix = parentMatrix.clone().multiply(localMatrix(part));
+ if (isContainerPart(part)) {
+ walk(childrenOf(part), matrix);
+ continue;
+ }
+ units.push({
+ id: part.id,
+ position: new THREE.Vector3().setFromMatrixPosition(matrix),
+ parentMatrix,
+ });
+ }
+ };
+ walk(parts, new THREE.Matrix4());
+ return units;
+};
+
+// Parts stacked exactly on the centre have no outward direction of their own.
+// Spread them deterministically (Fibonacci sphere) so a symmetric model still
+// comes apart instead of every centre part translating together.
+const fallbackDirection = (index, count) => {
+ const y = count > 1 ? 1 - ((2 * index) / (count - 1)) : 0;
+ const radius = Math.sqrt(Math.max(0, 1 - (y * y)));
+ const theta = GOLDEN_ANGLE * index;
+ const direction = new THREE.Vector3(Math.cos(theta) * radius, y, Math.sin(theta) * radius);
+ return direction.lengthSq() > EPSILON ? direction.normalize() : new THREE.Vector3(0, 1, 0);
+};
+
+// A world-space delta becomes a parent-space delta through the inverse of the
+// parent's basis. A degenerate (zero-scaled) parent has no inverse — fall back
+// to the world delta rather than emitting NaN positions.
+const toParentSpace = (delta, parentMatrix) => {
+ const basis = new THREE.Matrix3().setFromMatrix4(parentMatrix);
+ if (Math.abs(basis.determinant()) < EPSILON) return delta.clone();
+ return delta.clone().applyMatrix3(basis.clone().invert());
+};
+
+/**
+ * Explode layout for a spec's parts at `amount` (0 assembled → 1 fully apart).
+ *
+ * Returns the per-part offsets to add to each unit's `position`, the ids of the
+ * units that moved, and `growth` — how much the layout actually grew, measured
+ * from the moved parts rather than guessed, so the camera can re-fit on real
+ * change instead of on every slider tick.
+ */
+export function computeExplodeLayout(parts, amount = 0) {
+ const units = collectExplodeUnits(parts);
+ const unitIds = units.map((unit) => unit.id);
+ const progress = clamp01(amount);
+ // One unit has nothing to separate from, and any offset would just translate
+ // the whole model out of frame.
+ if (progress <= 0 || units.length < 2) return { offsets: {}, unitIds, growth: 1 };
+
+ const box = new THREE.Box3();
+ for (const unit of units) box.expandByPoint(unit.position);
+ const centre = box.getCenter(new THREE.Vector3());
+ const assembledRadius = units.reduce((max, unit) => Math.max(max, unit.position.distanceTo(centre)), 0);
+
+ const offsets = {};
+ let explodedRadius = 0;
+ units.forEach((unit, index) => {
+ const delta = unit.position.clone().sub(centre);
+ const distance = delta.length();
+ const direction = distance > EPSILON ? delta.clone().divideScalar(distance) : fallbackDirection(index, units.length);
+ // Scale the offset about the centre (the term that opens gaps between
+ // neighbours), then add the clearance that covers parts at the centre.
+ const scaled = distance * (EXPLODE_LAYOUT_SCALE - 1) * progress;
+ const clearance = (assembledRadius || 1) * EXPLODE_BASE_CLEARANCE * progress;
+ const worldOffset = direction.multiplyScalar(scaled + clearance);
+ explodedRadius = Math.max(explodedRadius, unit.position.clone().add(worldOffset).distanceTo(centre));
+ offsets[unit.id] = toParentSpace(worldOffset, unit.parentMatrix).toArray();
+ });
+
+ return {
+ offsets,
+ unitIds,
+ growth: assembledRadius > EPSILON ? explodedRadius / assembledRadius : 1,
+ };
+}
+
+/**
+ * Flatten the part tree into the lookups the picker needs.
+ *
+ * - `owners[id]` — the part a click on `id` selects: itself, or the nearest
+ * non-relief ancestor when `id` is surface relief.
+ * - `ancestry[id]` — root-to-self id chain, so "is this part inside the
+ * selection?" (subtree highlight) is a membership test.
+ * - `names[id]` — readable part name for the selection label.
+ */
+export function buildPartSelectionIndex(parts) {
+ const owners = {};
+ const ancestry = {};
+ const names = {};
+ const walk = (list, chain, owner) => {
+ for (const part of list || []) {
+ if (!part?.id) continue;
+ const selfChain = [...chain, part.id];
+ const selfOwner = isReliefPart(part) ? (owner ?? part.id) : part.id;
+ owners[part.id] = selfOwner;
+ ancestry[part.id] = selfChain;
+ names[part.id] = part.name || part.id;
+ walk(childrenOf(part), selfChain, selfOwner);
+ }
+ };
+ walk(parts, [], null);
+ return { owners, ancestry, names };
+}
diff --git a/client/src/lib/threejsExplode.test.js b/client/src/lib/threejsExplode.test.js
new file mode 100644
index 0000000000..222c7daf63
--- /dev/null
+++ b/client/src/lib/threejsExplode.test.js
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildPartSelectionIndex,
+ computeExplodeLayout,
+ EXPLODE_BASE_CLEARANCE,
+ EXPLODE_LAYOUT_SCALE,
+ isContainerPart,
+ isReliefPart,
+} from './threejsExplode.js';
+
+const part = (id, overrides = {}) => ({
+ id,
+ name: `${id} name`,
+ geometry: { type: 'box', width: 1, height: 1, depth: 1 },
+ material: 'body',
+ position: [0, 0, 0],
+ rotationDegrees: [0, 0, 0],
+ scale: [1, 1, 1],
+ children: [],
+ ...overrides,
+});
+
+const offsetOf = (layout, id) => layout.offsets[id] || [0, 0, 0];
+const magnitude = ([x, y, z]) => Math.sqrt((x * x) + (y * y) + (z * z));
+
+describe('the shared part definition', () => {
+ it('treats a geometry-bearing part with only relief children as a leaf that moves on its own', () => {
+ const blade = part('blade', {
+ children: [part('serrations', { explodeWithParent: true })],
+ });
+
+ expect(isReliefPart(blade)).toBe(false);
+ expect(isReliefPart(blade.children[0])).toBe(true);
+ // Relief rides its parent, so it never turns that parent into a container.
+ expect(isContainerPart(blade)).toBe(false);
+ expect(computeExplodeLayout([blade], 0).unitIds).toEqual(['blade']);
+ });
+
+ it('descends through a part whose children carry the geometry', () => {
+ const rig = part('rig', {
+ geometry: undefined,
+ material: undefined,
+ children: [part('left'), part('right')],
+ });
+
+ expect(isContainerPart(rig)).toBe(true);
+ expect(computeExplodeLayout([rig], 0).unitIds).toEqual(['left', 'right']);
+ });
+});
+
+describe('buildPartSelectionIndex', () => {
+ it('resolves a click on surface relief up to the part it belongs to', () => {
+ const { owners, names } = buildPartSelectionIndex([
+ part('blade', {
+ children: [
+ part('serrations', {
+ explodeWithParent: true,
+ children: [part('serrationTips', { explodeWithParent: true })],
+ }),
+ ],
+ }),
+ ]);
+
+ expect(owners.blade).toBe('blade');
+ expect(owners.serrations).toBe('blade');
+ // Relief nested under relief still resolves to the real part, not the sliver.
+ expect(owners.serrationTips).toBe('blade');
+ expect(names.serrations).toBe('serrations name');
+ });
+
+ it('keeps a non-relief child selectable in its own right', () => {
+ const { owners, ancestry } = buildPartSelectionIndex([
+ part('body', { children: [part('handle')] }),
+ ]);
+
+ expect(owners.handle).toBe('handle');
+ expect(ancestry.handle).toEqual(['body', 'handle']);
+ // Subtree highlight is an ancestry membership test.
+ expect(ancestry.handle.includes('body')).toBe(true);
+ expect(ancestry.body.includes('handle')).toBe(false);
+ });
+
+ it('falls back to the part id when a part has no readable name', () => {
+ const { names } = buildPartSelectionIndex([part('bolt', { name: '' })]);
+ expect(names.bolt).toBe('bolt');
+ });
+});
+
+describe('computeExplodeLayout', () => {
+ it('leaves the model assembled at amount 0', () => {
+ const layout = computeExplodeLayout([part('left', { position: [-1, 0, 0] }), part('right', { position: [1, 0, 0] })], 0);
+ expect(layout.offsets).toEqual({});
+ expect(layout.growth).toBe(1);
+ });
+
+ it('scales the layout about the model centre instead of pushing every part the same distance', () => {
+ // Three parts strung along X. A uniform outward push would move the outer
+ // two by the same amount and never open the gap the middle one sits in.
+ const layout = computeExplodeLayout([
+ part('near', { position: [0, 0, 0] }),
+ part('middle', { position: [1, 0, 0] }),
+ part('far', { position: [4, 0, 0] }),
+ ], 1);
+
+ const near = magnitude(offsetOf(layout, 'near'));
+ const middle = magnitude(offsetOf(layout, 'middle'));
+ const far = magnitude(offsetOf(layout, 'far'));
+
+ // Centre is x=2, assembled radius 2: displacement grows with distance from
+ // the centre rather than being one shared step.
+ expect(far).toBeCloseTo((2 * (EXPLODE_LAYOUT_SCALE - 1)) + (2 * EXPLODE_BASE_CLEARANCE), 6);
+ expect(middle).toBeCloseTo((1 * (EXPLODE_LAYOUT_SCALE - 1)) + (2 * EXPLODE_BASE_CLEARANCE), 6);
+ expect(far).toBeGreaterThan(middle);
+ expect(near).toBeCloseTo(far, 6);
+ // Directions stay opposite about the centre.
+ expect(offsetOf(layout, 'near')[0]).toBeLessThan(0);
+ expect(offsetOf(layout, 'far')[0]).toBeGreaterThan(0);
+ });
+
+ it('doubles the assembled spread at full explode', () => {
+ const parts = [part('left', { position: [-1, 0, 0] }), part('right', { position: [1, 0, 0] })];
+ const layout = computeExplodeLayout(parts, 1);
+
+ const rightX = 1 + offsetOf(layout, 'right')[0];
+ expect(rightX).toBeCloseTo(EXPLODE_LAYOUT_SCALE + EXPLODE_BASE_CLEARANCE, 6);
+ expect(layout.growth).toBeCloseTo(EXPLODE_LAYOUT_SCALE + EXPLODE_BASE_CLEARANCE, 6);
+ });
+
+ it('interpolates with the slider amount and clamps out-of-range values', () => {
+ const parts = [part('left', { position: [-1, 0, 0] }), part('right', { position: [1, 0, 0] })];
+ const half = magnitude(offsetOf(computeExplodeLayout(parts, 0.5), 'right'));
+ const full = magnitude(offsetOf(computeExplodeLayout(parts, 1), 'right'));
+
+ expect(half).toBeCloseTo(full / 2, 6);
+ expect(magnitude(offsetOf(computeExplodeLayout(parts, 5), 'right'))).toBeCloseTo(full, 6);
+ expect(computeExplodeLayout(parts, Number.NaN).offsets).toEqual({});
+ });
+
+ it('separates a part sitting on the centre, where the scaling term vanishes', () => {
+ const layout = computeExplodeLayout([
+ part('left', { position: [-1, 0, 0] }),
+ part('core', { position: [0, 0, 0] }),
+ part('right', { position: [1, 0, 0] }),
+ ], 1);
+
+ // Distance from the centre is 0, so only the base clearance can move it —
+ // without that, the core stays buried between its neighbours.
+ expect(magnitude(offsetOf(layout, 'core'))).toBeCloseTo(EXPLODE_BASE_CLEARANCE, 6);
+ });
+
+ it('spreads coincident centre parts in different directions', () => {
+ const layout = computeExplodeLayout([
+ part('stackA', { position: [0, 0, 0] }),
+ part('stackB', { position: [0, 0, 0] }),
+ part('stackC', { position: [0, 0, 0] }),
+ ], 1);
+
+ const directions = ['stackA', 'stackB', 'stackC'].map((id) => offsetOf(layout, id).join(','));
+ expect(new Set(directions).size).toBe(3);
+ for (const id of ['stackA', 'stackB', 'stackC']) {
+ expect(magnitude(offsetOf(layout, id))).toBeGreaterThan(0);
+ }
+ });
+
+ it('never moves relief off the part it rides', () => {
+ const layout = computeExplodeLayout([
+ part('blade', { position: [-1, 0, 0], children: [part('serrations', { position: [0, 0.5, 0], explodeWithParent: true })] }),
+ part('handle', { position: [1, 0, 0] }),
+ ], 1);
+
+ expect(layout.unitIds).toEqual(['blade', 'handle']);
+ expect(layout.offsets.serrations).toBeUndefined();
+ expect(layout.offsets.blade).toBeDefined();
+ });
+
+ it('expresses a nested part offset in its own parent space', () => {
+ const layout = computeExplodeLayout([
+ part('rig', {
+ geometry: undefined,
+ material: undefined,
+ scale: [2, 2, 2],
+ children: [part('a', { position: [1, 0, 0] }), part('b', { position: [-1, 0, 0] })],
+ }),
+ ], 1);
+
+ // `a` sits at world x=2 under a 2x-scaled parent. The world displacement is
+ // 2.36, so the offset added to its own `position` must be half that.
+ expect(offsetOf(layout, 'a')[0]).toBeCloseTo(((2 * (EXPLODE_LAYOUT_SCALE - 1)) + (2 * EXPLODE_BASE_CLEARANCE)) / 2, 6);
+ expect(layout.offsets.rig).toBeUndefined();
+ });
+
+ it('does nothing for a model with a single moving part', () => {
+ const layout = computeExplodeLayout([part('solo', { position: [3, 0, 0] })], 1);
+ expect(layout.offsets).toEqual({});
+ expect(layout.unitIds).toEqual(['solo']);
+ expect(layout.growth).toBe(1);
+ });
+
+ it('tolerates a missing or empty part list', () => {
+ expect(computeExplodeLayout(undefined, 1).unitIds).toEqual([]);
+ expect(computeExplodeLayout([], 1).offsets).toEqual({});
+ expect(buildPartSelectionIndex(undefined).owners).toEqual({});
+ });
+});
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 1642ef3421..03b9f0fb13 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -275,6 +275,11 @@ partSchema = z.lazy(() => z.object({
scale: vec3Schema.default([1, 1, 1]),
castShadow: z.boolean().default(true),
receiveShadow: z.boolean().default(true),
+ // Surface relief (serrations, stria, trim, port floors) belongs TO a part
+ // rather than being one: it rides its parent when the model is taken apart,
+ // and a click on it selects the parent. Without the flag a disassembly
+ // shatters into a comb of loose slivers nobody can read or pick.
+ explodeWithParent: z.boolean().default(false),
children: z.array(partSchema).max(40).default([]),
}));
@@ -489,6 +494,10 @@ function createPart(definition, materials, nodes) {
node.scale.set(...definition.scale);
node.castShadow = definition.castShadow;
node.receiveShadow = definition.receiveShadow;
+ // Carried through so a standalone consumer of the exported factory can build
+ // the same disassembly the PortOS preview does: relief rides its parent.
+ node.userData.partId = definition.id;
+ node.userData.explodeWithParent = definition.explodeWithParent;
nodes[definition.id] = node;
for (const child of definition.children) node.add(createPart(child, materials, nodes));
return node;
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index a7e19a1888..9ddb230289 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -66,6 +66,21 @@ describe('threejsSculptSpecSchema', () => {
expect(parsed.parts[0].children[0].id).toBe('frontTrim');
});
+ it('defaults surface relief off and preserves an explicit flag', () => {
+ const spec = validSpec();
+ spec.parts[0].children[0].explodeWithParent = true;
+ const parsed = threejsSculptSpecSchema.parse(spec);
+ // A part is a component unless the model says it merely rides one.
+ expect(parsed.parts[0].explodeWithParent).toBe(false);
+ expect(parsed.parts[0].children[0].explodeWithParent).toBe(true);
+ });
+
+ it('rejects a non-boolean surface-relief flag', () => {
+ const spec = validSpec();
+ spec.parts[0].explodeWithParent = 'yes';
+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);
+ });
+
it('rejects unknown material and detail references', () => {
const spec = validSpec();
spec.parts[0].material = 'missing';
@@ -266,6 +281,17 @@ describe('buildThreejsFactorySource', () => {
expect(source).toContain('new THREE.MeshBasicMaterial(unlit)');
});
+ it('carries the surface-relief flag into part userData so an export can disassemble too', () => {
+ const spec = validSpec();
+ spec.parts[0].children[0].explodeWithParent = true;
+ const source = buildThreejsFactorySource(spec);
+ expect(source).toContain('node.userData.partId = definition.id;');
+ expect(source).toContain('node.userData.explodeWithParent = definition.explodeWithParent;');
+ // The serialized spec the factory closes over must carry the flag, not just
+ // the code that reads it.
+ expect(source).toContain('"explodeWithParent": true');
+ });
+
it('emits extrude, tube, and physical-channel construction', () => {
const spec = validSpec();
spec.parts[0].geometry = validExtrude();
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index d0bf1e2f49..abc75d8b79 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -57,6 +57,7 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
"material":"materialId",
"position":[x,y,z],"rotationDegrees":[x,y,z],"scale":[x,y,z],
"castShadow":true,"receiveShadow":true,
+ "explodeWithParent":false,
"children":[ ...same part shape... ]
}],
"sockets": [{"name":"socketName","parentPartId":"partId","position":[x,y,z],"rotationDegrees":[x,y,z]}],
@@ -99,7 +100,7 @@ WORKFLOW:
1. Inspect the image before deciding geometry.
2. Classify the subject as object, character, or hybrid.
3. Inventory every identity-defining visible detail: silhouette, proportions, bevels/rounding, seams, trim, controls, fasteners, facial landmarks, limbs, wear, gloss, emissive regions, and attachment points.
-4. Build from a clear parent/child hierarchy. Put moving or attachable pieces in their own named parts. Add sockets for meaningful pivots/attachments.
+4. Build from a clear parent/child hierarchy. Put moving or attachable pieces in their own named parts. Add sockets for meaningful pivots/attachments. Set "explodeWithParent":true on surface relief — serrations, stria, ridges, trim, engraving, port floors, panel lines and other detail that belongs TO a part rather than being a part — so the viewer takes the model apart into readable components instead of a comb of loose slivers. Leave it false (the default) on anything a person would call a separate component.
5. Use primitive composition first, then the schema-backed extrude/tube/lathe forms for silhouettes, cutouts, and swept details. Use custom triangles only when no other allowed form can reproduce the shape.
6. Use physically coherent PBR material channels. Reach for "physical" with ior/transmission/thickness for glass, gems, liquid, and clear plastic, sheen for cloth and velvet, iridescence for oil-slick/soap-film/pearlescent finishes, and anisotropy for brushed metal or spun discs. Do not use textures, external meshes, URLs, downloaded assets, or JavaScript.
7. Center the subject near the origin, keep dimensions internally consistent, and choose a camera that frames the whole model.
@@ -108,6 +109,7 @@ WORKFLOW:
QUALITY GATE:
- A compound subject must not collapse into one primitive.
+- The model must come apart into readable components: every piece a person would name is its own part, and every detail that merely rides a surface carries "explodeWithParent":true.
- Major visible attachments may not float or be omitted.
- Identity-priority details must be represented by actual geometry/material choices.
- Do not spend custom triangles on a shape extrude, tube, or lathe already expresses.
diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.js
new file mode 100644
index 0000000000..b513dc0072
--- /dev/null
+++ b/server/services/threejsModels/prompt.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { buildThreejsGenerationPrompt } from './prompt.js';
+
+const build = (overrides = {}) => buildThreejsGenerationPrompt({
+ sourcePath: '/tmp/reference.png',
+ name: 'Example Model',
+ ...overrides,
+});
+
+describe('buildThreejsGenerationPrompt', () => {
+ it('documents the surface-relief flag in the parts shape and tells the model when to set it', () => {
+ const prompt = build();
+ // Undocumented, the flag is never emitted and every model disassembles into
+ // a comb of slivers.
+ expect(prompt).toContain('"explodeWithParent":false');
+ expect(prompt).toContain('"explodeWithParent":true on surface relief');
+ for (const relief of ['serrations', 'stria', 'trim', 'port floors']) {
+ expect(prompt).toContain(relief);
+ }
+ });
+
+ it('gates on the model coming apart into readable components', () => {
+ expect(build()).toContain('The model must come apart into readable components');
+ });
+
+ it('carries the reference path, name, and direction into the prompt', () => {
+ const prompt = build({ prompt: 'Match the brass finish.' });
+ expect(prompt).toContain('/tmp/reference.png');
+ expect(prompt).toContain('Example Model');
+ expect(prompt).toContain('Match the brass finish.');
+ });
+
+ it('switches to a refinement pass when a current spec is supplied', () => {
+ const prompt = build({ currentSpec: { schemaVersion: 1, name: 'Example Model' }, feedback: 'Thin the handle.' });
+ expect(prompt).toContain('This is a refinement pass');
+ expect(prompt).toContain('Thin the handle.');
+ expect(build()).not.toContain('This is a refinement pass');
+ });
+});