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(threejs models): derive refinement feedback from declared clips and ship a playback helper in the export (#4542)

[._.]/ Adam Eivybe9f706a8989
diff --git a/client/src/lib/threejsAnimation.js b/client/src/lib/threejsAnimation.js
index 89d71429b4..a58f760dd3 100644
--- a/client/src/lib/threejsAnimation.js
+++ b/client/src/lib/threejsAnimation.js
@@ -22,6 +22,10 @@
* The schema guarantees the invariants this relies on (windows inside the clip,
* no two sequences on one part+channel at once, every `partId` real), so there
* is no conflict resolution here to get wrong.
+ *
+ * These semantics are MIRRORED by the player PortOS emits into an exported
+ * factory (`server/lib/threejsModelPlayerSource.js`), so a clip poses identically
+ * in the preview and in a consumer's own scene. Change one and change the other.
*/
import { EASING_CURVES, linear } from '../utils/easing.js';
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index effd2239ca..62adbd504b 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -409,6 +409,12 @@ export default function ThreejsModelDetail() {
const materialFindings = Array.isArray(record.materialPlausibility?.findings)
? record.materialPlausibility.findings
: null;
+ // Clip findings only mean something for a model that declared clips: a static
+ // assembly evaluates to an empty list, and rendering a clean "clip playback"
+ // panel on every static model would be noise about a feature it never used.
+ const animationFindings = Array.isArray(record.animation?.findings) && record.animation?.animated
+ ? record.animation.findings
+ : null;
// Undecided contact is a note the reader is meant to judge, never something a
// refinement is told to fix — so the footer only promises a refinement when
// there is an actual defect above it.
@@ -648,6 +654,19 @@ export default function ThreejsModelDetail() {
/>
)}
+ {animationFindings && (
+ <GatePanel
+ title="Clip playback"
+ findings={animationFindings}
+ cleanLabel="Clips open, hand over, and loop cleanly"
+ footer={`The schema already proves a clip is well formed, so this check asks whether it will actually play: a clip authored against a pose the assembly does not build jumps the instant it opens, a handover between sequences that do not meet jumps mid-clip, and a loop that ends somewhere else snaps on every repeat.${
+ animationFindings.length > 0
+ ? ' Refining without your own feedback will also ask for clips that start from the assembled pose and close their loops.'
+ : ''
+ }`}
+ />
+ )}
+
{record.spec?.detailInventory?.length > 0 && (
<section className="rounded-xl border border-port-border bg-port-card p-4">
<div className="mb-2 flex items-center justify-between">
diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsx
index 7d926e694e..8dce5ffa47 100644
--- a/client/src/pages/ThreejsModelDetail.test.jsx
+++ b/client/src/pages/ThreejsModelDetail.test.jsx
@@ -530,6 +530,41 @@ describe('ThreejsModelDetail clip inventory', () => {
expect(screen.getByText('1s · 1 sequence')).toBeInTheDocument();
});
+ it('renders the clip-playback gate for a model whose clips will not play cleanly', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ animation: {
+ animated: true,
+ clipCount: 1,
+ warningCount: 1,
+ clips: [{ id: 'deploy', name: 'Deploy', role: 'deploy', durationSeconds: 2, sequenceCount: 1, cueCount: 0 }],
+ findings: [{
+ code: 'clip-start-pose-mismatch',
+ severity: 'warning',
+ message: 'clip Deploy is authored against a pose the assembly does not build',
+ }],
+ },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Clip playback')).toBeInTheDocument());
+ expect(screen.getByText(/clip Deploy is authored against a pose/)).toBeInTheDocument();
+ expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
+ });
+
+ // A static assembly evaluates to an empty finding list, which is not a verdict
+ // about clips — it never declared any.
+ it('shows no clip-playback gate for a static assembly that was evaluated', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ animation: { animated: false, clipCount: 0, warningCount: 0, clips: [], findings: [] },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
+ expect(screen.queryByText('Clip playback')).not.toBeInTheDocument();
+ });
+
it('shows no clip panel for a static assembly', async () => {
getThreejsModel.mockResolvedValue({ ...baseRecord, animation: null });
renderDetail();
diff --git a/docs/THREEJS_MODELS.md b/docs/THREEJS_MODELS.md
index 08f4783b77..2590982f99 100644
--- a/docs/THREEJS_MODELS.md
+++ b/docs/THREEJS_MODELS.md
@@ -9,7 +9,8 @@ procedural Three.js scene with:
- a live in-browser orbit/zoom preview using PortOS's existing Three.js stack,
with explode-to-disassemble, click-to-identify part picking, and a timeline
for any animation clips the spec declares;
-- deterministic download/copy of a standalone `THREE.Group` factory;
+- deterministic download/copy of a standalone `THREE.Group` factory, with a
+ clip player over the same data;
- gallery-image lineage, run attribution, detail inventory, and honest
single-view limitations.
@@ -102,9 +103,64 @@ reason a cue is data rather than embedded audio. A cue may only ride a sequence
that changes position, rotation, or scale: a sound needs movement to
synchronize to, and the schema rejects one attached to a fade.
+### The playback gate
+
+The schema proves a clip is well *formed*; `summarizeThreejsAnimation()`
+(`server/lib/threejsModelAnimation.js`) reports the ways a well-formed clip
+still plays badly, as advisory `warning` findings stored on the record beside
+the clip inventory:
+
+- **`clip-start-pose-mismatch`** — the first sequence on a part+channel starts
+ from a pose the assembly does not build, so the model jumps the instant the
+ clip opens.
+- **`clip-sequence-jump`** — a following sequence starts somewhere other than
+ where the previous one on that channel ended.
+- **`loop-does-not-close`** — a `loop: true` clip whose end pose differs from
+ its start pose, so it snaps on every repeat.
+- **`idle-clip-does-not-loop`** — a role `idle` clip authored as a one-shot.
+- **`unfired-cue`** — a declared cue no sequence fires.
+- **`clip-holds-still`** — motion finishes in the first half of the window with
+ more than 1.5s of dead tail left.
+- **`articulation-without-clips`** — a spec with a real articulation graph (2+
+ joints) and no `animation` at all. Deliberately narrow: a static object
+ declares no joints and gets no finding, so nothing pushes every model toward
+ motion it never showed.
+
+Nothing here rejects a generation — a static assembly is a complete answer and
+a stylized clip is the author's to keep. `buildThreejsAnimationFeedback()` turns
+the findings into refinement feedback, so a refinement the user did not steer
+asks for clips that open from the assembled pose and close their loops alongside
+the coverage, cross-section, penetration, and material asks.
+
+### The exported player
+
The exported standalone factory carries the validated `animation` block in
-`userData.sculptRuntime`, alongside the node map — enough for a consumer outside
-PortOS to drive the same clips, with no player and no provider code shipped.
+`userData.sculptRuntime` alongside the node map, plus a player over both:
+
+```js
+import { createExampleCrateModel, createSculptAnimationPlayer } from './example-crate.js';
+
+const root = createExampleCrateModel();
+const player = createSculptAnimationPlayer(root, { onCue: (event) => playMySound(event.cue) });
+player.setClip('deploy');
+player.play();
+// from your own render loop:
+player.update(deltaSeconds);
+```
+
+The player takes `update(deltaSeconds)` from the host's existing render loop
+rather than owning a `requestAnimationFrame` loop, so it cannot keep ticking
+after the consumer stops using it. `seek()` scrubs silently and `update()` is
+the only thing that fires cues — the same split the preview makes. `restore()`
+puts the authored assembly back, and a model with no clips yields a working
+no-op player (`clips: []`), so a static assembly needs no branch at the call
+site.
+
+Its source is a fixed string (`server/lib/threejsModelPlayerSource.js`) spliced
+into the emitted module: still no provider-authored code on the export path,
+only PortOS code over provider-authored data. Its pose semantics mirror
+`client/src/lib/threejsAnimation.js` exactly, so a clip poses identically in the
+preview and in a consumer's own scene — change one and change the other.
## Geometry vocabulary
diff --git a/server/lib/README.md b/server/lib/README.md
index dd9522fb70..c4cb6077bd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -173,10 +173,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
| `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. |
-| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, clips }`, one entry per clip with its role, duration, sequence count and distinct cue count. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared*, so the record answers "static assembly" versus "3 clips" without re-deriving it. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
+| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
| `threejsModelFamilies.js` | Curated subject-family checklists for Three.js generation. `THREEJS_MODEL_FAMILY_OPTIONS` / `THREEJS_MODEL_FAMILY_IDS` drive the picker and route validation; `buildThreejsFamilyChecklist(id)` returns the prompt block spliced into generation (`''` for the default `general`, so an un-narrowed subject keeps the unchanged general-purpose prompt); `findMissingFamilyComponents(spec, id)` reports which required components the spec never mentions. |
| `threejsModelPenetration.js` | `evaluateThreejsPenetration(spec)` — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same `THREE.Euler` 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (`error`) or unrelated parts occupying substantially the same space (`warning`). Parts in the same subtree and declared `attachmentPartIds` are exempt — embedding is what those relationships are *for* — and a shallow or transparent-container overlap is reported as an undecided `note`, never as a defect. `buildThreejsPenetrationFeedback(penetration)` turns the errors and warnings (never the undecided notes) into default refinement feedback. |
+| `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |
| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |
| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). |
| `multipart.js` | Streaming multipart/form-data parser. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 34167196d6..42caa27740 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -54,6 +54,7 @@ export * from './threejsModelAnimation.js';
export * from './threejsModelCoverage.js';
export * from './threejsModelFamilies.js';
export * from './threejsModelPenetration.js';
+export * from './threejsModelPlayerSource.js';
export * from './threejsModelRig.js';
// === Story & narrative ===
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 5b2529fb79..1219692dfc 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -10,6 +10,7 @@
import { z } from 'zod';
import { failValidation } from './errorHandler.js';
+import { THREEJS_PLAYER_SOURCE } from './threejsModelPlayerSource.js';
const idSchema = z.string().trim().min(1).max(80).regex(/^[A-Za-z][A-Za-z0-9_-]*$/);
const colorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
@@ -1247,16 +1248,16 @@ export function ${factoryName}() {
articulation: spec.articulation || null,
// Declared clips, or null for a static assembly. Data only: the parse above
// proves every sequence names a real part, stays inside its clip, and never
- // fights another sequence for the same channel, so a consumer can drive the
- // nodes above from it — PortOS ships no player in the exported factory and
- // never executes anything the provider authored.
+ // fights another sequence for the same channel, so createSculptAnimationPlayer
+ // below can drive the nodes above from it — PortOS-authored playback over
+ // provider-authored DATA, never anything the provider wrote as code.
animation: spec.animation || null,
detailInventory: spec.detailInventory,
limitations: spec.limitations,
};
return root;
}
-
+${THREEJS_PLAYER_SOURCE}
export { spec };
`;
}
diff --git a/server/lib/threejsModelAnimation.js b/server/lib/threejsModelAnimation.js
index 457bc0a6a4..70ba917f29 100644
--- a/server/lib/threejsModelAnimation.js
+++ b/server/lib/threejsModelAnimation.js
@@ -1,5 +1,5 @@
/**
- * Clip inventory for an already-validated Three.js scene spec.
+ * Clip inventory and playback gate for an already-validated Three.js scene spec.
*
* The schema (`server/lib/threejsModel.js`) proves a declared `animation` block
* is well FORMED: sequences point at real parts, stay inside their clip, never
@@ -9,15 +9,208 @@
* durable answer and the workspace can say "static assembly" versus "3 clips"
* without re-deriving it from the spec on every read.
*
+ * Alongside the inventory it reports the ways a well-formed clip still plays
+ * badly, which no schema rule can reach: a clip authored against a pose the
+ * assembly does not build jumps the instant it opens, a chain whose handover
+ * misses jumps mid-clip, a looping clip that ends somewhere else pops on every
+ * repeat. Those are `findings`, and `buildThreejsAnimationFeedback` turns them
+ * into refinement feedback the same way the coverage and material gates do.
+ *
* It reports rather than rejects, and it never claims skinning: PortOS builds
- * static assemblies plus declared motion, not skeletons or bind poses.
+ * static assemblies plus declared motion, not skeletons or bind poses. Every
+ * finding is a `warning` for the same reason — a static assembly is a complete
+ * answer, and a deliberately odd clip is the author's to keep.
*/
+import { listSpecNames } from './threejsModel.js';
+
+// Channels a part authors in `parts`, so a clip's opening pose can be compared
+// against what the assembly actually builds. `opacity` and `visible` have no
+// authored counterpart on a part (opacity lives on the shared material), so
+// they are only ever compared clip-internally.
+const POSED_CHANNELS = ['position', 'rotationDegrees', 'scale'];
+const ALL_CHANNELS = [...POSED_CHANNELS, 'opacity', 'visible'];
+// Authored endpoints are provider-written decimals, so an exact compare would
+// report `0.30000000000000004` as a jump. This is well below anything visible
+// at PortOS's scale (a spec's whole subject fits in single-digit units).
+const POSE_EPSILON = 1e-4;
+// A clip is allowed to hold its final pose — a deploy that lands and rests
+// reads better than one that cuts. What is reported is a window whose motion is
+// over before it is half spent AND that then sits still for a noticeable time,
+// which is an authored duration that does not match the clip inside it.
+const DEAD_TAIL_SHARE = 0.5;
+const DEAD_TAIL_SECONDS = 1.5;
+// One joint is a root and nothing else (mirrors `threejsModelRig.js`); a graph
+// with something to move against it, and no clip anywhere, declares motion the
+// model never demonstrates.
+const MIN_JOINTS_EXPECTING_MOTION = 2;
+
+const indexParts = (parts, into = new Map()) => {
+ for (const part of parts || []) {
+ into.set(part.id, part);
+ indexParts(part.children, into);
+ }
+ return into;
+};
+
+const sameValue = (a, b) => {
+ if (Array.isArray(a) && Array.isArray(b)) {
+ return a.length === b.length && a.every((value, axis) => Math.abs(value - b[axis]) <= POSE_EPSILON);
+ }
+ if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) <= POSE_EPSILON;
+ return a === b;
+};
+
+const formatValue = (value) => (Array.isArray(value) ? `[${value.join(', ')}]` : String(value));
+
+const partLabel = (part, partId) => part?.name || partId;
+
+/**
+ * Every sequence that drives one part+channel, in time order. The schema already
+ * forbids two of them overlapping, so the order is total and the list reads as
+ * the handover chain it is.
+ */
+function groupChannelChains(clip) {
+ const chains = new Map();
+ for (const sequence of clip.sequences || []) {
+ for (const channel of ALL_CHANNELS) {
+ const range = sequence.channels?.[channel];
+ if (!range) continue;
+ const key = `${sequence.partId}|${channel}`;
+ const chain = chains.get(key) || { partId: sequence.partId, channel, entries: [] };
+ chain.entries.push({ sequence, range });
+ chains.set(key, chain);
+ }
+ }
+ for (const chain of chains.values()) {
+ chain.entries.sort((a, b) => a.sequence.startSeconds - b.sequence.startSeconds);
+ }
+ return [...chains.values()];
+}
+
+function evaluateClipFindings(clip, partsById) {
+ const findings = [];
+ const chains = groupChannelChains(clip);
+ const clipLabel = clip.name || clip.id;
+
+ const startMismatches = [];
+ const handoverJumps = [];
+ const loopGaps = [];
+
+ for (const chain of chains) {
+ const part = partsById.get(chain.partId);
+ const label = partLabel(part, chain.partId);
+ const first = chain.entries[0];
+ const last = chain.entries[chain.entries.length - 1];
+
+ // The assembled pose is the model the user is looking at. A clip whose first
+ // sequence starts somewhere else teleports the part the moment the clip is
+ // opened, before a single frame has played.
+ if (POSED_CHANNELS.includes(chain.channel) && part && !sameValue(first.range.from, part[chain.channel])) {
+ startMismatches.push(`${label}.${chain.channel} opens at ${formatValue(first.range.from)} but the assembly builds it at ${formatValue(part[chain.channel])}`);
+ }
+
+ for (let index = 1; index < chain.entries.length; index += 1) {
+ const previous = chain.entries[index - 1];
+ const current = chain.entries[index];
+ if (sameValue(previous.range.to, current.range.from)) continue;
+ handoverJumps.push(`${label}.${chain.channel} ends ${previous.sequence.id} at ${formatValue(previous.range.to)} and starts ${current.sequence.id} at ${formatValue(current.range.from)}`);
+ }
+
+ // A loop that does not close is the one defect playback makes worse the
+ // longer it runs: every repeat snaps the part back across the whole gap.
+ if (clip.loop && !sameValue(last.range.to, first.range.from)) {
+ loopGaps.push(`${label}.${chain.channel} ends at ${formatValue(last.range.to)} and restarts at ${formatValue(first.range.from)}`);
+ }
+ }
+
+ if (startMismatches.length > 0) {
+ findings.push({
+ code: 'clip-start-pose-mismatch',
+ severity: 'warning',
+ message: `clip ${clipLabel} is authored against a pose the assembly does not build, so the model jumps the instant the clip opens: ${listSpecNames(startMismatches)}`,
+ });
+ }
+ if (handoverJumps.length > 0) {
+ findings.push({
+ code: 'clip-sequence-jump',
+ severity: 'warning',
+ message: `clip ${clipLabel} hands a channel between sequences that do not meet, so the part jumps mid-clip: ${listSpecNames(handoverJumps)}`,
+ });
+ }
+ if (loopGaps.length > 0) {
+ findings.push({
+ code: 'loop-does-not-close',
+ severity: 'warning',
+ message: `clip ${clipLabel} loops but does not return to where it began, so it snaps on every repeat: ${listSpecNames(loopGaps)}`,
+ });
+ }
+ // An idle is ambient repetition by definition. Authored as a one-shot it plays
+ // through once and the model sits frozen in its final pose.
+ if (clip.role === 'idle' && !clip.loop) {
+ findings.push({
+ code: 'idle-clip-does-not-loop',
+ severity: 'warning',
+ message: `clip ${clipLabel} is an idle but does not loop, so it plays once and freezes in its end pose`,
+ });
+ }
+
+ const lastEnd = (clip.sequences || []).reduce((latest, sequence) => Math.max(latest, sequence.endSeconds), 0);
+ const tail = clip.durationSeconds - lastEnd;
+ if (tail >= DEAD_TAIL_SECONDS && lastEnd <= clip.durationSeconds * DEAD_TAIL_SHARE) {
+ findings.push({
+ code: 'clip-holds-still',
+ severity: 'warning',
+ message: `clip ${clipLabel} finishes moving at ${lastEnd}s and then holds still for ${Number(tail.toFixed(2))}s of its ${clip.durationSeconds}s duration`,
+ });
+ }
+
+ return findings;
+}
+
+function evaluateAnimationFindings(spec) {
+ const animation = spec?.animation || null;
+ const joints = Array.isArray(spec?.articulation?.joints) ? spec.articulation.joints : [];
+
+ if (!animation) {
+ // Narrow on purpose: a static object declares no joints and gets no finding,
+ // so nothing here pushes every model toward motion it never showed.
+ if (joints.length >= MIN_JOINTS_EXPECTING_MOTION) {
+ return [{
+ code: 'articulation-without-clips',
+ severity: 'warning',
+ message: `the spec declares an articulation graph over ${joints.length} joints but no animation clip, so nothing demonstrates the motion it describes`,
+ }];
+ }
+ return [];
+ }
+
+ const partsById = indexParts(spec?.parts);
+ const clips = Array.isArray(animation.clips) ? animation.clips : [];
+ const findings = clips.flatMap((clip) => evaluateClipFindings(clip, partsById));
+
+ const firedCueIds = new Set(
+ clips.flatMap((clip) => (clip.sequences || []).map((sequence) => sequence.cueId).filter(Boolean))
+ );
+ const unfired = (animation.cues || []).filter((cue) => !firedCueIds.has(cue.id));
+ if (unfired.length > 0) {
+ findings.push({
+ code: 'unfired-cue',
+ severity: 'warning',
+ message: `${unfired.length} declared sound ${unfired.length === 1 ? 'cue is' : 'cues are'} never fired by any sequence, so a host is asked to supply a sound nothing plays: ${listSpecNames(unfired.map((cue) => cue.label || cue.id))}`,
+ });
+ }
+
+ return findings;
+}
+
/**
* @param {object|null} spec a spec that has already passed a sculpt-spec schema
* @returns {{animated: boolean, clipCount: number, cueCount: number, sequenceCount: number,
- * movingPartCount: number, longestClipSeconds: number, clips: Array<{id: string, name: string,
- * role: string, durationSeconds: number, sequenceCount: number, cueCount: number}>}}
+ * movingPartCount: number, longestClipSeconds: number, findings: Array<{code: string,
+ * severity: string, message: string}>, warningCount: number,
+ * clips: Array<{id: string, name: string, role: string, durationSeconds: number,
+ * sequenceCount: number, cueCount: number}>}}
*/
export function summarizeThreejsAnimation(spec) {
const animation = spec?.animation || null;
@@ -49,6 +242,8 @@ export function summarizeThreejsAnimation(spec) {
};
});
+ const findings = evaluateAnimationFindings(spec);
+
return {
animated: summaries.length > 0,
clipCount: summaries.length,
@@ -58,6 +253,27 @@ export function summarizeThreejsAnimation(spec) {
// how much of the assembly is more than scenery.
movingPartCount: movingPartIds.size,
longestClipSeconds,
+ findings,
+ warningCount: findings.filter((finding) => finding.severity === 'warning').length,
clips: summaries,
};
}
+
+/**
+ * Default refinement feedback for a stored clip report. Reads `findings` off the
+ * record rather than re-deriving them, exactly like the coverage, cross-section,
+ * penetration, and material builders — so a record written before this gate
+ * shipped contributes nothing rather than throwing.
+ *
+ * @param {object|null} animation a stored `summarizeThreejsAnimation` result
+ * @returns {string} '' when there is nothing to ask for
+ */
+export function buildThreejsAnimationFeedback(animation) {
+ const warnings = (animation?.findings || []).filter((finding) => finding.severity === 'warning');
+ if (warnings.length === 0) return '';
+ return [
+ 'The previous pass declared animation clips that will not play cleanly:',
+ ...warnings.map((finding, index) => `${index + 1}. ${finding.message}`),
+ 'Author every clip against the assembled pose: the first sequence on a part starts from exactly the position, rotation, and scale that part carries in "parts", each following sequence starts where the one before it ended, a looping clip returns to where it began, and the clip\'s duration ends when its motion does.',
+ ].join('\n');
+}
diff --git a/server/lib/threejsModelAnimation.test.js b/server/lib/threejsModelAnimation.test.js
index 95aeb35a47..c7171409f8 100644
--- a/server/lib/threejsModelAnimation.test.js
+++ b/server/lib/threejsModelAnimation.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { summarizeThreejsAnimation } from './threejsModelAnimation.js';
+import { buildThreejsAnimationFeedback, summarizeThreejsAnimation } from './threejsModelAnimation.js';
const clip = (overrides = {}) => ({
id: 'deploy',
@@ -82,3 +82,160 @@ describe('summarizeThreejsAnimation', () => {
expect(summary.clips[0].role).toBe('custom');
});
});
+
+// Parts the fixture clip drives, in the pose the assembly builds — so a test
+// that expects a clean gate is starting from a model that really does open
+// where its clip does.
+const parts = () => ([
+ { id: 'panel', name: 'Panel', position: [0, 0, 0], rotationDegrees: [0, 0, 0], scale: [1, 1, 1], children: [] },
+ { id: 'arm', name: 'Arm', position: [1, 0, 0], rotationDegrees: [0, 0, 0], scale: [1, 1, 1], children: [] },
+]);
+
+const animatedSpec = (overrides = {}) => ({
+ parts: parts(),
+ animation: {
+ cues: [{ id: 'latch', label: 'Latch', kind: 'latch' }],
+ clips: [clip()],
+ },
+ ...overrides,
+});
+
+const codesOf = (spec) => summarizeThreejsAnimation(spec).findings.map((finding) => finding.code);
+
+describe('summarizeThreejsAnimation playback findings', () => {
+ it('reports nothing for a clip authored against the pose the assembly builds', () => {
+ const summary = summarizeThreejsAnimation(animatedSpec());
+ expect(summary.findings).toEqual([]);
+ expect(summary.warningCount).toBe(0);
+ });
+
+ it('flags a clip that opens somewhere the assembly does not build, naming the part and both poses', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].sequences[0].channels.position.from = [0, 5, 0];
+ const [finding] = summarizeThreejsAnimation(spec).findings;
+ expect(finding).toMatchObject({ code: 'clip-start-pose-mismatch', severity: 'warning' });
+ expect(finding.message).toContain('Panel.position opens at [0, 5, 0] but the assembly builds it at [0, 0, 0]');
+ });
+
+ it('tolerates float drift in an authored endpoint rather than reporting a jump nobody can see', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].sequences[0].channels.position.from = [0, 1e-9, 0];
+ expect(codesOf(spec)).toEqual([]);
+ });
+
+ it('flags a handover between two sequences on one channel that do not meet', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].sequences.push({
+ id: 'lower',
+ name: 'Lower',
+ partId: 'panel',
+ startSeconds: 1,
+ endSeconds: 2,
+ easing: 'linear',
+ // The lift ended at [0, 1, 0]; this restarts the panel a metre away.
+ channels: { position: { from: [0, 2, 0], to: [0, 0, 0] } },
+ cueId: null,
+ });
+ const finding = summarizeThreejsAnimation(spec).findings.find((entry) => entry.code === 'clip-sequence-jump');
+ expect(finding.message).toContain('ends lift at [0, 1, 0] and starts lower at [0, 2, 0]');
+ });
+
+ it('flags a looping clip that does not return to where it began', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].loop = true;
+ const finding = summarizeThreejsAnimation(spec).findings.find((entry) => entry.code === 'loop-does-not-close');
+ expect(finding.message).toContain('Panel.position ends at [0, 1, 0] and restarts at [0, 0, 0]');
+ });
+
+ it('accepts a looping clip whose channels close back onto their opening pose', () => {
+ const spec = animatedSpec();
+ const [lift] = spec.animation.clips[0].sequences;
+ spec.animation.clips[0].loop = true;
+ spec.animation.clips[0].durationSeconds = 2;
+ spec.animation.clips[0].sequences = [
+ lift,
+ {
+ ...lift,
+ id: 'lower',
+ name: 'Lower',
+ startSeconds: 1,
+ endSeconds: 2,
+ channels: { position: { from: [0, 1, 0], to: [0, 0, 0] } },
+ },
+ ];
+ expect(codesOf(spec)).toEqual([]);
+ });
+
+ it('flags an idle authored as a one-shot, which plays once and freezes', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].role = 'idle';
+ expect(codesOf(spec)).toContain('idle-clip-does-not-loop');
+ });
+
+ it('flags a declared cue no sequence ever fires', () => {
+ const spec = animatedSpec();
+ spec.animation.cues.push({ id: 'servo', label: 'Servo whine', kind: 'servo' });
+ const finding = summarizeThreejsAnimation(spec).findings.find((entry) => entry.code === 'unfired-cue');
+ expect(finding.message).toContain('Servo whine');
+ });
+
+ it('flags a clip that finishes early and then holds still for most of its window', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].durationSeconds = 20;
+ const finding = summarizeThreejsAnimation(spec).findings.find((entry) => entry.code === 'clip-holds-still');
+ expect(finding.message).toContain('finishes moving at 2s and then holds still for 18s of its 20s duration');
+ });
+
+ it('leaves a clip that holds its final pose briefly alone', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].durationSeconds = 3;
+ expect(codesOf(spec)).toEqual([]);
+ });
+
+ it('flags an articulation graph no clip demonstrates, and leaves a plain static assembly alone', () => {
+ const articulated = {
+ parts: parts(),
+ articulation: {
+ joints: [
+ { id: 'root', partId: 'panel' },
+ { id: 'elbow', partId: 'arm', parentJointId: 'root', pivotSocket: 'elbow' },
+ ],
+ },
+ };
+ expect(codesOf(articulated)).toEqual(['articulation-without-clips']);
+ // A static object declares no joints, so nothing here pushes every model
+ // toward motion it never showed.
+ expect(codesOf({ parts: parts() })).toEqual([]);
+ expect(codesOf({ parts: parts(), articulation: { joints: [{ id: 'root', partId: 'panel' }] } })).toEqual([]);
+ });
+});
+
+describe('buildThreejsAnimationFeedback', () => {
+ it('returns nothing for a record with no findings, and for one written before the gate shipped', () => {
+ expect(buildThreejsAnimationFeedback(summarizeThreejsAnimation(animatedSpec()))).toBe('');
+ for (const stored of [null, undefined, {}, { animated: true, clipCount: 1 }]) {
+ expect(buildThreejsAnimationFeedback(stored)).toBe('');
+ }
+ });
+
+ it('numbers the warnings and states the contract a refinement has to satisfy', () => {
+ const spec = animatedSpec();
+ spec.animation.clips[0].sequences[0].channels.position.from = [0, 5, 0];
+ spec.animation.clips[0].role = 'idle';
+ const feedback = buildThreejsAnimationFeedback(summarizeThreejsAnimation(spec));
+ expect(feedback).toContain('1. clip Deploy is authored against a pose the assembly does not build');
+ expect(feedback).toContain('2. clip Deploy is an idle but does not loop');
+ expect(feedback).toContain('the first sequence on a part starts from exactly the position');
+ });
+
+ it('reads findings off the stored record rather than re-deriving them from a spec', () => {
+ const feedback = buildThreejsAnimationFeedback({
+ findings: [
+ { code: 'loop-does-not-close', severity: 'warning', message: 'clip Idle snaps on every repeat' },
+ { code: 'made-up', severity: 'note', message: 'not actionable' },
+ ],
+ });
+ expect(feedback).toContain('1. clip Idle snaps on every repeat');
+ expect(feedback).not.toContain('not actionable');
+ });
+});
diff --git a/server/lib/threejsModelPlayerSource.js b/server/lib/threejsModelPlayerSource.js
new file mode 100644
index 0000000000..bd66ddc455
--- /dev/null
+++ b/server/lib/threejsModelPlayerSource.js
@@ -0,0 +1,344 @@
+/**
+ * The clip player PortOS emits into an exported Three.js factory.
+ *
+ * The exported module already carries the validated `animation` block and the
+ * part node map, which is enough to drive a clip — but only if every consumer
+ * re-implements the pose semantics, and any of them getting it subtly wrong
+ * makes the export disagree with what the PortOS preview showed. So the export
+ * ships the player too.
+ *
+ * It is a fixed source STRING, not a generated one: nothing a provider authored
+ * is interpolated into it, and the only provider-derived text in the emitted
+ * file remains `JSON.stringify(spec)`. That is what keeps "clips are data,
+ * never code" true on the export path as well as inside PortOS.
+ *
+ * The semantics mirror `client/src/lib/threejsAnimation.js` exactly — same owner
+ * ranking per part+channel, same step `visible`, same half-open cue interval, so
+ * a clip poses identically in the preview and in a consumer's own scene. Change
+ * one and change the other; `threejsModelPlayerSource.test.js` executes the
+ * emitted player against the same expectations the client evaluator's suite
+ * asserts.
+ *
+ * Emitted into a module that already defines `spec`, `radians`, and `rotation`.
+ */
+export const THREEJS_PLAYER_SOURCE = `
+// ---------------------------------------------------------------------------
+// Clip playback. Declared transforms over time — no skeleton, no bind pose, and
+// nothing here was authored by the model provider. Mirrors the PortOS preview.
+// ---------------------------------------------------------------------------
+
+const CLIP_CHANNELS = ['position', 'rotationDegrees', 'scale', 'opacity', 'visible'];
+
+const EASING_CURVES = {
+ linear: (t) => t,
+ easeIn: (t) => t * t,
+ easeOut: (t) => t * (2 - t),
+ easeInOut: (t) => t * t * (3 - 2 * t),
+};
+
+const clamp01 = (value) => (value < 0 ? 0 : value > 1 ? 1 : value);
+
+const interpolateRange = (range, progress) => (
+ Array.isArray(range.from) && Array.isArray(range.to)
+ ? range.from.map((value, axis) => value + ((range.to[axis] - value) * progress))
+ : range.from + ((range.to - range.from) * progress)
+);
+
+// \`visible\` cannot be interpolated: the part holds \`from\` for the whole window
+// and takes \`to\` the instant the sequence completes.
+const stepRange = (range, progress) => (progress >= 1 ? range.to : range.from);
+
+const channelValue = (sequence, range, channel, timeSeconds) => {
+ const span = sequence.endSeconds - sequence.startSeconds;
+ const progress = clamp01(span > 0 ? (timeSeconds - sequence.startSeconds) / span : 1);
+ if (channel === 'visible') return stepRange(range, progress);
+ const curve = EASING_CURVES[sequence.easing] || EASING_CURVES.linear;
+ return interpolateRange(range, curve(progress));
+};
+
+// 2 = this window contains the instant, 1 = it is behind the playhead, 0 = ahead.
+const rankAt = (sequence, time) => {
+ if (time >= sequence.startSeconds && time <= sequence.endSeconds) return 2;
+ return sequence.endSeconds < time ? 1 : 0;
+};
+
+const outranks = (candidate, current, time) => {
+ const candidateRank = rankAt(candidate, time);
+ const currentRank = rankAt(current, time);
+ if (candidateRank !== currentRank) return candidateRank > currentRank;
+ if (candidateRank === 2) return candidate.startSeconds > current.startSeconds;
+ if (candidateRank === 1) return candidate.endSeconds > current.endSeconds;
+ return candidate.startSeconds < current.startSeconds;
+};
+
+/**
+ * Pose for every part a clip drives at an absolute time. Pure: the same time
+ * gives the same pose whether it came from a play loop, a scrub, or a test.
+ *
+ * Each part+channel resolves from the one sequence that owns the instant — the
+ * window containing it, else the most recent window behind it (whose \`to\` still
+ * holds), else the next window ahead (whose \`from\` has not moved yet) — so a
+ * part never snaps back to its authored pose in a gap, and declaration order
+ * decides nothing. A part no sequence drives is absent from the pose entirely.
+ */
+export function evaluateSculptClipPose(clip, timeSeconds) {
+ // Null-prototype: part ids come from the spec, and a bare lookup on a plain
+ // object can otherwise hand back \`toString\`.
+ const pose = Object.create(null);
+ const sequences = Array.isArray(clip && clip.sequences) ? clip.sequences : [];
+ const time = Number.isFinite(timeSeconds) ? timeSeconds : 0;
+ const owners = new Map();
+ for (const sequence of sequences) {
+ for (const channel of CLIP_CHANNELS) {
+ const range = sequence.channels && sequence.channels[channel];
+ if (!range) continue;
+ const key = sequence.partId + '|' + channel;
+ const current = owners.get(key);
+ if (!current || outranks(sequence, current.sequence, time)) {
+ owners.set(key, { sequence, range, channel });
+ }
+ }
+ }
+ for (const owner of owners.values()) {
+ const partPose = pose[owner.sequence.partId] || (pose[owner.sequence.partId] = {});
+ partPose[owner.channel] = channelValue(owner.sequence, owner.range, owner.channel, time);
+ }
+ return pose;
+}
+
+/**
+ * Cues whose sequence starts inside the half-open interval [fromSeconds,
+ * toSeconds) — what a play loop crossed since its last frame. Half-open so
+ * consecutive frames tile the timeline with no cue fired twice and none skipped.
+ */
+export function collectSculptCues(clip, fromSeconds, toSeconds) {
+ if (!(toSeconds > fromSeconds)) return [];
+ return (Array.isArray(clip && clip.sequences) ? clip.sequences : [])
+ .filter((sequence) => sequence.cueId
+ && sequence.startSeconds >= fromSeconds
+ && sequence.startSeconds < toSeconds)
+ .sort((a, b) => a.startSeconds - b.startSeconds)
+ .map((sequence) => ({
+ cueId: sequence.cueId,
+ sequenceId: sequence.id,
+ partId: sequence.partId,
+ atSeconds: sequence.startSeconds,
+ }));
+}
+
+const indexAuthoredPose = (parts, into) => {
+ for (const part of parts) {
+ into[part.id] = { position: part.position, rotationDegrees: part.rotationDegrees, scale: part.scale };
+ indexAuthoredPose(part.children, into);
+ }
+ return into;
+};
+
+/**
+ * Drive this model's declared clips over the node map the factory built.
+ *
+ * The player does NOT own an animation loop: call \`update(deltaSeconds)\` from
+ * the render loop you already have, so nothing keeps ticking after you stop
+ * using it. \`seek()\` scrubs silently; \`update()\` is the only thing that fires
+ * cues, which is what makes a cue an identifier your host maps to its own sound
+ * rather than embedded audio.
+ *
+ * A model with no clips yields a working no-op player (\`clips: []\`), so a
+ * static assembly needs no branch at the call site.
+ *
+ * @param {THREE.Object3D} root the Group returned by this module's factory
+ * @param {{ onCue?: (event: object) => void, speed?: number }} [options]
+ */
+export function createSculptAnimationPlayer(root, options) {
+ const settings = options || {};
+ const runtime = (root && root.userData && root.userData.sculptRuntime) || {};
+ const nodes = runtime.nodes || {};
+ const animation = runtime.animation || null;
+ const clips = (animation && animation.clips) || [];
+ const cues = (animation && animation.cues) || [];
+ const cuesById = Object.create(null);
+ for (const cue of cues) cuesById[cue.id] = cue;
+ const authored = indexAuthoredPose(spec.parts, Object.create(null));
+ // Materials are shared between parts, so driving \`opacity\` through the shared
+ // instance would fade every part that happens to use it. The first opacity
+ // frame swaps in a clone and remembers the original for \`restore()\`.
+ const sharedMaterials = new Map();
+ const posedPartIds = new Set();
+
+ let clip = clips[0] || null;
+ let timeSeconds = 0;
+ let playing = false;
+ let speed = Number.isFinite(settings.speed) && settings.speed > 0 ? settings.speed : 1;
+
+ const duration = () => (clip && Number.isFinite(clip.durationSeconds) ? clip.durationSeconds : 0);
+
+ const applyOpacity = (partId, node, opacity) => {
+ if (!node.material) return;
+ if (!sharedMaterials.has(partId)) {
+ sharedMaterials.set(partId, node.material);
+ node.material = node.material.clone();
+ }
+ node.material.opacity = opacity;
+ node.material.transparent = sharedMaterials.get(partId).transparent || opacity < 1;
+ };
+
+ const restorePart = (partId) => {
+ const node = nodes[partId];
+ if (!node) return;
+ const pose = authored[partId];
+ if (pose) {
+ node.position.set(pose.position[0], pose.position[1], pose.position[2]);
+ node.rotation.set(...rotation(pose.rotationDegrees));
+ node.scale.set(pose.scale[0], pose.scale[1], pose.scale[2]);
+ }
+ node.visible = true;
+ const shared = sharedMaterials.get(partId);
+ if (shared) {
+ // The clone exists only for this player, so it is ours to dispose.
+ if (node.material && node.material !== shared) node.material.dispose();
+ node.material = shared;
+ sharedMaterials.delete(partId);
+ }
+ };
+
+ const applyPose = () => {
+ const pose = evaluateSculptClipPose(clip, timeSeconds);
+ for (const partId of Object.keys(pose)) {
+ const node = nodes[partId];
+ if (!node) continue;
+ const partPose = pose[partId];
+ posedPartIds.add(partId);
+ if (partPose.position) node.position.set(partPose.position[0], partPose.position[1], partPose.position[2]);
+ if (partPose.rotationDegrees) node.rotation.set(...rotation(partPose.rotationDegrees));
+ if (partPose.scale) node.scale.set(partPose.scale[0], partPose.scale[1], partPose.scale[2]);
+ if (typeof partPose.visible === 'boolean') node.visible = partPose.visible;
+ if (typeof partPose.opacity === 'number') applyOpacity(partId, node, partPose.opacity);
+ }
+ };
+
+ // Put every part this player has moved back to the pose the factory built,
+ // then apply the current clip. Called when the open clip changes, because the
+ // new clip drives a different set of parts and the old ones would otherwise
+ // stay frozen wherever the previous clip left them.
+ const reapply = () => {
+ for (const partId of posedPartIds) restorePart(partId);
+ posedPartIds.clear();
+ applyPose();
+ };
+
+ const seekTo = (seconds) => {
+ const total = duration();
+ const target = Number.isFinite(seconds) ? seconds : 0;
+ timeSeconds = target < 0 ? 0 : target > total ? total : target;
+ applyPose();
+ return timeSeconds;
+ };
+
+ const emit = (crossed) => {
+ const handler = settings.onCue;
+ if (typeof handler !== 'function') return;
+ for (const event of crossed) {
+ // A host callback must not be able to kill the caller's render loop.
+ try {
+ handler({ ...event, clipId: clip.id, cue: cuesById[event.cueId] || null });
+ } catch (error) {
+ console.error('Sculpt clip cue handler failed: ' + error.message);
+ }
+ }
+ };
+
+ const player = {
+ clips: clips.map((entry) => ({
+ id: entry.id,
+ name: entry.name,
+ role: entry.role,
+ durationSeconds: entry.durationSeconds,
+ loop: entry.loop,
+ })),
+ cues: cues.map((cue) => ({ ...cue })),
+ get clipId() { return clip ? clip.id : null; },
+ get durationSeconds() { return duration(); },
+ get timeSeconds() { return timeSeconds; },
+ get playing() { return playing; },
+ get speed() { return speed; },
+ set speed(value) { if (Number.isFinite(value) && value > 0) speed = value; },
+
+ /**
+ * Open a clip by id, stopped at its first frame. An id this model does not
+ * declare falls back to the first clip, so a stale selection degrades to
+ * something playable instead of an empty transport.
+ */
+ setClip(clipId) {
+ if (clips.length === 0) return null;
+ clip = clips.find((entry) => entry.id === clipId) || clips[0];
+ timeSeconds = 0;
+ playing = false;
+ reapply();
+ return clip.id;
+ },
+
+ /** Scrub. Never fires a cue — silence while dragging is the point. */
+ seek: seekTo,
+
+ play() {
+ if (!clip) return false;
+ // Pressing play on a finished one-shot replays it rather than sitting on
+ // its last frame.
+ if (!clip.loop && timeSeconds >= duration()) seekTo(0);
+ playing = true;
+ return true;
+ },
+
+ pause() { playing = false; },
+
+ stop() {
+ playing = false;
+ seekTo(0);
+ },
+
+ /**
+ * Advance the playhead by real seconds and pose the model. Returns the cues
+ * crossed by this frame (also handed to \`onCue\`), oldest first.
+ */
+ update(deltaSeconds) {
+ const total = duration();
+ if (!playing || !clip || !(total > 0) || !Number.isFinite(deltaSeconds) || deltaSeconds <= 0) return [];
+ const from = timeSeconds;
+ let to = from + (deltaSeconds * speed);
+ let crossed;
+ if (to < total) {
+ crossed = collectSculptCues(clip, from, to);
+ } else if (clip.loop) {
+ // A frame gap longer than the whole clip — a backgrounded tab, a stall —
+ // crossed every cue in it. Fire each ONCE for the gap rather than
+ // replaying the clip's audio for every lap it skipped.
+ crossed = collectSculptCues(clip, from, total);
+ const wrapped = ((to - total) % total + total) % total;
+ const fired = new Set(crossed.map((event) => event.sequenceId));
+ for (const event of collectSculptCues(clip, 0, wrapped)) {
+ if (!fired.has(event.sequenceId)) crossed.push(event);
+ }
+ to = wrapped;
+ } else {
+ crossed = collectSculptCues(clip, from, total);
+ to = total;
+ playing = false;
+ }
+ timeSeconds = to;
+ applyPose();
+ emit(crossed);
+ return crossed;
+ },
+
+ /** Put the assembly back exactly as the factory built it, and stop. */
+ restore() {
+ playing = false;
+ timeSeconds = 0;
+ for (const partId of posedPartIds) restorePart(partId);
+ posedPartIds.clear();
+ },
+ };
+
+ return player;
+}
+`;
diff --git a/server/lib/threejsModelPlayerSource.test.js b/server/lib/threejsModelPlayerSource.test.js
new file mode 100644
index 0000000000..1689217f39
--- /dev/null
+++ b/server/lib/threejsModelPlayerSource.test.js
@@ -0,0 +1,268 @@
+import { describe, expect, it } from 'vitest';
+import { buildThreejsFactorySource } from './threejsModel.js';
+
+// The emitted player is only worth shipping if it actually runs, so the suite
+// EXECUTES it rather than grepping the string: the module is imported with the
+// `three` import swapped for the two helpers the player reaches through
+// (`MathUtils.degToRad`), which is enough to drive poses without pulling a
+// renderer into a node test.
+const importEmitted = async (spec) => {
+ const source = buildThreejsFactorySource(spec)
+ .replace(
+ "import * as THREE from 'three';",
+ 'const THREE = { MathUtils: { degToRad: (degrees) => (degrees * Math.PI) / 180 } };'
+ );
+ return import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
+};
+
+const vector = () => {
+ const value = { x: 0, y: 0, z: 0 };
+ value.set = (x, y, z) => Object.assign(value, { x, y, z });
+ return value;
+};
+
+// A stand-in for the Three.js node the factory would have built. Only the
+// surface the player touches is modelled.
+const node = (material = null) => ({
+ position: vector(),
+ rotation: vector(),
+ scale: vector(),
+ visible: true,
+ material,
+});
+
+const material = (overrides = {}) => {
+ const value = { opacity: 1, transparent: false, disposed: false, ...overrides };
+ value.clone = () => material({ ...value, clonedFrom: value });
+ value.dispose = () => { value.disposed = true; };
+ return value;
+};
+
+const spec = () => ({
+ schemaVersion: 1,
+ name: 'Example Hatch',
+ summary: 'A panel that lifts and an arm that swings.',
+ subjectType: 'object',
+ background: '#111827',
+ camera: { position: [4, 3, 5], target: [0, 0, 0], fov: 42 },
+ materials: { body: { type: 'standard', color: '#8b5a2b', metalness: 0, roughness: 0.7 } },
+ lights: [{ type: 'ambient', color: '#ffffff', intensity: 0.4 }],
+ parts: [
+ {
+ id: 'panel',
+ name: 'Panel',
+ geometry: { type: 'box', width: 1, height: 0.2, depth: 1 },
+ material: 'body',
+ position: [0, 0, 0],
+ rotationDegrees: [0, 0, 0],
+ scale: [1, 1, 1],
+ children: [],
+ },
+ {
+ id: 'arm',
+ name: 'Arm',
+ geometry: { type: 'box', width: 0.2, height: 1, depth: 0.2 },
+ material: 'body',
+ position: [1, 0, 0],
+ rotationDegrees: [0, 0, 0],
+ scale: [1, 1, 1],
+ children: [],
+ },
+ ],
+ sockets: [],
+ detailInventory: [{
+ feature: 'Lifting panel',
+ evidence: 'The reference shows a hinged panel over the housing.',
+ implementationPartIds: ['panel'],
+ priority: 'identity',
+ }],
+ animation: {
+ cues: [{ id: 'latch', label: 'Latch release', kind: 'latch' }],
+ clips: [
+ {
+ id: 'deploy',
+ name: 'Deploy',
+ role: 'deploy',
+ durationSeconds: 4,
+ loop: false,
+ sequences: [
+ {
+ id: 'lift',
+ name: 'Lift the panel',
+ partId: 'panel',
+ startSeconds: 0,
+ endSeconds: 2,
+ easing: 'linear',
+ channels: { position: { from: [0, 0, 0], to: [0, 2, 0] } },
+ cueId: 'latch',
+ },
+ {
+ id: 'swing',
+ name: 'Swing the arm',
+ partId: 'arm',
+ startSeconds: 2,
+ endSeconds: 4,
+ easing: 'linear',
+ channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 180, 0] } },
+ cueId: 'latch',
+ },
+ ],
+ },
+ {
+ id: 'fade',
+ name: 'Fade',
+ role: 'custom',
+ durationSeconds: 2,
+ loop: false,
+ sequences: [{
+ id: 'dim',
+ name: 'Dim the panel',
+ partId: 'panel',
+ startSeconds: 0,
+ endSeconds: 2,
+ easing: 'linear',
+ channels: { opacity: { from: 1, to: 0 }, visible: { from: true, to: false } },
+ cueId: null,
+ }],
+ },
+ ],
+ },
+});
+
+const mountPlayer = async (input = spec(), options = undefined) => {
+ const module = await importEmitted(input);
+ const nodes = { panel: node(material()), arm: node(material()) };
+ const root = { userData: { sculptRuntime: { nodes, animation: input.animation || null } } };
+ return { module, nodes, player: module.createSculptAnimationPlayer(root, options) };
+};
+
+describe('emitted clip player', () => {
+ it('poses the node map from a scrub without firing a cue', async () => {
+ const cues = [];
+ const { nodes, player } = await mountPlayer(spec(), { onCue: (event) => cues.push(event) });
+
+ expect(player.clipId).toBe('deploy');
+ expect(player.durationSeconds).toBe(4);
+ player.seek(1);
+ // Half-way through a linear two-second lift.
+ expect(nodes.panel.position).toMatchObject({ x: 0, y: 1, z: 0 });
+ // A sequence still ahead of the playhead holds its `from`, so the arm has
+ // not moved and has NOT snapped back to the authored pose either.
+ expect(nodes.arm.rotation).toMatchObject({ x: 0, y: 0, z: 0 });
+ expect(cues).toEqual([]);
+ });
+
+ it('fires each crossed cue once on update, oldest first, and stops a one-shot at its end', async () => {
+ const cues = [];
+ const { player } = await mountPlayer(spec(), { onCue: (event) => cues.push(event) });
+
+ expect(player.play()).toBe(true);
+ // One frame long enough to cross both cue-carrying sequence starts (0s, 2s)
+ // and run past the clip's 4s end.
+ const crossed = player.update(9);
+ expect(crossed.map((event) => event.sequenceId)).toEqual(['lift', 'swing']);
+ expect(cues.map((event) => event.cueId)).toEqual(['latch', 'latch']);
+ // The cue is resolved to its declared entry so a host can map an identifier
+ // to its own sound without re-reading the spec.
+ expect(cues[0].cue).toMatchObject({ id: 'latch', kind: 'latch' });
+ expect(player.timeSeconds).toBe(4);
+ expect(player.playing).toBe(false);
+ // A finished one-shot replays from the top rather than sitting on its last
+ // frame.
+ player.play();
+ expect(player.timeSeconds).toBe(0);
+ });
+
+ it('wraps a looping clip and fires every cue in a gap longer than the clip exactly once', async () => {
+ const looping = spec();
+ looping.animation.clips[0].loop = true;
+ const cues = [];
+ const { player } = await mountPlayer(looping, { onCue: (event) => cues.push(event) });
+
+ player.play();
+ player.update(10);
+ expect(cues.map((event) => event.sequenceId)).toEqual(['lift', 'swing']);
+ expect(player.playing).toBe(true);
+ expect(player.timeSeconds).toBeCloseTo(2, 6);
+ });
+
+ it('clones a shared material before driving opacity, and gives it back on restore', async () => {
+ const { nodes, player } = await mountPlayer();
+ const sharedPanelMaterial = nodes.panel.material;
+ const sharedArmMaterial = nodes.arm.material;
+
+ player.setClip('fade');
+ player.seek(1);
+ expect(nodes.panel.material).not.toBe(sharedPanelMaterial);
+ expect(nodes.panel.material.opacity).toBeCloseTo(0.5, 6);
+ expect(nodes.panel.material.transparent).toBe(true);
+ // The arm shares the same material definition and must not have faded with
+ // the panel.
+ expect(sharedPanelMaterial.opacity).toBe(1);
+ expect(nodes.arm.material).toBe(sharedArmMaterial);
+
+ player.restore();
+ expect(nodes.panel.material).toBe(sharedPanelMaterial);
+ expect(nodes.panel.visible).toBe(true);
+ expect(nodes.panel.position).toMatchObject({ x: 0, y: 0, z: 0 });
+ });
+
+ it('returns parts the previous clip drove to their authored pose when the clip changes', async () => {
+ const { nodes, player } = await mountPlayer();
+
+ player.seek(4);
+ expect(nodes.panel.position).toMatchObject({ x: 0, y: 2, z: 0 });
+ expect(nodes.arm.rotation.y).toBeCloseTo(Math.PI, 6);
+
+ // `fade` drives the panel only — the arm would otherwise stay frozen where
+ // `deploy` left it.
+ player.setClip('fade');
+ expect(nodes.arm.rotation).toMatchObject({ x: 0, y: 0, z: 0 });
+ expect(nodes.panel.position).toMatchObject({ x: 0, y: 0, z: 0 });
+ expect(player.timeSeconds).toBe(0);
+ });
+
+ it('steps visible at the end of its window rather than fading it', async () => {
+ const { nodes, player } = await mountPlayer();
+ player.setClip('fade');
+ player.seek(1.9);
+ expect(nodes.panel.visible).toBe(true);
+ player.seek(2);
+ expect(nodes.panel.visible).toBe(false);
+ });
+
+ it('falls back to the first clip for an id this model does not declare', async () => {
+ const { player } = await mountPlayer();
+ expect(player.setClip('nope')).toBe('deploy');
+ });
+
+ it('yields a working no-op player for a static assembly', async () => {
+ const staticSpec = spec();
+ delete staticSpec.animation;
+ const { nodes, player } = await mountPlayer(staticSpec);
+
+ expect(player.clips).toEqual([]);
+ expect(player.clipId).toBeNull();
+ expect(player.play()).toBe(false);
+ expect(player.update(1)).toEqual([]);
+ expect(player.setClip('deploy')).toBeNull();
+ expect(nodes.panel.position).toMatchObject({ x: 0, y: 0, z: 0 });
+ });
+
+ it('survives a host cue handler that throws rather than killing the render loop', async () => {
+ const { player } = await mountPlayer(spec(), { onCue: () => { throw new Error('host blew up'); } });
+ player.play();
+ expect(() => player.update(1)).not.toThrow();
+ expect(player.timeSeconds).toBe(1);
+ });
+
+ it('exports the pose evaluator so a host can drive its own renderer', async () => {
+ const { module } = await mountPlayer();
+ const clip = spec().animation.clips[0];
+ expect(module.evaluateSculptClipPose(clip, 1).panel.position).toEqual([0, 1, 0]);
+ expect(module.collectSculptCues(clip, 0, 1).map((event) => event.sequenceId)).toEqual(['lift']);
+ // Half-open: a cue at the interval's end belongs to the NEXT frame, so no
+ // frame boundary fires one twice.
+ expect(module.collectSculptCues(clip, 0, 2).map((event) => event.sequenceId)).toEqual(['lift']);
+ });
+});
diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.js
index 3f4466aeb1..9409e28e66 100644
--- a/server/services/threejsModels/db.js
+++ b/server/services/threejsModels/db.js
@@ -95,11 +95,13 @@ export async function createModel(input) {
// which every consumer renders as an unevaluated STATIC assembly — never as
// "articulation-ready".
rig: null,
- // Clip inventory for `spec.animation`, written alongside it by
- // `summarizeThreejsAnimation`. Same additive-field contract as `coverage`
- // and `rig`: a record written before clips shipped reads back undefined,
- // which every consumer renders as an unevaluated STATIC assembly with
- // nothing to play — never as "no clips were declared".
+ // Clip inventory AND playback findings for `spec.animation`, written
+ // alongside it by `summarizeThreejsAnimation`. Same additive-field contract
+ // as `coverage` and `rig`: a record written before clips shipped reads back
+ // undefined, which every consumer renders as an unevaluated STATIC assembly
+ // with nothing to play — never as "no clips were declared". A record written
+ // before the playback gate shipped carries no `findings` key, which
+ // contributes no refinement feedback rather than reading as a clean pass.
animation: null,
// Material-plausibility findings for `spec`, written alongside it by
// `evaluateThreejsMaterialPlausibility`. Same additive-field contract as
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index 2c0ed5bb23..1bba0b3ff9 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -16,7 +16,7 @@ import {
evaluateThreejsMaterialPlausibility,
threejsSculptSpecSchema,
} from '../../lib/threejsModel.js';
-import { summarizeThreejsAnimation } from '../../lib/threejsModelAnimation.js';
+import { buildThreejsAnimationFeedback, summarizeThreejsAnimation } from '../../lib/threejsModelAnimation.js';
import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';
import { buildThreejsPenetrationFeedback, evaluateThreejsPenetration } from '../../lib/threejsModelPenetration.js';
import { evaluateThreejsRigReadiness } from '../../lib/threejsModelRig.js';
@@ -177,6 +177,9 @@ async function executeGeneration({
if (animation.animated) {
console.log(`🎬 Three.js model ${id} declares ${animation.clipCount} clip(s) over ${animation.movingPartCount} moving part(s), longest ${animation.longestClipSeconds}s`);
}
+ if (animation.warningCount > 0) {
+ console.warn(`⚠️ Three.js model ${id} clip playback: ${animation.warningCount} warning finding(s)`);
+ }
if (rig.articulationReady) {
console.log(`🦴 Three.js model ${id} declares an articulation graph: ${rig.jointCount} joint(s), ${rig.socketCount} pivot socket(s)`);
}
@@ -236,13 +239,15 @@ export async function startGeneration(id, {
// got wrong — the promises it did not build, the identity parts it built
// without a cross-section, the parts it modelled inside each other, and the
// materials whose values contradict the substance they are named for —
- // instead of a generic "improve it". All are sent when all fired: they are
- // independent defects with independent remedies.
+ // instead of a generic "improve it" — plus, for a model that declared clips,
+ // the ways a well-formed clip still plays badly. All are sent when all fired:
+ // they are independent defects with independent remedies.
const effectiveFeedback = (feedback || '').trim() || [
buildThreejsCoverageFeedback(current.coverage),
buildThreejsFlatnessFeedback(current.flatness),
buildThreejsPenetrationFeedback(current.penetration),
buildThreejsMaterialFeedback(current.materialPlausibility),
+ buildThreejsAnimationFeedback(current.animation),
].filter(Boolean).join('\n\n');
// Absent (`undefined`) keeps whatever the record already had; an explicit
// `null` — what the picker's "Default effort" choice sends — clears it.
diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.js
index 3ce2a19e9c..5c52161855 100644
--- a/server/services/threejsModels/index.test.js
+++ b/server/services/threejsModels/index.test.js
@@ -740,5 +740,69 @@ describe('Three.js model clip inventory', () => {
// The clips survive the parse onto the record, so the export and the preview
// play the same sequences the inventory counted.
expect(current.spec.animation.clips[0].sequences).toHaveLength(1);
+ // A clip authored against the pose the assembly builds has nothing to fix,
+ // so a refinement of it is not steered toward the clips at all.
+ expect(current.animation.findings).toEqual([]);
+ });
+
+ it('steers an unsteered refinement at a clip that will not play cleanly', async () => {
+ const jumpingSpec = {
+ ...spec,
+ animation: {
+ cues: [{ id: 'latchRelease', label: 'Latch lets go', kind: 'latch' }],
+ clips: [{
+ id: 'deploy',
+ name: 'Deploy',
+ role: 'deploy',
+ durationSeconds: 1.5,
+ sequences: [{
+ id: 'raiseLens',
+ name: 'Raise lens',
+ partId: 'lens',
+ startSeconds: 0,
+ endSeconds: 1,
+ // The assembly builds the lens at the origin, so this clip
+ // teleports it the instant it opens.
+ channels: { position: { from: [0, 0.9, 0], to: [0, 0.6, 0] } },
+ cueId: 'latchRelease',
+ }],
+ }],
+ },
+ };
+ let current = {
+ id: 'threejs-clip-feedback',
+ name: 'Example Beacon',
+ sourceImage: { filename: 'example.png' },
+ providerId: 'vision-api',
+ model: null,
+ prompt: '',
+ status: 'draft',
+ spec: null,
+ animation: null,
+ runs: [],
+ };
+ store.getModel.mockImplementation(async () => current);
+ store.mutateModel.mockImplementation(async (_id, mutate) => {
+ const next = mutate(current);
+ if (next) current = next;
+ return current;
+ });
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify(jumpingSpec),
+ runId: 'run-clip-feedback',
+ provider: { id: 'vision-api' },
+ model: null,
+ });
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+ expect(current.animation.findings.map((finding) => finding.code)).toEqual(['clip-start-pose-mismatch']);
+ // A clip finding never rejects the generation — the model is still ready and
+ // its spec is stored verbatim.
+ expect(current.spec.animation.clips[0].sequences[0].channels.position.from).toEqual([0, 0.9, 0]);
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ expect(current.runs.at(-1).feedback).toContain('will not play cleanly');
+ expect(current.runs.at(-1).feedback).toContain('Lens.position opens at [0, 0.9, 0]');
});
});
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index b2612df7f8..3c8200132d 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -193,6 +193,15 @@ Rules, all enforced — a spec that breaks one is rejected outright:
- Channels are the only animation surface. Do not animate materials, lights, the camera, or
geometry parameters, and do not return JavaScript, keyframe arrays, or curve definitions.
+Also checked after generation, and fed back as refinement notes rather than rejected:
+- A "loop": true clip returns to where it began — its last endpoint on a channel equals that
+ channel's first one — or it snaps back on every repeat. An "idle" clip is repeating motion by
+ definition, so give it "loop": true.
+- Every declared cue is fired by at least one sequence; a cue nothing fires asks for a sound that
+ never plays.
+- "durationSeconds" ends near where the motion does. A short hold on the final pose is good; a
+ clip that finishes in its first half and then sits still for seconds is a mistyped duration.
+
Prefer a short, legible set: a "deploy" clip and its "retract" mirror explain a mechanism better
than eight speculative ones. Author each clip against the model's assembled pose — sequence one
starts from exactly the "position"/"rotationDegrees"/"scale" the part carries in "parts".