Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: declarative animation clips for Three.js model specs (#4542)
[._.]/ Adam Eivy4502d2d2b7f6
diff --git a/client/src/components/threejsModels/ThreejsClipTransport.jsx b/client/src/components/threejsModels/ThreejsClipTransport.jsxnew file mode 100644index 0000000000..f2c226d5ef--- /dev/null+++ b/client/src/components/threejsModels/ThreejsClipTransport.jsx@@ -0,0 +1,91 @@+import { useId } from 'react';+import { Pause, Play, Square } from 'lucide-react';++/**+ * Timeline controls for the declarative clips a Three.js model spec may declare+ * (`server/lib/threejsModel.js`). Presentation only: the playhead, the clip+ * selection, and the cue callback all live in the preview, so this stays a pure+ * render of the transport state and never owns a clock.+ */+export const CLIP_SPEEDS = [0.25, 0.5, 1, 2];++export default function ThreejsClipTransport({+ clips,+ clip,+ duration,+ time,+ playing,+ speed,+ activeSequenceNames = [],+ onSelectClip,+ onTogglePlay,+ onStop,+ onScrub,+ onSpeedChange,+}) {+ const clipSelectId = useId();+ const scrubId = useId();+ const speedSelectId = useId();+ if (!clip) return null;+ return (+ <div className="port-media-overlay pointer-events-auto flex max-w-full flex-wrap items-center gap-1.5 rounded-lg px-2 py-1.5 text-[10px]">+ <label htmlFor={clipSelectId} className="whitespace-nowrap text-port-text-muted">Clip</label>+ <select+ id={clipSelectId}+ value={clip.id}+ onChange={(event) => onSelectClip(event.target.value)}+ className="port-media-overlay-item rounded px-1.5 py-1 text-[10px]"+ >+ {clips.map((option) => (+ <option key={option.id} value={option.id}>{option.name}</option>+ ))}+ </select>+ <button+ type="button"+ aria-label={playing ? 'Pause clip' : 'Play clip'}+ aria-pressed={playing}+ onClick={onTogglePlay}+ className="port-media-overlay-item rounded px-1.5 py-1"+ >+ {playing ? <Pause className="h-3 w-3" /> : <Play className="h-3 w-3" />}+ </button>+ <button+ type="button"+ aria-label="Stop clip"+ disabled={!playing && time === 0}+ onClick={onStop}+ className="port-media-overlay-item rounded px-1.5 py-1 disabled:cursor-not-allowed disabled:opacity-40"+ >+ <Square className="h-3 w-3" />+ </button>+ {/* Dragging this never fires a cue — scrubbing is the silent mode, and the+ preview only collects cues from the play loop. */}+ <label htmlFor={scrubId} className="whitespace-nowrap text-port-text-muted">Time</label>+ <input+ id={scrubId}+ type="range"+ min="0"+ max={duration}+ step="0.01"+ value={Math.min(time, duration)}+ onChange={(event) => onScrub(Number(event.target.value))}+ className="h-1 w-24 cursor-pointer accent-port-accent sm:w-36"+ />+ <span className="w-16 tabular-nums text-port-text-muted">+ {time.toFixed(2)}/{duration.toFixed(2)}s+ </span>+ <label htmlFor={speedSelectId} className="whitespace-nowrap text-port-text-muted">Speed</label>+ <select+ id={speedSelectId}+ value={speed}+ onChange={(event) => onSpeedChange(Number(event.target.value))}+ className="port-media-overlay-item rounded px-1.5 py-1 text-[10px]"+ >+ {CLIP_SPEEDS.map((option) => <option key={option} value={option}>{option}×</option>)}+ </select>+ <span className="max-w-full truncate text-port-text-muted">+ {activeSequenceNames.length > 0 ? activeSequenceNames.join(' · ') : 'no sequence at this time'}+ </span>+ </div>+ );+}diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsxindex 5db41c2493..bf311ed430 100644--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx@@ -4,8 +4,17 @@ import { Canvas, useFrame } from '@react-three/fiber';import { Bounds, OrbitControls, useBounds } from '@react-three/drei';import * as THREE from 'three';import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from '../../lib/threejsSculpt';+import {+ collectThreejsCues,+ evaluateThreejsClipPose,+ getThreejsClipDuration,+ listThreejsClips,+ listThreejsCues,+ resolveThreejsClip,+} from '../../lib/threejsAnimation';import { buildPartSelectionIndex, computeExplodeLayout, isReliefPart } from '../../lib/threejsExplode';import { summarizeThreejsArticulation } from '../../lib/threejsRig';+import ThreejsClipTransport from './ThreejsClipTransport';import {createRenderBudget,getEffectiveTier,@@ -120,14 +129,21 @@ function Geometry({ definition }) {}}-function Material({ definition, highlighted = false, auditMode = 'final', partId }) {+function Material({ definition, highlighted = false, auditMode = 'final', partId, opacity }) {if (auditMode === 'normals') return <meshNormalMaterial />;if (auditMode === 'wireframe') return <meshBasicMaterial color="#cbd5e1" wireframe />;if (auditMode === 'boundaries') {return <meshStandardMaterial color={auditPartColor(partId)} metalness={0} roughness={0.62} />;}if (auditMode === 'neutral') return <meshStandardMaterial color="#a8b0bd" metalness={0} roughness={0.72} />;- const props = sculptMaterialProps(definition);+ const authored = sculptMaterialProps(definition);+ // A clip's opacity channel overrides the authored value for as long as the+ // clip drives it. `transparent` has to come with it — Three.js ignores an+ // opacity below 1 on an opaque material — but the authored flag still wins+ // when the material was already transparent.+ const props = typeof opacity === 'number'+ ? { ...authored, opacity, transparent: authored.transparent || opacity < 1 }+ : authored;// 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') {@@ -145,12 +161,19 @@ function Material({ definition, highlighted = false, auditMode = 'final', partIdconst offsetPosition = (position = [0, 0, 0], offset) =>(Array.isArray(offset) ? position.map((value, axis) => value + offset[axis]) : position);-function Part({ part, materials, layout, selection, selectedId, onSelect, auditMode }) {+function Part({ part, materials, layout, selection, selectedId, onSelect, auditMode, pose }) {+ // The clip's pose for this part, or nothing — a part no sequence drives keeps+ // exactly the transform the spec authored, which is also what every part of a+ // model with no clips at all gets.+ const posed = pose[part.id];const transform = {name: part.name,- position: offsetPosition(part.position, layout.offsets[part.id]),- rotation: rotation(part.rotationDegrees),- scale: part.scale,+ position: offsetPosition(posed?.position || part.position, layout.offsets[part.id]),+ rotation: rotation(posed?.rotationDegrees || part.rotationDegrees),+ scale: posed?.scale || part.scale,+ // Hides the whole subtree, which is what a retracted or destroyed component+ // means — its relief and children go with it.+ visible: posed?.visible !== false,};// The whole selected subtree lights up, so selecting a container reads as one// component rather than one lonely mesh inside it.@@ -168,11 +191,11 @@ function Part({ part, materials, layout, selection, selectedId, onSelect, auditM{part.geometry && (<mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow} onClick={select}><Geometry definition={part.geometry} />- <Material definition={materials[part.material]} highlighted={highlighted} auditMode={auditMode} partId={part.id} />+ <Material definition={materials[part.material]} highlighted={highlighted} auditMode={auditMode} partId={part.id} opacity={posed?.opacity} /></mesh>)}{part.children.filter(isReliefPart).map((child) => (- <Part key={child.id} part={child} materials={materials} layout={layout} selection={selection} selectedId={selectedId} onSelect={onSelect} auditMode={auditMode} />+ <Part key={child.id} part={child} materials={materials} layout={layout} selection={selection} selectedId={selectedId} onSelect={onSelect} auditMode={auditMode} pose={pose} />))}</>);@@ -190,6 +213,7 @@ function Part({ part, materials, layout, selection, selectedId, onSelect, auditMselectedId={selectedId}onSelect={onSelect}auditMode={auditMode}+ pose={pose}/>))}</group>@@ -259,7 +283,7 @@ function SceneLight({ light }) {return <directionalLight color={light.color} intensity={light.intensity} position={light.position} castShadow />;}-function ProceduralScene({ spec, background, layout, selection, selectedId, onSelect, auditMode }) {+function ProceduralScene({ spec, background, layout, selection, selectedId, onSelect, auditMode, pose }) {return (<>{background && <color attach="background" args={[background]} />}@@ -280,6 +304,7 @@ function ProceduralScene({ spec, background, layout, selection, selectedId, onSeselectedId={selectedId}onSelect={onSelect}auditMode={auditMode}+ pose={pose}/>))}</group>@@ -297,7 +322,104 @@ function ProceduralScene({ spec, background, layout, selection, selectedId, onSe);}-export default function ThreejsModelPreview({ spec, family = null, className = '' }) {+/**+ * Playhead for one declared clip.+ *+ * The time lives in a ref as well as in state because the play loop needs the+ * PREVIOUS frame's time to ask which cues it just crossed — deriving that inside+ * a state updater would make firing a cue a side effect of rendering, which+ * double-fires the moment React replays the updater.+ *+ * Scrubbing moves the same playhead and fires nothing: only this loop collects+ * cues, which is the entire difference between silent scrubbing and playback.+ */+function useClipPlayback({ clip, cuesById, onCue }) {+ const [timeSeconds, setTimeSeconds] = useState(0);+ const [playing, setPlaying] = useState(false);+ const [speed, setSpeed] = useState(1);+ const timeRef = useRef(0);+ const onCueRef = useRef(onCue);+ const duration = getThreejsClipDuration(clip);+ const clipId = clip?.id || null;++ const setPlayhead = useCallback((value) => {+ timeRef.current = value;+ setTimeSeconds(value);+ }, []);++ // A different clip starts at its own beginning, stopped — carrying a playhead+ // across clips would drop the model into a pose the new clip never authored.+ useEffect(() => {+ setPlaying(false);+ setPlayhead(0);+ }, [clipId, setPlayhead]);++ // Held in a ref so a caller passing an inline handler cannot restart the loop+ // on every render.+ useEffect(() => {+ onCueRef.current = onCue;+ }, [onCue]);++ useEffect(() => {+ if (!playing || !clip || !(duration > 0)) return undefined;+ let frame = 0;+ let last = performance.now();+ const fire = (from, to) => {+ const handler = onCueRef.current;+ if (!handler) return;+ for (const crossed of collectThreejsCues(clip, from, to)) {+ // The handler runs outside React's render and outside any request+ // lifecycle: an uncaught throw here would break the rAF chain and stop+ // playback dead with no way to restart it.+ try {+ handler({ ...crossed, clipId: clip.id, cue: cuesById[crossed.cueId] || null });+ } catch (error) {+ console.error(`❌ Three.js clip cue handler failed: ${error.message}`);+ }+ }+ };+ const step = (now) => {+ const delta = Math.max(0, (now - last) / 1000) * speed;+ last = now;+ const from = timeRef.current;+ const raw = from + delta;+ if (raw < duration) {+ fire(from, raw);+ setPlayhead(raw);+ } else if (clip.loop) {+ fire(from, duration);+ const wrapped = raw % duration;+ fire(0, wrapped);+ setPlayhead(wrapped);+ } else {+ fire(from, duration);+ setPlayhead(duration);+ setPlaying(false);+ return;+ }+ frame = requestAnimationFrame(step);+ };+ frame = requestAnimationFrame(step);+ return () => cancelAnimationFrame(frame);+ }, [playing, clip, duration, speed, cuesById, setPlayhead]);++ const togglePlay = useCallback(() => {+ // Pressing play on a finished clip replays it rather than sitting on the+ // last frame doing nothing. Read from state rather than an updater — moving+ // the playhead from inside one makes it a side effect React may replay.+ if (!playing && timeRef.current >= duration) setPlayhead(0);+ setPlaying(!playing);+ }, [playing, duration, setPlayhead]);++ const stop = useCallback(() => {+ setPlaying(false);+ setPlayhead(0);+ }, [setPlayhead]);++ return { timeSeconds, playing, speed, setSpeed, togglePlay, stop, setPlayhead, duration };+}++export default function ThreejsModelPreview({ spec, family = null, className = '', onCue = null }) {const [background, setBackground] = useState(() => spec?.background || '#000000');const [explode, setExplode] = useState(0);const [qualityMode, setQualityMode] = useState('auto');@@ -356,6 +478,30 @@ export default function ThreejsModelPreview({ spec, family = null, className = 'const requestedAuditMode = searchParams.get('auditMode');const auditMode = isAuditRenderMode(requestedAuditMode) ? requestedAuditMode : 'final';const auditCameraPosition = getAuditCameraPosition(spec, auditCamera);+ // Which clip is open is part of what the URL describes, the same way the audit+ // camera and inspection mode are — a clip a model does not declare degrades to+ // its first one rather than to an empty transport.+ const clips = useMemo(() => listThreejsClips(spec), [spec]);+ // Keyed on the requested id rather than the params object: picking a part+ // rewrites the URL, and a fresh `searchParams` identity would hand the play+ // loop a new clip object and restart it mid-playback.+ const requestedClipId = searchParams.get('clip');+ const clip = useMemo(() => resolveThreejsClip(spec, requestedClipId), [spec, requestedClipId]);+ const cuesById = useMemo(() => {+ // Null-prototype: cue ids are provider-authored and the id schema accepts+ // `toString`, so a bare lookup on a plain object can hand back a function.+ const map = Object.create(null);+ for (const cue of listThreejsCues(spec)) map[cue.id] = cue;+ return map;+ }, [spec]);+ const playback = useClipPlayback({ clip, cuesById, onCue });+ const { pose, activeSequenceIds } = useMemo(+ () => evaluateThreejsClipPose(clip, playback.timeSeconds),+ [clip, playback.timeSeconds],+ );+ const activeSequenceNames = (clip?.sequences || [])+ .filter((sequence) => activeSequenceIds.includes(sequence.id))+ .map((sequence) => sequence.name);const handleSelect = useCallback((partId) => {setSearchParams((previous) => {const next = new URLSearchParams(previous);@@ -364,7 +510,7 @@ export default function ThreejsModelPreview({ spec, family = null, className = 'return next;}, { replace: true });}, [setSearchParams]);- const setAuditParam = useCallback((key, value) => {+ const setPreviewParam = useCallback((key, value) => {setSearchParams((previous) => {const next = new URLSearchParams(previous);next.set(key, value);@@ -406,6 +552,7 @@ export default function ThreejsModelPreview({ spec, family = null, className = 'selectedId={selectedId}onSelect={handleSelect}auditMode={auditMode}+ pose={pose}/></Canvas><div className="port-media-overlay absolute left-2 top-2 flex max-w-[calc(100%-1rem)] flex-wrap items-center gap-1.5 rounded-lg px-2 py-1.5 text-[10px]">@@ -488,7 +635,7 @@ export default function ThreejsModelPreview({ spec, family = null, className = 'aria-pressed={auditCamera === camera.id}disabled={unavailable}title={unavailable ? 'Choose a subject family to enable family review' : undefined}- onClick={() => setAuditParam('auditCamera', camera.id)}+ onClick={() => setPreviewParam('auditCamera', camera.id)}className="port-media-overlay-item rounded px-1.5 py-1 disabled:cursor-not-allowed disabled:opacity-40">{camera.label}@@ -505,7 +652,7 @@ export default function ThreejsModelPreview({ spec, family = null, className = 'type="button"aria-label={mode.label}aria-pressed={auditMode === mode.id}- onClick={() => setAuditParam('auditMode', mode.id)}+ onClick={() => setPreviewParam('auditMode', mode.id)}className="port-media-overlay-item rounded px-1.5 py-1">{mode.label}@@ -538,6 +685,20 @@ export default function ThreejsModelPreview({ spec, family = null, className = '</div>)}<div className="pointer-events-none absolute bottom-2 left-2 flex max-w-[calc(100%-1rem)] flex-wrap items-center gap-1.5 text-[10px]">+ <ThreejsClipTransport+ clips={clips}+ clip={clip}+ duration={playback.duration}+ time={playback.timeSeconds}+ playing={playback.playing}+ speed={playback.speed}+ activeSequenceNames={activeSequenceNames}+ onSelectClip={(clipId) => setPreviewParam('clip', clipId)}+ onTogglePlay={playback.togglePlay}+ onStop={playback.stop}+ onScrub={playback.setPlayhead}+ onSpeedChange={playback.setSpeed}+ /><span className="port-media-overlay rounded px-2 py-1">Drag to orbit · scroll to zoom · click a part to identify it · audit controls never change the saved model</span>diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsxindex 21220f5b83..79459cf7f4 100644--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx@@ -1,6 +1,6 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import { MemoryRouter, useLocation } from 'react-router';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('@react-three/fiber', () => ({Canvas: ({ children, ...props }) => (@@ -414,3 +414,221 @@ describe('ThreejsModelPreview articulation status', () => {expect(screen.queryByText(/^joint /)).not.toBeInTheDocument();});});++const clipSpec = () => ({+ ...knifeSpec(),+ animation: {+ cues: [{ id: 'latchRelease', label: 'Latch lets go', kind: 'latch' }],+ clips: [+ {+ id: 'deploy',+ name: 'Deploy',+ role: 'deploy',+ durationSeconds: 2,+ loop: false,+ sequences: [+ {+ id: 'swingBlade',+ name: 'Swing blade',+ partId: 'blade',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'linear',+ channels: { position: { from: [-1, 0, 0], to: [-1, 4, 0] } },+ cueId: 'latchRelease',+ },+ {+ id: 'dropHandle',+ name: 'Drop handle',+ partId: 'handle',+ startSeconds: 1,+ endSeconds: 2,+ easing: 'linear',+ channels: { visible: { from: true, to: false }, opacity: { from: 1, to: 0 } },+ cueId: null,+ },+ ],+ },+ {+ id: 'retract',+ name: 'Retract',+ role: 'retract',+ durationSeconds: 1,+ loop: false,+ sequences: [{+ id: 'foldBlade',+ name: 'Fold blade',+ partId: 'blade',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'linear',+ channels: { position: { from: [-1, 4, 0], to: [-1, 0, 0] } },+ cueId: null,+ }],+ },+ ],+ },+});++const scrub = (value) => fireEvent.change(screen.getByLabelText('Time'), { target: { value: String(value) } });+const opacityOf = (container, name) =>+ container.querySelector(`group[name="${name}"] meshStandardMaterial`).getAttribute('opacity');++describe('ThreejsModelPreview clips', () => {+ let frames = [];+ let nowMs = 0;++ beforeEach(() => {+ frames = [];+ nowMs = 0;+ // A hand-driven frame queue, so playback is stepped deterministically+ // instead of waiting on the browser's own rAF cadence.+ vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((callback) => frames.push(callback));+ vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation(() => {});+ vi.spyOn(performance, 'now').mockImplementation(() => nowMs);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ const advance = (ms) => {+ nowMs += ms;+ const pending = frames.splice(0);+ act(() => {+ for (const callback of pending) callback(nowMs);+ });+ };++ it('shows no transport for a model that declares no clips', () => {+ renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);+ expect(screen.queryByLabelText('Clip')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Play clip')).not.toBeInTheDocument();+ });++ it('renders a declared clip at its start pose and keeps undriven parts as authored', () => {+ const { container } = renderPreview(<ThreejsModelPreview spec={clipSpec()} />);++ expect(screen.getByLabelText('Clip')).toHaveValue('deploy');+ expect(positionOf(container, 'Blade')).toEqual([-1, 0, 0]);+ // Undriven at t=0: the handle keeps the authored material, with no opacity+ // override in sight.+ expect(opacityOf(container, 'Handle')).toBe('1');+ });++ it('scrubs to any time deterministically, including the visibility step at a window end', () => {+ const { container } = renderPreview(<ThreejsModelPreview spec={clipSpec()} />);++ scrub(0.5);+ expect(positionOf(container, 'Blade')).toEqual([-1, 2, 0]);+ expect(screen.getByText('Swing blade')).toBeInTheDocument();++ scrub(1.5);+ // Past its window the blade holds where its sequence left it, while the+ // handle is half faded through the window that is still running. (The+ // `visible` step riding the same sequence is asserted in the evaluator's own+ // suite — React drops a boolean prop on an unrecognized element, so the DOM+ // stand-in for a three.js group cannot show it.)+ expect(positionOf(container, 'Blade')).toEqual([-1, 4, 0]);+ expect(opacityOf(container, 'Handle')).toBe('0.5');++ scrub(2);+ expect(opacityOf(container, 'Handle')).toBe('0');+ });++ it('never fires a cue while scrubbing', () => {+ const onCue = vi.fn();+ renderPreview(<ThreejsModelPreview spec={clipSpec()} onCue={onCue} />);++ scrub(0.5);+ scrub(0);+ scrub(1.2);+ expect(onCue).not.toHaveBeenCalled();+ });++ it('plays the clip forward, fires each crossed cue once, and stops at the end', () => {+ const onCue = vi.fn();+ const { container } = renderPreview(<ThreejsModelPreview spec={clipSpec()} onCue={onCue} />);++ fireEvent.click(screen.getByLabelText('Play clip'));+ advance(500);+ expect(positionOf(container, 'Blade')).toEqual([-1, 2, 0]);+ expect(onCue).toHaveBeenCalledTimes(1);+ expect(onCue).toHaveBeenCalledWith(expect.objectContaining({+ cueId: 'latchRelease',+ sequenceId: 'swingBlade',+ partId: 'blade',+ clipId: 'deploy',+ cue: expect.objectContaining({ label: 'Latch lets go', kind: 'latch' }),+ }));++ advance(500);+ expect(onCue).toHaveBeenCalledTimes(1);++ // Past the authored duration the clip stops on its final pose instead of+ // running on, and the transport flips back to offering Play.+ advance(2_000);+ expect(screen.getByLabelText('Play clip')).toBeInTheDocument();+ expect(screen.getByText('2.00/2.00s')).toBeInTheDocument();+ expect(frames).toHaveLength(0);+ });++ it('applies the speed multiplier to the playhead', () => {+ renderPreview(<ThreejsModelPreview spec={clipSpec()} />);++ fireEvent.change(screen.getByLabelText('Speed'), { target: { value: '2' } });+ fireEvent.click(screen.getByLabelText('Play clip'));+ advance(500);+ expect(screen.getByText('1.00/2.00s')).toBeInTheDocument();+ });++ it('stops back to the clip start and releases the frame loop on unmount', () => {+ const { unmount } = renderPreview(<ThreejsModelPreview spec={clipSpec()} />);++ fireEvent.click(screen.getByLabelText('Play clip'));+ advance(500);+ fireEvent.click(screen.getByLabelText('Stop clip'));+ expect(screen.getByText('0.00/2.00s')).toBeInTheDocument();+ expect(globalThis.cancelAnimationFrame).toHaveBeenCalled();++ fireEvent.click(screen.getByLabelText('Play clip'));+ globalThis.cancelAnimationFrame.mockClear();+ unmount();+ expect(globalThis.cancelAnimationFrame).toHaveBeenCalled();+ });++ it('keeps the open clip in the URL and rewinds when it changes', () => {+ const { container } = renderPreview(+ <><ThreejsModelPreview spec={clipSpec()} /><LocationProbe /></>,+ '/?clip=retract',+ );++ expect(screen.getByLabelText('Clip')).toHaveValue('retract');+ expect(positionOf(container, 'Blade')).toEqual([-1, 4, 0]);++ scrub(0.5);+ fireEvent.change(screen.getByLabelText('Clip'), { target: { value: 'deploy' } });+ expect(screen.getByTestId('location-probe')).toHaveTextContent('clip=deploy');+ expect(screen.getByText('0.00/2.00s')).toBeInTheDocument();+ });++ it('falls back to the first clip when the URL names one this model does not have', () => {+ renderPreview(<ThreejsModelPreview spec={clipSpec()} />, '/?clip=noSuchClip');+ expect(screen.getByLabelText('Clip')).toHaveValue('deploy');+ });++ it('leaves explode and part picking working while a clip is posed', () => {+ const { container } = renderPreview(<ThreejsModelPreview spec={clipSpec()} />);++ scrub(1);+ setExplode(1);+ // The clip's pose and the disassembly offset compose rather than replacing+ // each other: the blade sits at its posed Y with the explode offset on top.+ const [bladeX, bladeY] = positionOf(container, 'Blade');+ expect(bladeY).toBe(4);+ expect(bladeX).toBeCloseTo(-2.18, 6);++ fireEvent.click(container.querySelector('group[name="Blade"] mesh'));+ expect(screen.getByText('Blade')).toBeInTheDocument();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 851f8b6f5f..f3df429083 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -179,6 +179,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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`). || `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. || `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. |+| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. || `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, meshOffsets, 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 — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures 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. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. || `threejsRig.js` | `summarizeThreejsArticulation(spec)` → `{ articulationReady, jointCount, socketCount, attachmentCount, jointsByPartId }` — client mirror of the readiness rule in `server/lib/threejsModelRig.js`, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no `articulation` key reads as a static assembly; a graph is ready only when it carries more than a lone root and every child joint names a pivot socket. `jointsByPartId` is null-prototype so a provider-authored part id cannot resolve to an inherited function. || `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. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 1734e17656..1fcc4e321c 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -144,6 +144,7 @@ export * from './syncCounts.js';export * from './tabNotation.js';export * from './terminalDictation.js';export * from './terminalTheme.js';+export * from './threejsAnimation.js';export * from './threejsExplode.js';export * from './threejsRig.js';export * from './threejsSculpt.js';diff --git a/client/src/lib/threejsAnimation.js b/client/src/lib/threejsAnimation.jsnew file mode 100644index 0000000000..89d71429b4--- /dev/null+++ b/client/src/lib/threejsAnimation.js@@ -0,0 +1,172 @@+/**+ * Pure pose evaluator for the declarative clip contract in+ * `server/lib/threejsModel.js`, used by the Three.js Models preview.+ *+ * A clip is data, never code: named sequences carry one part between two+ * authored endpoints inside a bounded window, and the easing is a NAME resolved+ * against `utils/easing`'s curve map. So the pose at time T is a pure function+ * of (clip, T) — the same input gives the same pose whether it arrived from a+ * play loop, a scrub, or a test — and nothing here touches Three.js, the DOM, or+ * a clock.+ *+ * Semantics, chosen so the function stays total and deterministic:+ * - Before a sequence starts, its channel holds `from`; after it ends, `to`.+ * Between two sequences on the same channel, the earlier one's `to` holds, so+ * a part never snaps back to its authored pose in a gap.+ * - `visible` is a STEP: `from` for the whole window, `to` the instant the+ * sequence completes. A boolean has no midpoint, and inventing a fade here+ * would make playback disagree with the exported factory's data.+ * - A part with no sequence in the clip is absent from the pose entirely, which+ * every consumer reads as "render exactly what the spec authored".+ *+ * 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.+ */++import { EASING_CURVES, linear } from '../utils/easing.js';++/** Channels a sequence may drive, in the order the schema declares them. */+export const THREEJS_CLIP_CHANNELS = ['position', 'rotationDegrees', 'scale', 'opacity', 'visible'];++const clamp01 = (value) => (value < 0 ? 0 : value > 1 ? 1 : value);++/** Declared clips for a spec, or `[]` for a static assembly. */+export const listThreejsClips = (spec) => (Array.isArray(spec?.animation?.clips) ? spec.animation.clips : []);++/** Declared sound cues for a spec, or `[]`. Data identifiers — never audio. */+export const listThreejsCues = (spec) => (Array.isArray(spec?.animation?.cues) ? spec.animation.cues : []);++/**+ * The clip a URL/selection names, or the first declared clip when it names none+ * or one this spec does not have. Returns null for a static assembly, so a+ * caller can gate the whole transport on a single check.+ */+export function resolveThreejsClip(spec, clipId) {+ const clips = listThreejsClips(spec);+ if (clips.length === 0) return null;+ return clips.find((clip) => clip.id === clipId) || clips[0];+}++/** Authored duration of a clip — the window, not the last sequence's end. */+export const getThreejsClipDuration = (clip) => (Number.isFinite(clip?.durationSeconds) ? clip.durationSeconds : 0);++const interpolate = (range, progress) => {+ const { from, to } = range;+ if (Array.isArray(from) && Array.isArray(to)) {+ return from.map((value, axis) => value + ((to[axis] - value) * progress));+ }+ return from + ((to - from) * progress);+};++// `from` until the window closes, `to` from that instant on. Used for the one+// channel that cannot be interpolated.+const step = (range, progress) => (progress >= 1 ? range.to : range.from);++const channelValue = (sequence, range, channel, timeSeconds) => {+ const span = sequence.endSeconds - sequence.startSeconds;+ // A zero-length window is unreachable through the schema, which requires+ // `endSeconds > startSeconds`; a hand-repaired record that has one reads as+ // already finished rather than dividing by zero.+ const raw = span > 0 ? (timeSeconds - sequence.startSeconds) / span : 1;+ const progress = clamp01(raw);+ if (channel === 'visible') return step(range, progress);+ const curve = EASING_CURVES[sequence.easing] || linear;+ return interpolate(range, curve(progress));+};++// 2 = this window contains the instant, 1 = it is behind the playhead, 0 = it is+// still ahead. The schema forbids two windows on one part+channel from+// overlapping, so a tie can only happen at a shared endpoint or among windows+// that all sit on the same side of the playhead.+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;+ // Two windows meeting at a shared instant: the one that has just BEGUN wins,+ // so forward playback reads as the handover it is rather than replaying the+ // finished sequence's final frame.+ 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.+ *+ * @param {object|null} clip a validated clip, or null+ * @param {number} timeSeconds absolute seconds from the clip's start+ * @returns {{timeSeconds: number, pose: object, activeSequenceIds: string[], activePartIds: string[]}}+ * `pose` is a null-prototype map of partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }`;+ * `activeSequenceIds` are the sequences whose window contains the time.+ */+export function evaluateThreejsClipPose(clip, timeSeconds) {+ // Null-prototype: part ids are provider-authored and the id schema accepts+ // `toString`, so a bare lookup on a plain object can hand back a function.+ const pose = Object.create(null);+ const sequences = Array.isArray(clip?.sequences) ? clip.sequences : [];+ const time = Number.isFinite(timeSeconds) ? timeSeconds : 0;+ const activeSequenceIds = [];+ const activeParts = new Set();++ // Each part+channel is resolved 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).+ // Declaration order decides nothing, so a spec that lists its sequences out of+ // time order evaluates identically.+ const owners = new Map();+ for (const sequence of sequences) {+ for (const channel of THREEJS_CLIP_CHANNELS) {+ const range = 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 });+ }+ }+ if (time >= sequence.startSeconds && time <= sequence.endSeconds) {+ activeSequenceIds.push(sequence.id);+ activeParts.add(sequence.partId);+ }+ }+ const activePartIds = [...activeParts];++ for (const { sequence, range, channel } of owners.values()) {+ const partPose = pose[sequence.partId] || (pose[sequence.partId] = {});+ partPose[channel] = channelValue(sequence, range, channel, time);+ }++ return { timeSeconds: time, pose, activeSequenceIds, activePartIds };+}++/**+ * Cues whose sequence starts inside the half-open interval `[fromSeconds,+ * toSeconds)` — what a play loop crossed since its last frame.+ *+ * Half-open on purpose: consecutive frames tile the timeline with no cue fired+ * twice and none skipped, and a cue at 0 fires on the first frame of playback.+ * A scrub calls this never — silence while dragging is the whole reason a cue+ * is an identifier the host maps to its own sound rather than embedded audio.+ *+ * @returns {Array<{cueId: string, sequenceId: string, partId: string, atSeconds: number}>}+ */+export function collectThreejsCues(clip, fromSeconds, toSeconds) {+ if (!(toSeconds > fromSeconds)) return [];+ return (Array.isArray(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,+ }));+}diff --git a/client/src/lib/threejsAnimation.test.js b/client/src/lib/threejsAnimation.test.jsnew file mode 100644index 0000000000..68743b182d--- /dev/null+++ b/client/src/lib/threejsAnimation.test.js@@ -0,0 +1,218 @@+import { describe, expect, it } from 'vitest';+import {+ collectThreejsCues,+ evaluateThreejsClipPose,+ getThreejsClipDuration,+ listThreejsClips,+ listThreejsCues,+ resolveThreejsClip,+} from './threejsAnimation';++const clip = (overrides = {}) => ({+ id: 'deploy',+ name: 'Deploy',+ role: 'deploy',+ durationSeconds: 3,+ loop: false,+ sequences: [+ {+ id: 'lift',+ name: 'Lift',+ partId: 'panel',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'linear',+ channels: { position: { from: [0, 0, 0], to: [0, 2, 0] } },+ cueId: 'latch',+ },+ {+ id: 'swing',+ name: 'Swing',+ partId: 'panel',+ startSeconds: 2,+ endSeconds: 3,+ easing: 'linear',+ channels: { position: { from: [0, 2, 0], to: [0, 2, 4] } },+ cueId: null,+ },+ ],+ ...overrides,+});++const spec = (overrides = {}) => ({+ name: 'Example model',+ animation: {+ cues: [{ id: 'latch', label: 'Latch lets go', kind: 'latch' }],+ clips: [clip(), clip({ id: 'retract', name: 'Retract' })],+ },+ ...overrides,+});++const poseOf = (target, time, partId = 'panel') => evaluateThreejsClipPose(target, time).pose[partId];++describe('clip lookup', () => {+ it('reads a spec with no animation key as a static assembly', () => {+ expect(listThreejsClips(null)).toEqual([]);+ expect(listThreejsClips({ name: 'x' })).toEqual([]);+ expect(listThreejsCues({ name: 'x' })).toEqual([]);+ expect(resolveThreejsClip({ name: 'x' }, 'deploy')).toBeNull();+ });++ it('falls back to the first clip for an unknown or absent id', () => {+ expect(resolveThreejsClip(spec(), 'retract').id).toBe('retract');+ expect(resolveThreejsClip(spec(), 'noSuchClip').id).toBe('deploy');+ expect(resolveThreejsClip(spec(), null).id).toBe('deploy');+ });++ it('reads a duration only from a real number', () => {+ expect(getThreejsClipDuration(clip())).toBe(3);+ expect(getThreejsClipDuration(null)).toBe(0);+ expect(getThreejsClipDuration({ durationSeconds: 'soon' })).toBe(0);+ });+});++describe('evaluateThreejsClipPose', () => {+ it('poses nothing for a static assembly, so every part renders as authored', () => {+ const result = evaluateThreejsClipPose(null, 1.5);+ expect(Object.keys(result.pose)).toEqual([]);+ expect(result.activeSequenceIds).toEqual([]);+ });++ it('is deterministic at both boundaries of a window', () => {+ expect(poseOf(clip(), 0).position).toEqual([0, 0, 0]);+ expect(poseOf(clip(), 1).position).toEqual([0, 2, 0]);+ expect(poseOf(clip(), 0.5).position).toEqual([0, 1, 0]);+ });++ it('holds the previous window\'s end value in the gap between two sequences', () => {+ // Between 1s and 2s nothing is driving the part: it must hold where the+ // first sequence left it, not snap back to the authored pose or jump ahead+ // to the second sequence's start value.+ expect(poseOf(clip(), 1.5).position).toEqual([0, 2, 0]);+ expect(poseOf(clip(), 1.999).position).toEqual([0, 2, 0]);+ });++ it('holds the last window\'s end value past the end of the clip', () => {+ expect(poseOf(clip(), 3).position).toEqual([0, 2, 4]);+ expect(poseOf(clip(), 99).position).toEqual([0, 2, 4]);+ });++ it('evaluates identically whichever order the sequences are declared in', () => {+ const reversed = clip({ sequences: [...clip().sequences].reverse() });+ for (const time of [0, 0.5, 1, 1.5, 2, 2.5, 3]) {+ expect(poseOf(reversed, time)).toEqual(poseOf(clip(), time));+ }+ });++ it('hands a shared instant to the window that has just begun', () => {+ const chained = clip({+ sequences: [+ { ...clip().sequences[0] },+ // A deliberately discontinuous handover, so the assertion can tell WHICH+ // window owns the shared instant: the first ends at [0,2,0] and the+ // second begins at [0,5,0].+ {+ ...clip().sequences[1],+ startSeconds: 1,+ endSeconds: 2,+ channels: { position: { from: [0, 5, 0], to: [0, 5, 4] } },+ },+ ],+ });+ expect(poseOf(chained, 0.999).position).toEqual([0, 1.998, 0]);+ // At 1s the first window is finished and the second starts — the second's+ // `from` is what plays next, so it owns the instant.+ expect(poseOf(chained, 1).position).toEqual([0, 5, 0]);+ expect(poseOf(chained, 1.5).position).toEqual([0, 5, 2]);+ });++ it('applies the named easing curve rather than always interpolating linearly', () => {+ const eased = clip({ sequences: [{ ...clip().sequences[0], easing: 'easeIn' }] });+ expect(poseOf(eased, 0.5).position).toEqual([0, 0.5, 0]);+ const unknown = clip({ sequences: [{ ...clip().sequences[0], easing: 'elasticOut' }] });+ // An easing name this build does not implement falls back to linear rather+ // than producing NaN.+ expect(poseOf(unknown, 0.5).position).toEqual([0, 1, 0]);+ });++ it('steps visibility at the end of its window instead of interpolating a boolean', () => {+ const hides = clip({+ sequences: [{+ id: 'hide',+ name: 'Hide',+ partId: 'panel',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'linear',+ channels: { visible: { from: true, to: false } },+ cueId: null,+ }],+ });+ expect(poseOf(hides, 0).visible).toBe(true);+ expect(poseOf(hides, 0.99).visible).toBe(true);+ expect(poseOf(hides, 1).visible).toBe(false);+ expect(poseOf(hides, 2).visible).toBe(false);+ });++ it('interpolates scalar channels and reports which sequences are live', () => {+ const fades = clip({+ sequences: [{+ ...clip().sequences[0],+ channels: { opacity: { from: 1, to: 0 }, position: { from: [0, 0, 0], to: [0, 2, 0] } },+ }],+ });+ const result = evaluateThreejsClipPose(fades, 0.25);+ expect(result.pose.panel.opacity).toBeCloseTo(0.75, 6);+ expect(result.activeSequenceIds).toEqual(['lift']);+ expect(result.activePartIds).toEqual(['panel']);+ expect(evaluateThreejsClipPose(fades, 2).activeSequenceIds).toEqual([]);+ });++ it('keeps parts no sequence drives out of the pose entirely', () => {+ expect(evaluateThreejsClipPose(clip(), 0.5).pose.somethingElse).toBeUndefined();+ });++ it('resolves a part id that shadows an Object prototype member', () => {+ const shady = clip({ sequences: [{ ...clip().sequences[0], partId: 'toString' }] });+ expect(evaluateThreejsClipPose(shady, 1).pose.toString).toEqual({ position: [0, 2, 0] });+ });++ it('reads a non-finite time as the start of the clip rather than producing NaN', () => {+ expect(poseOf(clip(), Number.NaN).position).toEqual([0, 0, 0]);+ expect(poseOf(clip(), undefined).position).toEqual([0, 0, 0]);+ });+});++describe('collectThreejsCues', () => {+ it('fires a cue once, on the frame that crosses its start', () => {+ expect(collectThreejsCues(clip(), 0, 0.016)).toEqual([+ { cueId: 'latch', sequenceId: 'lift', partId: 'panel', atSeconds: 0 },+ ]);+ // The next frame must not fire it again — consecutive half-open intervals+ // tile the timeline with no duplicate and no gap.+ expect(collectThreejsCues(clip(), 0.016, 0.032)).toEqual([]);+ });++ it('returns nothing for an interval that does not move forward, which is what a scrub passes', () => {+ expect(collectThreejsCues(clip(), 1, 1)).toEqual([]);+ expect(collectThreejsCues(clip(), 1, 0)).toEqual([]);+ });++ it('ignores sequences that declare no cue', () => {+ expect(collectThreejsCues(clip(), 1.9, 2.1)).toEqual([]);+ });++ it('returns crossed cues in time order for a long frame', () => {+ const busy = clip({+ sequences: [+ { ...clip().sequences[0], startSeconds: 0.5, endSeconds: 1, cueId: 'latch' },+ { ...clip().sequences[1], startSeconds: 0.1, endSeconds: 0.4, cueId: 'thud' },+ ],+ });+ expect(collectThreejsCues(busy, 0, 2).map((entry) => entry.cueId)).toEqual(['thud', 'latch']);+ });++ it('returns nothing for a static assembly', () => {+ expect(collectThreejsCues(null, 0, 1)).toEqual([]);+ });+});diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsxindex 280bdb44ba..effd2239ca 100644--- a/client/src/pages/ThreejsModelDetail.jsx+++ b/client/src/pages/ThreejsModelDetail.jsx@@ -18,6 +18,7 @@ import {} from '../services/api';import toast from '../components/ui/Toast';import { copyToClipboard } from '../lib/clipboard';+import { listThreejsClips } from '../lib/threejsAnimation';import { summarizeThreejsArticulation } from '../lib/threejsRig';import { timeAgo } from '../utils/formatters';import { seedModelEffort } from '../utils/providers';@@ -201,6 +202,58 @@ function RigReadinessPanel({ rig, spec }) {);}+/**+ * What the spec declared it can PLAY. Prefers the inventory the server wrote at+ * generation time and falls back to the spec's own clips, so a model generated+ * before clips shipped reads as the static assembly it is rather than borrowing+ * a verdict it was never given.+ */+function ClipInventoryPanel({ animation, spec }) {+ const clips = Array.isArray(animation?.clips) && animation.clips.length > 0+ ? animation.clips+ : listThreejsClips(spec).map((clip) => ({+ id: clip.id,+ name: clip.name,+ role: clip.role,+ durationSeconds: clip.durationSeconds,+ sequenceCount: clip.sequences?.length || 0,+ cueCount: new Set((clip.sequences || []).map((sequence) => sequence.cueId).filter(Boolean)).size,+ }));+ if (clips.length === 0) return null;+ return (+ <section className="rounded-xl border border-port-border bg-port-card p-4">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-xs font-medium uppercase tracking-wide text-gray-400">Animation clips</h2>+ <span className="text-xs text-gray-600">+ {clips.length} clip{clips.length === 1 ? '' : 's'}+ </span>+ </div>+ <div className="grid gap-2 md:grid-cols-2">+ {clips.map((clip) => (+ <div key={clip.id} className="rounded-lg border border-port-border bg-port-bg/50 p-2.5">+ <div className="flex items-start justify-between gap-2">+ <h3 className="text-xs font-medium text-gray-200">{clip.name}</h3>+ <span className="rounded bg-port-border px-1.5 py-0.5 text-[9px] uppercase text-gray-400">{clip.role || 'custom'}</span>+ </div>+ <p className="mt-1 text-xs text-gray-500">+ {clip.durationSeconds}s · {clip.sequenceCount} sequence{clip.sequenceCount === 1 ? '' : 's'}+ {clip.cueCount > 0 ? ` · ${clip.cueCount} sound cue${clip.cueCount === 1 ? '' : 's'}` : ''}+ </p>+ </div>+ ))}+ </div>+ <p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-gray-500">+ <Info className="mt-0.5 h-3 w-3 shrink-0" />+ <span>+ Clips are declared transforms over time, not a skeleton and not code — play or scrub them+ in the preview. Sound cues are identifiers only: PortOS ships no audio and plays none,+ and scrubbing never fires one.+ </span>+ </p>+ </section>+ );+}+export default function ThreejsModelDetail() {const { id } = useParams();const navigate = useNavigate();@@ -588,6 +641,13 @@ export default function ThreejsModelDetail() {/>)}+ {record.spec && (+ <ClipInventoryPanel+ animation={record.animation && typeof record.animation === 'object' ? record.animation : null}+ spec={record.spec}+ />+ )}+{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.jsxindex 85715e171b..7d926e694e 100644--- a/client/src/pages/ThreejsModelDetail.test.jsx+++ b/client/src/pages/ThreejsModelDetail.test.jsx@@ -484,3 +484,57 @@ describe('ThreejsModelDetail rig readiness fallbacks', () => {expect(screen.queryByText(/undefined/)).not.toBeInTheDocument();});});++describe('ThreejsModelDetail clip inventory', () => {+ beforeEach(resetMocks);++ it('lists the clips the server inventoried, with role, duration and cue count', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ animation: {+ animated: true,+ clipCount: 1,+ clips: [{ id: 'deploy', name: 'Deploy', role: 'deploy', durationSeconds: 2, sequenceCount: 3, cueCount: 1 }],+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Animation clips')).toBeInTheDocument());+ expect(screen.getByText('Deploy')).toBeInTheDocument();+ expect(screen.getByText('2s · 3 sequences · 1 sound cue')).toBeInTheDocument();+ });++ // A record generated before the inventory shipped still has the clips in its+ // spec, so the panel derives them rather than claiming the model is static.+ it('derives the list from the spec when the record carries no inventory', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ animation: undefined,+ spec: {+ ...baseRecord.spec,+ animation: {+ cues: [],+ clips: [{+ id: 'retract',+ name: 'Retract',+ role: 'retract',+ durationSeconds: 1,+ sequences: [{ id: 'fold', cueId: null }],+ }],+ },+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Animation clips')).toBeInTheDocument());+ expect(screen.getByText('1s · 1 sequence')).toBeInTheDocument();+ });++ it('shows no clip panel for a static assembly', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, animation: null });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());+ expect(screen.queryByText('Animation clips')).not.toBeInTheDocument();+ });+});diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex a295c8407a..1d17c4ace7 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -34,7 +34,7 @@ grep -i "what you want to do" client/src/utils/README.md|---|---|| `animationClips` | Treadmill helpers for rigged GLB clips: `withInPlaceClips` synthesizes root-translation-stripped ("in place") variants of root-motion walk/run clips so a fixed-frame avatar can't drift; `inPlaceClipName` routes a clip name to its variant. Framework-agnostic (caller passes the root-motion names + suffix). || `coalesce` | Trailing-edge coalescer: wraps a function so rapid calls collapse into one deferred invocation. |-| `easing` | `smoothstep` interpolation easing curve. |+| `easing` | Interpolation easing curves — `linear`, `easeIn`, `easeOut`, `smoothstep` (ease in/out), plus the `EASING_CURVES` map keyed by the declarative Three.js clip contract's easing enum. Extend here rather than re-defining an easing inline. || `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). || `modelFit` | `fitModelToHeight(object, { targetHeight, feetOnGround, yOffset })` — normalize a loaded GLB to a fixed on-screen height and anchor it vertically, either by bounding-box center (portrait framing) or by its lowest point (a figure standing on a ground plane). Recenters x/z, guards a zero-height model against an infinite scale, leaves a geometry-less object or a non-finite `targetHeight` untouched rather than writing `NaN`/`Infinity` through the transform, and resets to identity before measuring so a repeat call (StrictMode's double mount effect) converges instead of blowing the model back up. Call from an effect, never during render — a skinned mesh measures wrong before `useAnimations` binds the skeleton. || `sleep` | `sleep(ms)` — promise-returning `setTimeout` for retry backoffs and race timeouts. Use instead of re-declaring a local `delay`. |diff --git a/client/src/utils/easing.js b/client/src/utils/easing.jsindex 309f946eb2..f09c7f7378 100644--- a/client/src/utils/easing.js+++ b/client/src/utils/easing.js@@ -3,3 +3,20 @@// Classic Hermite smoothstep: eases in and out, t clamped to [0,1] by the caller.export const smoothstep = (t) => t * t * (3 - 2 * t);++// Quadratic ease in/out. Paired with `smoothstep` (which is the ease-in-out of+// this set) they cover the four easing names the declarative Three.js clip+// contract allows (`server/lib/threejsModel.js`).+export const linear = (t) => t;+export const easeIn = (t) => t * t;+export const easeOut = (t) => t * (2 - t);++// Keyed by the clip contract's easing enum, so an evaluator resolves a NAME to+// a curve instead of branching on it. An unknown name is the caller's problem —+// look it up with a `linear` fallback rather than trusting the map to have it.+export const EASING_CURVES = Object.freeze({+ linear,+ easeIn,+ easeOut,+ easeInOut: smoothstep,+});diff --git a/docs/THREEJS_MODELS.md b/docs/THREEJS_MODELS.mdindex 3b2dfa34f9..08f4783b77 100644--- a/docs/THREEJS_MODELS.md+++ b/docs/THREEJS_MODELS.md@@ -7,7 +7,8 @@ procedural Three.js scene with:- a validated, bounded JSON scene spec rather than model-authored executableJavaScript;- a live in-browser orbit/zoom preview using PortOS's existing Three.js stack,- with explode-to-disassemble and click-to-identify part picking;+ 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;- gallery-image lineage, run attribution, detail inventory, and honestsingle-view limitations.@@ -59,6 +60,52 @@ The exported standalone factory carries the same information —`buildThreejsFactorySource()` writes `partId` and `explodeWithParent` into eachnode's `userData` — so a consumer outside PortOS can build the same disassembly.+## Animation clips++A spec may declare an optional `animation` block: named **clips** (deploy,+retract, assemble, destroy, idle) built from named **sequences**, each carrying+one part from one authored endpoint to another inside a bounded time window.+Absent means the model is a static assembly — every spec written before clips+shipped keeps parsing, rendering, and exporting unchanged.++Clips are data, never code. A sequence names an easing (`linear`, `easeIn`,+`easeOut`, `easeInOut`) rather than supplying a curve, and drives only+`position`, `rotationDegrees`, `scale`, `opacity`, and `visible`. Materials,+lights, the camera, and geometry parameters are not animatable, so playback can+never change what the model *is*. Nothing is skinned: this is declared motion+over the existing part hierarchy, not a skeleton or a bind pose.++The schema rejects the ways a clip can be meaningless rather than letting the+runtime paper over them: a window that ends before it starts or outruns its+clip, a sequence whose endpoints are equal, two sequences driving one part's+channel at overlapping times, a sequence pointed at a part that does not exist,+and an unknown easing. `visible` is a **step**, not a fade — the part holds+`from` for the whole window and takes `to` the instant the sequence ends — so a+part that should appear mid-clip is authored as its own short sequence ending at+that moment.++Evaluation is a pure function of (clip, time) in+`client/src/lib/threejsAnimation.js`: 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. So+scrubbing, playing, and a test all produce the same pose, and a part no sequence+drives renders exactly as authored.++### Sound cues++A sequence may name a `cueId` pointing at an entry in `animation.cues` — an+identifier and a kind (`latch`, `servo`, `hydraulic`, …), never a filename, a+URL, or audio data. PortOS ships no audio and plays none; the preview forwards+crossed cues to an optional `onCue` callback so a host can map them to its own+sounds. **Playback fires cues; scrubbing never does** — that split is the entire+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 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.+## Geometry vocabularyAlongside the primitives (box, sphere, cylinder, cone, torus, capsule, lathe)diff --git a/server/lib/README.md b/server/lib/README.mdindex 12df2c42ca..f93e28fc39 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -173,6 +173,7 @@ 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. || `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 28e467199c..150b537eba 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -50,6 +50,7 @@ export * from './validation.js';// same objects — same identity, so the collision detector is satisfied.export * from './sharedSchemas.js';export * from './threejsModel.js';+export * from './threejsModelAnimation.js';export * from './threejsModelCoverage.js';export * from './threejsModelFamilies.js';export * from './threejsModelPenetration.js';diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.jsindex 8307dbe9ad..5b2529fb79 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -359,7 +359,169 @@ const detailSchema = z.object({priority: z.enum(['identity', 'major', 'minor']).default('major'),});-const makeSpecSchema = (partSchema) => z.object({+// Animation clips. PortOS still builds STATIC assemblies — nothing here is+// skinned, bound, or deformed, and no provider-authored JavaScript ever runs.+// A clip is a DECLARATION of transforms over time: named sequences that carry+// one part from one authored pose to another inside a bounded window, so a+// deployable can demonstrate assembly, retraction, or destruction and a+// timeline can scrub it deterministically.+//+// Absent `animation` means "static assembly", exactly the way absent+// `articulation` means "no declared joints" — a spec written before clips+// shipped keeps parsing, rendering, and exporting unchanged.+export const THREEJS_CLIP_EASINGS = ['linear', 'easeIn', 'easeOut', 'easeInOut'];+export const THREEJS_CLIP_ROLES = ['deploy', 'retract', 'assemble', 'destroy', 'idle', 'custom'];+// Cue KINDS, not sounds: PortOS ships no audio and loads none. A cue is a data+// identifier a host may map to its own sample, and the kind is the only hint+// about what it should sound like.+export const THREEJS_CUE_KINDS = ['mechanical', 'servo', 'latch', 'hydraulic', 'impact', 'electronic', 'ambient'];++const MAX_CLIP_SECONDS = 120;+const MIN_CLIP_SECONDS = 0.05;+const clipSeconds = z.number().finite().min(0).max(MAX_CLIP_SECONDS);+const unitInterval = z.number().finite().min(0).max(1);++// Every channel is a bounded pair of authored endpoints. There are no keyframe+// arrays and no provider-authored curves: an easing NAME picks one of four+// interpolations PortOS implements, which is what keeps playback deterministic+// and the contract small enough to validate exhaustively.+const rangeSchema = (valueSchema) => z.object({ from: valueSchema, to: valueSchema });++const cueSchema = z.object({+ id: idSchema,+ label: z.string().trim().min(1).max(120),+ kind: z.enum(THREEJS_CUE_KINDS).default('mechanical'),+});++// `visible` is a STEP, not an interpolation: the part holds `from` for the whole+// window and takes `to` the instant the sequence completes. A part that should+// appear part-way through a clip is authored as its own short sequence ending at+// that instant — which keeps the evaluator a pure function of time with no+// hidden fade semantics.+const CHANNEL_KEYS = ['position', 'rotationDegrees', 'scale', 'opacity', 'visible'];+// A sound cue synchronizes to MOVEMENT. A fade or a visibility flip has no+// mechanism behind it to hear, so it cannot be what a cue is attached to.+const MOTION_CHANNEL_KEYS = ['position', 'rotationDegrees', 'scale'];++const rangeChanges = (range) => {+ if (!range) return false;+ const { from, to } = range;+ if (Array.isArray(from) && Array.isArray(to)) return from.some((value, axis) => value !== to[axis]);+ return from !== to;+};++const makeSequenceSchema = (scaleSchema) => z.object({+ id: idSchema,+ name: z.string().trim().min(1).max(120),+ partId: idSchema,+ startSeconds: clipSeconds,+ endSeconds: clipSeconds,+ easing: z.enum(THREEJS_CLIP_EASINGS).default('easeInOut'),+ channels: z.object({+ position: rangeSchema(vec3Schema).optional(),+ rotationDegrees: rangeSchema(vec3Schema).optional(),+ scale: rangeSchema(scaleSchema).optional(),+ opacity: rangeSchema(unitInterval).optional(),+ visible: rangeSchema(z.boolean()).optional(),+ }),+ // The cue this sequence fires when the playhead crosses its start during+ // PLAYBACK. Scrubbing never fires anything — that split is the whole reason+ // the cue is data rather than an embedded sound.+ cueId: idSchema.nullable().default(null),+}).superRefine((sequence, ctx) => {+ if (!(sequence.endSeconds > sequence.startSeconds)) {+ ctx.addIssue({ code: 'custom', message: 'a sequence must end after it starts', path: ['endSeconds'] });+ }+ const changed = CHANNEL_KEYS.filter((key) => rangeChanges(sequence.channels[key]));+ if (changed.length === 0) {+ // A sequence whose endpoints are equal occupies a window on the timeline and+ // moves nothing — indistinguishable from a modeling slip, and it would make+ // the overlap rule below reject a real sequence in the same window.+ ctx.addIssue({ code: 'custom', message: 'a sequence must change at least one channel', path: ['channels'] });+ }+ if (sequence.cueId && !changed.some((key) => MOTION_CHANNEL_KEYS.includes(key))) {+ ctx.addIssue({+ code: 'custom',+ message: `sequence ${sequence.id} fires cue ${sequence.cueId} without moving the part — attach a cue to a sequence that changes position, rotation, or scale`,+ path: ['cueId'],+ });+ }+});++const makeClipSchema = (scaleSchema) => z.object({+ id: idSchema,+ name: z.string().trim().min(1).max(120),+ role: z.enum(THREEJS_CLIP_ROLES).default('custom'),+ durationSeconds: z.number().finite().min(MIN_CLIP_SECONDS).max(MAX_CLIP_SECONDS),+ loop: z.boolean().default(false),+ sequences: z.array(makeSequenceSchema(scaleSchema)).min(1).max(120),+}).superRefine((clip, ctx) => {+ const sequenceIds = new Set();+ // One window per part per channel. Two sequences driving the same channel of+ // the same part at the same time have no defined result — whichever the+ // evaluator happened to visit last would win, so the ambiguity is rejected at+ // authoring time instead of resolved by declaration order.+ const windows = new Map();+ clip.sequences.forEach((sequence, index) => {+ if (sequenceIds.has(sequence.id)) {+ ctx.addIssue({ code: 'custom', message: `duplicate sequence id: ${sequence.id}`, path: ['sequences', index, 'id'] });+ }+ sequenceIds.add(sequence.id);+ if (sequence.endSeconds > clip.durationSeconds) {+ ctx.addIssue({+ code: 'custom',+ message: `sequence ${sequence.id} ends at ${sequence.endSeconds}s, past the clip's ${clip.durationSeconds}s duration`,+ path: ['sequences', index, 'endSeconds'],+ });+ }+ for (const channel of CHANNEL_KEYS) {+ if (!sequence.channels[channel]) continue;+ const key = `${sequence.partId}|${channel}`;+ const claimed = windows.get(key) || [];+ const clash = claimed.find((other) => sequence.startSeconds < other.endSeconds && other.startSeconds < sequence.endSeconds);+ if (clash) {+ ctx.addIssue({+ code: 'custom',+ message: `sequences ${clash.id} and ${sequence.id} both drive ${channel} of part ${sequence.partId} at the same time`,+ path: ['sequences', index, 'channels', channel],+ });+ }+ claimed.push(sequence);+ windows.set(key, claimed);+ }+ });+});++const makeAnimationSchema = (scaleSchema) => z.object({+ clips: z.array(makeClipSchema(scaleSchema)).min(1).max(12),+ cues: z.array(cueSchema).max(24).default([]),+}).superRefine((animation, ctx) => {+ const cueIds = new Set();+ animation.cues.forEach((cue, index) => {+ if (cueIds.has(cue.id)) {+ ctx.addIssue({ code: 'custom', message: `duplicate cue id: ${cue.id}`, path: ['cues', index, 'id'] });+ }+ cueIds.add(cue.id);+ });+ const clipIds = new Set();+ animation.clips.forEach((clip, clipIndex) => {+ if (clipIds.has(clip.id)) {+ ctx.addIssue({ code: 'custom', message: `duplicate clip id: ${clip.id}`, path: ['clips', clipIndex, 'id'] });+ }+ clipIds.add(clip.id);+ clip.sequences.forEach((sequence, index) => {+ if (sequence.cueId && !cueIds.has(sequence.cueId)) {+ ctx.addIssue({+ code: 'custom',+ message: `unknown cue: ${sequence.cueId}`,+ path: ['clips', clipIndex, 'sequences', index, 'cueId'],+ });+ }+ });+ });+});++const makeSpecSchema = (scaleSchema) => z.object({schemaVersion: z.literal(1),name: z.string().trim().min(1).max(120),summary: z.string().trim().min(1).max(1_000),@@ -375,11 +537,14 @@ const makeSpecSchema = (partSchema) => z.object({.refine((materials) => Object.keys(materials).length > 0, 'at least one material is required').refine((materials) => Object.keys(materials).length <= 50, 'at most 50 materials are allowed'),lights: z.array(lightSchema).min(1).max(8),- parts: z.array(partSchema).min(1).max(40),+ parts: z.array(makePartSchema(scaleSchema)).min(1).max(40),sockets: z.array(socketSchema).max(40).default([]),// Optional and additive: a spec written before articulation shipped simply has// no key, which every consumer reads as "static assembly", never as "rigged".articulation: articulationSchema.optional(),+ // Same contract: absent means the model is a static assembly with nothing to+ // play, which is what every spec authored before clips shipped says.+ animation: makeAnimationSchema(scaleSchema).optional(),detailInventory: z.array(detailSchema).min(1).max(80),}).superRefine((spec, ctx) => {const materialIds = new Set(Object.keys(spec.materials));@@ -472,6 +637,20 @@ const makeSpecSchema = (partSchema) => z.object({}}+ if (spec.animation) {+ for (const [clipIndex, clip] of spec.animation.clips.entries()) {+ for (const [index, sequence] of clip.sequences.entries()) {+ if (!partIds.has(sequence.partId)) {+ ctx.addIssue({+ code: 'custom',+ message: `unknown sequence part: ${sequence.partId}`,+ path: ['animation', 'clips', clipIndex, 'sequences', index, 'partId'],+ });+ }+ }+ }+ }+for (const [index, detail] of spec.detailInventory.entries()) {for (const [partIndex, id] of detail.implementationPartIds.entries()) {if (!partIds.has(id)) {@@ -486,7 +665,7 @@ const makeSpecSchema = (partSchema) => z.object({* floored here, so a spec that would render a part reflected or collapsed is* rejected at the one moment the model can still be asked for another pass.*/-export const threejsSculptSpecSchema = makeSpecSchema(makePartSchema(scale3Schema));+export const threejsSculptSpecSchema = makeSpecSchema(scale3Schema);/*** The READ contract for a spec an install has already stored. Identical except@@ -501,7 +680,7 @@ export const threejsSculptSpecSchema = makeSpecSchema(makePartSchema(scale3Schem* this schema is entitled to make, so an existing record exports exactly as it* renders, while the bound above keeps any NEW spec from acquiring the problem.*/-export const storedThreejsSculptSpecSchema = makeSpecSchema(makePartSchema(vec3Schema));+export const storedThreejsSculptSpecSchema = makeSpecSchema(vec3Schema);const MAX_NAMES_IN_MESSAGE = 8;@@ -1066,6 +1245,12 @@ export function ${factoryName}() {// known single-rooted, acyclic, and pointed at real parts and sockets. It is// NOT a skeleton: nothing here is skinned, bound, or deformed.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.+ animation: spec.animation || null,detailInventory: spec.detailInventory,limitations: spec.limitations,};diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex 10495c205e..1892cbf394 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -859,3 +859,169 @@ describe('buildThreejsMaterialFeedback', () => {expect(feedback).toContain('steelPlate');});});++const animatedSpec = () => {+ const spec = validSpec();+ spec.animation = {+ cues: [{ id: 'latchRelease', label: 'Latch lets go', kind: 'latch' }],+ clips: [{+ id: 'deploy',+ name: 'Deploy',+ role: 'deploy',+ durationSeconds: 2,+ sequences: [+ {+ id: 'liftLid',+ name: 'Lift lid',+ partId: 'frontTrim',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'easeOut',+ channels: { position: { from: [0, 0, 0.64], to: [0, 0.6, 0.64] } },+ cueId: 'latchRelease',+ },+ {+ id: 'hideTrim',+ name: 'Hide trim',+ partId: 'frontTrim',+ startSeconds: 1,+ endSeconds: 2,+ channels: { visible: { from: true, to: false } },+ },+ ],+ }],+ };+ return spec;+};++const animationIssues = (mutate) => {+ const spec = animatedSpec();+ mutate(spec);+ const result = threejsSculptSpecSchema.safeParse(spec);+ expect(result.success).toBe(false);+ return result.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`);+};++describe('threejsSculptSpecSchema animation', () => {+ it('accepts a well-formed clip and fills the optional sequence fields', () => {+ const parsed = threejsSculptSpecSchema.parse(animatedSpec());+ expect(parsed.animation.clips[0].loop).toBe(false);+ expect(parsed.animation.clips[0].sequences[1].easing).toBe('easeInOut');+ expect(parsed.animation.clips[0].sequences[1].cueId).toBeNull();+ expect(parsed.animation.cues[0].kind).toBe('latch');+ });++ // The whole point of the field being optional: a record written before clips+ // existed has no key at all, and must not acquire one on read.+ it('leaves a spec that declares no animation without the key, on both contracts', () => {+ expect(threejsSculptSpecSchema.parse(validSpec()).animation).toBeUndefined();+ expect(storedThreejsSculptSpecSchema.parse(validSpec()).animation).toBeUndefined();+ });++ it('accepts a stored animated spec whose part scale predates the authoring floor', () => {+ const spec = animatedSpec();+ spec.parts[0].scale = [1, 0, 1];+ spec.animation.clips[0].sequences[0].channels.scale = { from: [1, 0, 1], to: [1, 1, 1] };+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);+ expect(storedThreejsSculptSpecSchema.safeParse(spec).success).toBe(true);+ });++ it('rejects a sequence pointed at a part that does not exist, naming the path', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[0].partId = 'notARealPart';+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.0.partId: unknown sequence part: notARealPart',+ ]));+ });++ it('rejects a window that ends before it starts and one that outruns its clip', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[0].endSeconds = 0;+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.0.endSeconds: a sequence must end after it starts',+ ]));+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[1].endSeconds = 9;+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.1.endSeconds: sequence hideTrim ends at 9s, past the clip\'s 2s duration',+ ]));+ });++ it('rejects an easing name it does not implement', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[0].easing = 'elasticOut';+ })).toEqual(expect.arrayContaining([expect.stringContaining('animation.clips.0.sequences.0.easing')]));+ });++ it('rejects a sequence whose endpoints are equal, which occupies time and moves nothing', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[0].channels = { position: { from: [0, 0, 0.64], to: [0, 0, 0.64] } };+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.0.channels: a sequence must change at least one channel',+ ]));+ });++ it('rejects a cue on a sequence that only fades or hides — a sound needs motion to ride', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[1].cueId = 'latchRelease';+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.1.cueId: sequence hideTrim fires cue latchRelease without moving the part — attach a cue to a sequence that changes position, rotation, or scale',+ ]));+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[0].channels = { opacity: { from: 1, to: 0 } };+ })).toEqual(expect.arrayContaining([expect.stringContaining('without moving the part')]));+ });++ it('rejects a cue nothing declared', () => {+ expect(animationIssues((spec) => {+ spec.animation.cues = [];+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.0.cueId: unknown cue: latchRelease',+ ]));+ });++ it('rejects two sequences driving one part+channel at overlapping times', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[1].channels = { position: { from: [0, 0.6, 0.64], to: [0, 0, 0.64] } };+ spec.animation.clips[0].sequences[1].startSeconds = 0.5;+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.1.channels.position: sequences liftLid and hideTrim both drive position of part frontTrim at the same time',+ ]));+ });++ // Handing one window off to the next at a shared instant is how a multi-step+ // deployment is authored, so it must NOT read as an overlap.+ it('accepts two windows on one channel that meet end-to-start', () => {+ const spec = animatedSpec();+ spec.animation.clips[0].sequences[1].channels = { position: { from: [0, 0.6, 0.64], to: [0, 0, 0.64] } };+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(true);+ });++ it('rejects duplicate clip, sequence, and cue ids', () => {+ expect(animationIssues((spec) => {+ spec.animation.clips[0].sequences[1].id = 'liftLid';+ })).toEqual(expect.arrayContaining([+ 'animation.clips.0.sequences.1.id: duplicate sequence id: liftLid',+ ]));+ expect(animationIssues((spec) => {+ spec.animation.clips.push({ ...spec.animation.clips[0] });+ })).toEqual(expect.arrayContaining(['animation.clips.1.id: duplicate clip id: deploy']));+ expect(animationIssues((spec) => {+ spec.animation.cues.push({ ...spec.animation.cues[0] });+ })).toEqual(expect.arrayContaining(['animation.cues.1.id: duplicate cue id: latchRelease']));+ });+});++describe('buildThreejsFactorySource animation', () => {+ it('carries validated clips into the exported runtime metadata as data', () => {+ const source = buildThreejsFactorySource(animatedSpec());+ expect(source).toContain('animation: spec.animation || null,');+ expect(source.replace(/\s+/g, '')).toContain('"cueId":"latchRelease"');+ });++ it('exports null animation for a static spec, and never invents a clip', () => {+ const source = buildThreejsFactorySource(validSpec());+ expect(source).toContain('animation: spec.animation || null,');+ expect(source).not.toContain('"sequences"');+ });+});diff --git a/server/lib/threejsModelAnimation.js b/server/lib/threejsModelAnimation.jsnew file mode 100644index 0000000000..457bc0a6a4--- /dev/null+++ b/server/lib/threejsModelAnimation.js@@ -0,0 +1,63 @@+/**+ * Clip inventory 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+ * fight each other for the same channel, and never fire a cue without moving+ * anything. What this reports is what the model actually DECLARED — how many+ * clips, which roles, how much of the assembly moves — so the record carries a+ * durable answer and the workspace can say "static assembly" versus "3 clips"+ * without re-deriving it from the spec on every read.+ *+ * It reports rather than rejects, and it never claims skinning: PortOS builds+ * static assemblies plus declared motion, not skeletons or bind poses.+ */++/**+ * @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}>}}+ */+export function summarizeThreejsAnimation(spec) {+ const animation = spec?.animation || null;+ const clips = Array.isArray(animation?.clips) ? animation.clips : [];+ const cues = Array.isArray(animation?.cues) ? animation.cues : [];+ const movingPartIds = new Set();+ let sequenceCount = 0;+ let longestClipSeconds = 0;++ const summaries = clips.map((clip) => {+ const sequences = Array.isArray(clip.sequences) ? clip.sequences : [];+ sequenceCount += sequences.length;+ // Duration is the authored window, not the last sequence's end: a clip is+ // allowed to hold its final pose after everything has finished moving.+ if (Number.isFinite(clip.durationSeconds) && clip.durationSeconds > longestClipSeconds) {+ longestClipSeconds = clip.durationSeconds;+ }+ for (const sequence of sequences) movingPartIds.add(sequence.partId);+ return {+ id: clip.id,+ name: clip.name,+ role: clip.role || 'custom',+ durationSeconds: clip.durationSeconds,+ sequenceCount: sequences.length,+ // Distinct cues, not sequences carrying one: the same latch firing in+ // four places is one sound the host has to supply, and reporting four+ // would overstate what the clip asks for.+ cueCount: new Set(sequences.map((sequence) => sequence.cueId).filter(Boolean)).size,+ };+ });++ return {+ animated: summaries.length > 0,+ clipCount: summaries.length,+ cueCount: cues.length,+ sequenceCount,+ // Parts a clip actually drives, across every clip — the honest measure of+ // how much of the assembly is more than scenery.+ movingPartCount: movingPartIds.size,+ longestClipSeconds,+ clips: summaries,+ };+}diff --git a/server/lib/threejsModelAnimation.test.js b/server/lib/threejsModelAnimation.test.jsnew file mode 100644index 0000000000..95aeb35a47--- /dev/null+++ b/server/lib/threejsModelAnimation.test.js@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest';+import { summarizeThreejsAnimation } from './threejsModelAnimation.js';++const clip = (overrides = {}) => ({+ id: 'deploy',+ name: 'Deploy',+ role: 'deploy',+ durationSeconds: 3,+ loop: false,+ sequences: [+ {+ id: 'lift',+ name: 'Lift',+ partId: 'panel',+ startSeconds: 0,+ endSeconds: 1,+ easing: 'easeOut',+ channels: { position: { from: [0, 0, 0], to: [0, 1, 0] } },+ cueId: 'latch',+ },+ {+ id: 'swing',+ name: 'Swing',+ partId: 'arm',+ startSeconds: 1,+ endSeconds: 2,+ easing: 'linear',+ channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 90, 0] } },+ cueId: 'latch',+ },+ ],+ ...overrides,+});++describe('summarizeThreejsAnimation', () => {+ it('reports a spec with no animation key as a static assembly, never as evaluated-and-empty', () => {+ for (const spec of [null, undefined, {}, { animation: null }]) {+ expect(summarizeThreejsAnimation(spec)).toMatchObject({+ animated: false,+ clipCount: 0,+ sequenceCount: 0,+ movingPartCount: 0,+ longestClipSeconds: 0,+ });+ }+ });++ it('counts clips, sequences, distinct moving parts, and the longest authored window', () => {+ const summary = summarizeThreejsAnimation({+ animation: {+ cues: [{ id: 'latch', label: 'Latch', kind: 'latch' }],+ clips: [clip(), clip({ id: 'retract', name: 'Retract', role: 'retract', durationSeconds: 5 })],+ },+ });+ expect(summary).toMatchObject({+ animated: true,+ clipCount: 2,+ cueCount: 1,+ sequenceCount: 4,+ // Two parts across four sequences — the same part in two clips is one part.+ movingPartCount: 2,+ longestClipSeconds: 5,+ });+ expect(summary.clips[0]).toEqual({+ id: 'deploy',+ name: 'Deploy',+ role: 'deploy',+ durationSeconds: 3,+ sequenceCount: 2,+ // One cue fired by two sequences is one sound the host has to supply.+ cueCount: 1,+ });+ });++ it('reports the authored duration, not the last sequence end, so a held final pose counts', () => {+ const summary = summarizeThreejsAnimation({ animation: { clips: [clip({ durationSeconds: 8 })] } });+ expect(summary.longestClipSeconds).toBe(8);+ });++ it('defaults a clip that arrived without a role rather than printing undefined', () => {+ const summary = summarizeThreejsAnimation({ animation: { clips: [clip({ role: undefined })] } });+ expect(summary.clips[0].role).toBe('custom');+ });+});diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.jsindex c6c3abb89c..3f4466aeb1 100644--- a/server/services/threejsModels/db.js+++ b/server/services/threejsModels/db.js@@ -95,6 +95,12 @@ 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".+ animation: null,// Material-plausibility findings for `spec`, written alongside it by// `evaluateThreejsMaterialPlausibility`. Same additive-field contract as// `coverage` and `flatness`: an older record reads back undefined, whichdiff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.jsindex f19c7459d3..2c0ed5bb23 100644--- a/server/services/threejsModels/index.js+++ b/server/services/threejsModels/index.js@@ -16,6 +16,7 @@ import {evaluateThreejsMaterialPlausibility,threejsSculptSpecSchema,} from '../../lib/threejsModel.js';+import { 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';@@ -126,6 +127,10 @@ async function executeGeneration({// when it did not, the reason. A model with no graph reports not-ready with// reasons rather than passing silently.const rig = evaluateThreejsRigReadiness(spec);+ // What the spec DECLARED it can play. Nothing is skinned and no clip is+ // executed here — this is the inventory, so the record answers "static+ // assembly" versus "3 clips" without re-deriving it on every read.+ const animation = summarizeThreejsAnimation(spec);const completedAt = new Date().toISOString();const effectiveProvider = result.provider?.id || result.fallbackProvider?.id || provider.id;const effectiveModel = result.model || requestedModel || provider.defaultModel || null;@@ -142,6 +147,7 @@ async function executeGeneration({flatness,penetration,rig,+ animation,materialPlausibility,error: null,generationOperationId: null,@@ -168,6 +174,9 @@ async function executeGeneration({if (materialPlausibility.warningCount > 0) {console.warn(`⚠️ Three.js model ${id} material plausibility: ${materialPlausibility.warningCount} of ${materialPlausibility.matchedMaterialCount} recognized material(s) carry values their substance does not support`);}+ 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 (rig.articulationReady) {console.log(`🦴 Three.js model ${id} declares an articulation graph: ${rig.jointCount} joint(s), ${rig.socketCount} pivot socket(s)`);}diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.jsindex 43de0a9177..3ce2a19e9c 100644--- a/server/services/threejsModels/index.test.js+++ b/server/services/threejsModels/index.test.js@@ -145,6 +145,9 @@ describe('Three.js model generation orchestration', () => {// not-ready WITH a reason rather than passing silently.expect(current.rig).toMatchObject({ articulationReady: false, jointCount: 0, socketCount: 0 });expect(current.rig.reasons).toHaveLength(1);+ // Likewise for clips: a spec that declared none is recorded as a static+ // assembly with nothing to play, never left unevaluated.+ expect(current.animation).toMatchObject({ animated: false, clipCount: 0, sequenceCount: 0 });expect(current.runs.at(-1)).toMatchObject({status: 'completed',runId: 'run-example',@@ -663,3 +666,79 @@ describe('Three.js model generation orchestration', () => {});});});++describe('Three.js model clip inventory', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getProviderById.mockResolvedValue({+ id: 'vision-api',+ name: 'Vision API',+ type: 'api',+ enabled: true,+ defaultModel: 'vision-default',+ });+ });++ it('persists the declared clips alongside the spec, and keeps them on the record', async () => {+ const animatedSpec = {+ ...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,+ channels: { position: { from: [0, 0, 0], to: [0, 0.6, 0] } },+ cueId: 'latchRelease',+ }],+ }],+ },+ };+ let current = {+ id: 'threejs-animated',+ name: 'Example Beacon',+ sourceImage: { filename: 'example.png' },+ providerId: 'vision-api',+ model: null,+ prompt: '',+ status: 'draft',+ spec: null,+ runs: [],+ };+ store.getModel.mockResolvedValue(current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });+ runPromptThroughProvider.mockResolvedValue({+ text: JSON.stringify(animatedSpec),+ runId: 'run-animated',+ provider: { id: 'vision-api' },+ model: null,+ });++ await startGeneration(current.id, { providerId: 'vision-api' });+ await vi.waitFor(() => expect(current.status).toBe('ready'));++ expect(current.animation).toMatchObject({+ animated: true,+ clipCount: 1,+ cueCount: 1,+ sequenceCount: 1,+ movingPartCount: 1,+ longestClipSeconds: 1.5,+ });+ expect(current.animation.clips[0]).toMatchObject({ id: 'deploy', role: 'deploy', cueCount: 1 });+ // 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);+ });+});diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.jsindex d23771be40..b2612df7f8 100644--- a/server/services/threejsModels/prompt.js+++ b/server/services/threejsModels/prompt.js@@ -142,6 +142,62 @@ bones for parts the reference does not clearly show. A short, defensible graph bspeculative one, and omitting the key is better than guessing.`;+// Clips are DATA, not code: named windows over parts the spec already builds,+// with an easing NAME rather than a curve, so PortOS can scrub them+// deterministically and never has to run anything the provider wrote. The block+// is offered for every subject — a deployable can be an object, a character, or+// a hybrid — but the default answer is silence: an assembly with no mechanism+// the reference actually shows is a static model, and inventing motion for it is+// worse than omitting the key.+const animationContract = `+ANIMATION CLIPS (optional, any subject):+Return an "animation" object ONLY if the reference clearly shows a mechanism that deploys,+retracts, opens, folds, spins, or comes apart. Omit the key entirely for a static subject —+a static assembly is a complete answer, and invented motion is not.++"animation": {+ "clips": [{+ "id":"deploy","name":"Deploy","role":"deploy"|"retract"|"assemble"|"destroy"|"idle"|"custom",+ "durationSeconds":0.05..120,"loop":false,+ "sequences": [{+ "id":"stableSequenceId","name":"Readable step name","partId":"partId",+ "startSeconds":n,"endSeconds":n,+ "easing":"linear"|"easeIn"|"easeOut"|"easeInOut",+ "channels": {+ "position":{"from":[x,y,z],"to":[x,y,z]},+ "rotationDegrees":{"from":[x,y,z],"to":[x,y,z]},+ "scale":{"from":[sx,sy,sz],"to":[sx,sy,sz]},+ "opacity":{"from":0..1,"to":0..1},+ "visible":{"from":true,"to":false}+ },+ "cueId":"cueId"+ }]+ }],+ "cues": [{"id":"cueId","label":"What is heard","kind":"mechanical"|"servo"|"latch"|"hydraulic"|"impact"|"electronic"|"ambient"}]+}++Rules, all enforced — a spec that breaks one is rejected outright:+- Every "partId" names a real part. A sequence moves that part and everything parented to it.+- "endSeconds" is strictly greater than "startSeconds", and no sequence ends after its clip's+ "durationSeconds". A clip may hold its final pose after the last sequence finishes.+- Every sequence changes at least one channel: a "from" equal to its "to" moves nothing.+- Two sequences may not drive the same channel of the same part at overlapping times. Chain them+ end-to-start instead, and start the next one from where the previous one ended so the part does+ not jump.+- "visible" is a step, not a fade: the part holds "from" for the whole window and takes "to" the+ instant the sequence ends. To make a part appear part-way through, give it its own short+ sequence ending at that moment.+- Every "cueId" names an entry in "cues", and a cue may only ride a sequence that changes+ position, rotationDegrees, or scale — a sound has to have movement to synchronize to. Cues are+ identifiers only: never a filename, a URL, or audio data. PortOS plays no sound for them.+- 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.++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".+`;+export function buildThreejsGenerationPrompt({sourcePath,name,@@ -204,5 +260,5 @@ QUALITY GATE:under-observed the reference.` : ''}${geometryContract}-${outputContract}${articulation}`;+${outputContract}${articulation}${animationContract}`;}diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.jsindex 7a1c65110c..52557a53d9 100644--- a/server/services/threejsModels/prompt.test.js+++ b/server/services/threejsModels/prompt.test.js@@ -136,3 +136,42 @@ describe('buildThreejsGenerationPrompt articulation gating fallbacks', () => {expect(unknownUnderCharacter).not.toContain('ARTICULATION');});});++describe('buildThreejsGenerationPrompt animation clips', () => {+ // Offered for every subject: a deployable can be an object, a character, or a+ // hybrid, so the clip contract is not gated the way articulation is.+ it('offers the clip contract whatever the subject is, and tells the model to omit it by default', () => {+ for (const overrides of [+ {},+ { family: 'vehicle' },+ { family: 'character', currentSpec: { schemaVersion: 1, name: 'Example Model', subjectType: 'character' } },+ ]) {+ const prompt = build(overrides);+ expect(prompt).toContain('ANIMATION CLIPS (optional, any subject)');+ expect(prompt).toContain('Omit the key entirely for a static subject');+ }+ });++ it('states the rules the schema actually enforces, so a rejection is never a surprise', () => {+ const prompt = build();+ expect(prompt).toContain('Every sequence changes at least one channel');+ expect(prompt).toContain('may not drive the same channel of the same part at overlapping times');+ expect(prompt).toContain('"visible" is a step, not a fade');+ expect(prompt).toContain('a cue may only ride a sequence that changes');+ expect(prompt).toContain('do not return JavaScript, keyframe arrays, or curve definitions');+ });++ it('names every easing and clip role the schema accepts', () => {+ const prompt = build();+ for (const easing of ['linear', 'easeIn', 'easeOut', 'easeInOut']) {+ expect(prompt).toContain(`"${easing}"`);+ }+ for (const role of ['deploy', 'retract', 'assemble', 'destroy', 'idle']) {+ expect(prompt).toContain(`"${role}"`);+ }+ });++ it('says a cue is an identifier, never audio PortOS would load', () => {+ expect(build()).toContain('never a filename, a URL, or audio data');+ });+});