Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: centralize safe GLTF clones (#3208)

[._.]/ Adam Eivy656281092b6b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dfe16ba12a..42851a4281 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## 3D avatars
+
+- **[issue-3208] Shared GLB avatars now keep their cached model resources intact by construction.** CyberCity, Chief of Staff, and generated-model views render cached or cloned scenes through one safe path, preventing future avatar additions from reintroducing blank meshes after navigation or remounts.
+
## Added
- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.
diff --git a/client/src/components/city/PlayerAvatar.jsx b/client/src/components/city/PlayerAvatar.jsx
index ea1e295e2f..52ae16fb12 100644
--- a/client/src/components/city/PlayerAvatar.jsx
+++ b/client/src/components/city/PlayerAvatar.jsx
@@ -1,11 +1,11 @@
import { useRef, useMemo, useEffect, useCallback } from 'react';
import { useFrame } from '@react-three/fiber';
-import { useGLTF, useAnimations } from '@react-three/drei';
+import { useGLTF } from '@react-three/drei';
import * as THREE from 'three';
-import { SkeletonUtils } from 'three-stdlib';
import { useCityPalette } from './CityPaletteContext';
import { dampFactor, EYE_HEIGHT } from '../../utils/cityPlayerRig';
import { withInPlaceClips, inPlaceClipName } from '../../utils/animationClips';
+import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
// The root-motion clip set + treadmill suffix are model-level facts about the bundled
// RobotExpressive GLB, so import the single source of truth rather than redeclaring it —
// a divergent copy would silently break in-place routing in one avatar and not the other.
@@ -34,6 +34,9 @@ const FADE = 0.25; // crossfade seconds between state clips
// If a user swaps in a GLB with a different forward axis, the runner would face the wrong
// way — this offset is the one model-orientation assumption, called out so it's greppable.
const MODEL_FACING_OFFSET = Math.PI;
+const buildPlayerAnimations = (animations) => (
+ withInPlaceClips(animations, ROOT_MOTION_CLIPS, IN_PLACE_SUFFIX)
+);
// rig.state → { desired GLB clip, playback rate }. The clip is auto-routed to its
// in-place variant when it's a root-motion clip. Rates lean a touch fast so the gait
@@ -47,20 +50,9 @@ const STATE_CLIP = {
export default function PlayerAvatar({ rigRef }) {
const { accent } = useCityPalette();
- const gltf = useGLTF(MODEL_URL);
-
- // SkeletonUtils.clone rebinds SkinnedMeshes to the cloned skeleton so the mixer
- // actually deforms the visible mesh (a plain scene.clone would animate bones the
- // rendered mesh no longer references). Memoized on the source scene.
- const scene = useMemo(() => SkeletonUtils.clone(gltf.scene), [gltf.scene]);
-
- // Append neutralized in-place variants of the root-motion clips so walk/run cycle
- // the legs without translating the model off the rig-driven position.
- const animations = useMemo(
- () => withInPlaceClips(gltf.animations, ROOT_MOTION_CLIPS, IN_PLACE_SUFFIX),
- [gltf.animations]
- );
- const { actions, names } = useAnimations(animations, scene);
+ // Append neutralized in-place variants of the root-motion clips so walk/run
+ // cycles the legs without translating the model off the rig-driven position.
+ const { scene, actions, names } = useClonedGltf(MODEL_URL, buildPlayerAnimations);
const hasClips = names.length > 0;
const rootRef = useRef();
@@ -162,11 +154,8 @@ export default function PlayerAvatar({ rigRef }) {
return (
<group ref={rootRef}>
- {/* scene carries its own fit scale/position (applied in the effect above).
- dispose={null}: the clone shares geometry/material refs with the useGLTF cache
- (SkeletonUtils.clone is shallow for those), so letting r3f dispose them on unmount
- would corrupt the cache for the next mount / the CoS Muse avatar. */}
- <primitive object={scene} dispose={null} />
+ {/* scene carries its own fit scale/position (applied in the effect above). */}
+ <GltfPrimitive object={scene} />
{/* Accent-tinted ground glow — the runner's neon footprint. Declared as JSX so R3F
owns the geometry/material lifecycle; `color` tracks the theme reactively and the
per-frame opacity write goes through discMatRef. */}
diff --git a/client/src/components/cos/MiniCharacterCoSAvatar.jsx b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
index 295c4e579e..8abaa21d0a 100644
--- a/client/src/components/cos/MiniCharacterCoSAvatar.jsx
+++ b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
@@ -1,12 +1,12 @@
import { useRef, useMemo, useEffect, useState, Suspense, Component } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
-import { useGLTF, useAnimations } from '@react-three/drei';
+import { useGLTF } from '@react-three/drei';
import * as THREE from 'three';
-import { SkeletonUtils } from 'three-stdlib';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
import CoSAvatarFrame from './CoSAvatarFrame';
import CoSBackgroundCamera from './CoSBackgroundCamera';
+import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
// Kenney Mini Characters (CC0) ship 32 named clips. We map the CoS agent
// states onto the most evocative ones. Each entry has a clip name plus a
@@ -38,15 +38,8 @@ function buildModelUrl(variant) {
function MiniCharacter({ state, speaking, variant }) {
const url = useMemo(() => buildModelUrl(variant), [variant]);
- const gltf = useGLTF(url);
const group = useRef();
-
- // Clone via SkeletonUtils — a plain Object3D.clone() does NOT rebind the
- // SkinnedMesh to the cloned skeleton, so AnimationMixer would drive bones
- // the visible mesh no longer references and nothing moves. SkeletonUtils
- // rebuilds the bone bindings on the clone so animations actually deform it.
- const scene = useMemo(() => SkeletonUtils.clone(gltf.scene), [gltf.scene]);
- const { actions, names } = useAnimations(gltf.animations, scene);
+ const { scene, actions, names } = useClonedGltf(url);
// Fit the character into a consistent height regardless of source scale.
// Kenney mini-characters are authored ~1.7 units tall already, but we
@@ -101,11 +94,7 @@ function MiniCharacter({ state, speaking, variant }) {
return (
<group ref={group}>
- {/* dispose={null}: SkeletonUtils.clone shares geometry/material refs with
- drei's useGLTF cache (the clone is shallow for those), so letting R3F
- dispose them on unmount corrupts the cache and the next mount renders
- disposed buffers as an invisible mesh (see the CoS Muse avatar). */}
- <primitive object={scene} dispose={null} />
+ <GltfPrimitive object={scene} />
</group>
);
}
diff --git a/client/src/components/cos/MuseCoSAvatar.jsx b/client/src/components/cos/MuseCoSAvatar.jsx
index 3777eca189..cba7adc198 100644
--- a/client/src/components/cos/MuseCoSAvatar.jsx
+++ b/client/src/components/cos/MuseCoSAvatar.jsx
@@ -1,8 +1,7 @@
import { useRef, useMemo, useEffect, useState, useCallback, Suspense, Component } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
-import { useGLTF, useAnimations, Sparkles } from '@react-three/drei';
+import { useGLTF, Sparkles } from '@react-three/drei';
import * as THREE from 'three';
-import { SkeletonUtils } from 'three-stdlib';
import {
AGENT_STATES,
MUSE_STATE_ANIMATIONS,
@@ -16,9 +15,13 @@ import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
import CoSAvatarFrame from './CoSAvatarFrame';
import CoSBackgroundCamera from './CoSBackgroundCamera';
import { withInPlaceClips, inPlaceClipName } from '../../utils/animationClips';
+import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
const MODEL_URL = '/api/avatar/model.glb';
const FADE = 0.35; // crossfade seconds between state loops
+const buildMuseAnimations = (animations) => (
+ withInPlaceClips(animations, MUSE_ROOT_MOTION_CLIPS, MUSE_IN_PLACE_SUFFIX)
+);
// Loaded avatar rendered with its own textures/materials. When the GLB ships
// animation clips (the bundled RobotExpressive default does), an AnimationMixer
@@ -27,21 +30,13 @@ const FADE = 0.35; // crossfade seconds between state loops
// lives entirely in the surrounding lights/halo/glow/sparkles (see Scene) — the
// model itself keeps its real colors rather than being tinted.
function GLBAvatar({ state, speaking }) {
- const gltf = useGLTF(MODEL_URL);
const ref = useRef();
-
- // SkeletonUtils.clone rebinds SkinnedMeshes to the cloned skeleton so the
- // AnimationMixer actually deforms the visible mesh. A plain scene.clone(true)
- // leaves the mixer driving bones the rendered mesh no longer references, so
- // nothing would move — the reason clips were previously ignored.
- const scene = useMemo(() => SkeletonUtils.clone(gltf.scene), [gltf.scene]);
// Append the treadmill (in-place) variants of the root-motion clips so the
- // coding montage can run/walk without drifting. Memoized on the source clips.
- const animations = useMemo(
- () => withInPlaceClips(gltf.animations, MUSE_ROOT_MOTION_CLIPS, MUSE_IN_PLACE_SUFFIX),
- [gltf.animations]
+ // coding montage can run/walk without drifting.
+ const { scene, actions, names, mixer } = useClonedGltf(
+ MODEL_URL,
+ buildMuseAnimations,
);
- const { actions, names, mixer } = useAnimations(animations, scene);
const hasClips = names.length > 0;
// Fit the model to the viewport ONCE per scene (absolute `setScalar`, so it
@@ -235,11 +230,7 @@ function GLBAvatar({ state, speaking }) {
return (
<group ref={ref}>
- {/* dispose={null}: SkeletonUtils.clone shares geometry/material refs with
- drei's useGLTF cache (shallow clone), so letting R3F dispose them on
- unmount corrupts the cache — the next mount then renders disposed
- buffers as an invisible mesh, leaving only the halo ring ("SVG circle"). */}
- <primitive object={scene} dispose={null} />
+ <GltfPrimitive object={scene} />
</group>
);
}
diff --git a/client/src/components/media/GlbViewer.jsx b/client/src/components/media/GlbViewer.jsx
index bd476dffcf..f62686e60d 100644
--- a/client/src/components/media/GlbViewer.jsx
+++ b/client/src/components/media/GlbViewer.jsx
@@ -7,6 +7,7 @@ import {
useGLTF,
} from '@react-three/drei';
import { Download, Rotate3d, SlidersHorizontal } from 'lucide-react';
+import { GltfPrimitive } from '../../hooks/useClonedGltf';
const DEFAULT_BACKGROUND = '#050505';
const ENVIRONMENT_HDRI = '/hdri/studio-small-08-1k.hdr';
@@ -71,13 +72,7 @@ function GlbModel({ src, forceOpaque }) {
});
};
}, [forceOpaque, renderedScene]);
- // dispose={null}: when !forceOpaque this primitive renders drei's cached scene
- // directly, and even the forceOpaque clone shares geometry refs with the cache
- // (scene.clone(true) is shallow for geometry). Letting R3F auto-dispose those
- // GPU buffers on unmount would empty the cache the comment above deliberately
- // keeps, so revisiting the same `src` would render a blank mesh. The cloned
- // opaque *materials* (not shared) are still freed by the cleanup effect above.
- return <primitive object={renderedScene} dispose={null} />;
+ return <GltfPrimitive object={renderedScene} />;
}
// Own `scene.environmentIntensity` directly rather than passing drei's
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 678f66f847..ef7f96c5c0 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -63,6 +63,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMediaCompletionRefresh` | Refetch on image/video completion socket events. | A list view that needs to refresh when new media lands. |
| `useOpenClawAttachments` | File attachment handling (base64, size-capped). | OpenClaw attachment UI. |
| `useMediaPreviewActions` | Shared MediaPreview / MediaLightbox action handlers (images + videos — dispatch by `item.kind`). | New surface that exposes the same 4 preview actions. |
+| `useClonedGltf` | Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated `GltfPrimitive` prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. | Any skinned GLTF rendered from `useGLTF`; render its scene through `GltfPrimitive` so remounts cannot inherit disposed geometry or materials. |
| `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. |
| `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |
| `useImageRenderSettings` | Load the pipeline image-gen config once (`getSettings → readPipelineImageSettings`), failing open to `PIPELINE_IMAGE_DEFAULTS`; returns `{ imageCfg }`. | A single-image render slot that needs the render config and doesn't already load the full settings blob. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 392ff53fc7..ef8a0cd5d6 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -11,6 +11,8 @@
export { default as useAnchorReveal } from './useAnchorReveal.js';
export { default as useAutoscroll } from './useAutoscroll.js';
export { default as useCityAudio } from './useCityAudio.js';
+export { default as useClonedGltf } from './useClonedGltf.jsx';
+export * from './useClonedGltf.jsx';
export { default as useAutoSizeTextarea } from './useAutoSizeTextarea.js';
export { default as useChartColors } from './useChartColors.js';
export * from './useChartColors.js';
diff --git a/client/src/hooks/useClonedGltf.jsx b/client/src/hooks/useClonedGltf.jsx
new file mode 100644
index 0000000000..882f8b58c6
--- /dev/null
+++ b/client/src/hooks/useClonedGltf.jsx
@@ -0,0 +1,24 @@
+import { useMemo } from 'react';
+import { useAnimations, useGLTF } from '@react-three/drei';
+import { SkeletonUtils } from 'three-stdlib';
+
+const preserveAnimations = (animations) => animations;
+
+export function GltfPrimitive({ object, ...props }) {
+ // SkeletonUtils.clone and Object3D.clone share geometry/material references
+ // with drei's URL-keyed useGLTF cache. R3F must never auto-dispose those
+ // shared resources on unmount, or the next mount of the URL renders blank.
+ return <primitive {...props} object={object} dispose={null} />;
+}
+
+export default function useClonedGltf(url, transformAnimations = preserveAnimations) {
+ const gltf = useGLTF(url);
+ const scene = useMemo(() => SkeletonUtils.clone(gltf.scene), [gltf.scene]);
+ const animations = useMemo(
+ () => transformAnimations(gltf.animations),
+ [gltf.animations, transformAnimations],
+ );
+ const { actions, mixer, names } = useAnimations(animations, scene);
+
+ return { scene, animations, actions, mixer, names };
+}
diff --git a/client/src/hooks/useClonedGltf.test.jsx b/client/src/hooks/useClonedGltf.test.jsx
new file mode 100644
index 0000000000..7b51753044
--- /dev/null
+++ b/client/src/hooks/useClonedGltf.test.jsx
@@ -0,0 +1,70 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import useClonedGltf, { GltfPrimitive } from './useClonedGltf.jsx';
+
+const mocks = vi.hoisted(() => ({
+ clone: vi.fn(),
+ useAnimations: vi.fn(),
+ useGLTF: vi.fn(),
+}));
+
+vi.mock('@react-three/drei', () => ({
+ useAnimations: mocks.useAnimations,
+ useGLTF: mocks.useGLTF,
+}));
+
+vi.mock('three-stdlib', () => ({
+ SkeletonUtils: { clone: mocks.clone },
+}));
+
+describe('useClonedGltf', () => {
+ beforeEach(() => {
+ mocks.clone.mockReset();
+ mocks.useAnimations.mockReset();
+ mocks.useGLTF.mockReset();
+ });
+
+ it('clones the cached scene and binds transformed animations to the clone', () => {
+ const sourceScene = { name: 'source' };
+ const clonedScene = { name: 'clone' };
+ const sourceAnimations = [{ name: 'Walk' }];
+ const transformedAnimations = [{ name: 'Walk-in-place' }];
+ const transformAnimations = vi.fn(() => transformedAnimations);
+ const animationState = {
+ actions: { 'Walk-in-place': {} },
+ mixer: {},
+ names: ['Walk-in-place'],
+ };
+ mocks.useGLTF.mockReturnValue({ scene: sourceScene, animations: sourceAnimations });
+ mocks.clone.mockReturnValue(clonedScene);
+ mocks.useAnimations.mockReturnValue(animationState);
+
+ const { result, rerender } = renderHook(() => (
+ useClonedGltf('/example.glb', transformAnimations)
+ ));
+
+ expect(mocks.clone).toHaveBeenCalledWith(sourceScene);
+ expect(transformAnimations).toHaveBeenCalledWith(sourceAnimations);
+ expect(mocks.useAnimations).toHaveBeenCalledWith(transformedAnimations, clonedScene);
+ expect(result.current).toEqual({
+ scene: clonedScene,
+ animations: transformedAnimations,
+ ...animationState,
+ });
+
+ rerender();
+ expect(mocks.clone).toHaveBeenCalledTimes(1);
+ expect(transformAnimations).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders shared GLTF resources with disposal disabled', () => {
+ const object = {};
+ const element = GltfPrimitive({ object, dispose: true, name: 'avatar' });
+
+ expect(element.props).toMatchObject({
+ object,
+ dispose: null,
+ name: 'avatar',
+ });
+ });
+});