Skip to content

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

fix: dispose the PMREM render target and instanced-mesh buffers, not just the texture (#4630)

[._.]/ Adam Eivy375a8b251d1b
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index 6a894fb9ae..884a206f0e 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -4,7 +4,7 @@ import { Canvas, useFrame, useThree } 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 { createSculptEnvironmentTexture, resolveSculptEnvironment, THREEJS_RENDER_PROFILE } from '../../lib/threejsEnvironment';
+import { createSculptEnvironmentTarget, resolveSculptEnvironment, THREEJS_RENDER_PROFILE } from '../../lib/threejsEnvironment';
import {
collectThreejsCues,
evaluateThreejsClipPose,
@@ -306,13 +306,15 @@ function SceneEnvironment({ preset }) {
const scene = useThree((state) => state.scene);
useEffect(() => {
if (!scene) return undefined;
- const texture = preset === 'none' ? null : createSculptEnvironmentTexture(gl, preset);
- scene.environment = texture;
+ // The render TARGET, not just its texture: disposing the texture alone
+ // leaves the framebuffer behind it allocated on every preset swap.
+ const target = preset === 'none' ? null : createSculptEnvironmentTarget(gl, preset);
+ scene.environment = target?.texture || null;
return () => {
// Only clear what this effect set — a later effect may already have
// installed the next preset's texture.
- if (scene.environment === texture) scene.environment = null;
- texture?.dispose();
+ if (scene.environment === (target?.texture || null)) scene.environment = null;
+ target?.dispose();
};
}, [gl, scene, preset]);
return null;
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
index a41fe2a740..c3d1a1b6a3 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
@@ -13,11 +13,13 @@ vi.mock('../../lib/threejsEnvironment', async (importOriginal) => {
return {
...actual,
// PMREM needs a real renderer; what matters here is WHICH preset the preview
- // asked for and that the texture it got is released again.
- createSculptEnvironmentTexture: (_renderer, preset) => {
- const texture = { preset, dispose: vi.fn() };
- environmentBuilds.push(texture);
- return texture;
+ // asked for, that its texture reached the scene, and that the whole render
+ // TARGET is released again — disposing the texture alone leaks the
+ // framebuffer behind it.
+ createSculptEnvironmentTarget: (_renderer, preset) => {
+ const target = { preset, texture: { preset }, dispose: vi.fn() };
+ environmentBuilds.push(target);
+ return target;
},
};
});
@@ -290,8 +292,8 @@ describe('ThreejsModelPreview environment', () => {
it('assigns the authored preset to the scene and forwards its intensity to the material', () => {
const { container } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 2 })} />);
- expect(environmentBuilds.map((texture) => texture.preset)).toEqual(['studio']);
- expect(threeState.scene.environment).toBe(environmentBuilds[0]);
+ expect(environmentBuilds.map((target) => target.preset)).toEqual(['studio']);
+ expect(threeState.scene.environment).toBe(environmentBuilds[0].texture);
expect(intensityOf(container)).toBe('2');
});
@@ -305,22 +307,22 @@ describe('ThreejsModelPreview environment', () => {
expect(intensityOf(container)).toBe('1');
});
- it('swaps presets without leaking the previous PMREM texture', () => {
+ it('swaps presets without leaking the previous PMREM target', () => {
const { rerender } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'neutral', intensity: 1 })} />);
const [first] = environmentBuilds;
rerender(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 1 })} />);
expect(first.dispose).toHaveBeenCalled();
- expect(threeState.scene.environment).toBe(environmentBuilds[1]);
+ expect(threeState.scene.environment).toBe(environmentBuilds[1].texture);
expect(environmentBuilds[1].preset).toBe('studio');
});
- it('releases the texture and clears the scene on unmount', () => {
+ it('releases the render target and clears the scene on unmount', () => {
const { unmount } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 1 })} />);
- const [texture] = environmentBuilds;
+ const [target] = environmentBuilds;
unmount();
- expect(texture.dispose).toHaveBeenCalled();
+ expect(target.dispose).toHaveBeenCalled();
expect(threeState.scene.environment).toBeNull();
});
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index ceb4702e37..7621c29d05 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -181,7 +181,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `terminalScroll.js` | Scrolling the Shell terminal by touch, and inside a full-screen TUI. Two gaps, one primitive: xterm 6 binds **no touch handlers at all** (its viewport is VS Code’s `SmoothScrollableElement`, whose scroll extent is virtual — there is no oversized spacer for the browser to scroll natively), and a TUI’s ALTERNATE screen buffer additionally has no scrollback, so `scrollLines()` clamps to a no-op there. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer; `scrollTerminalLines(terminal, lines, geometry?)` / `scrollTerminalPage(terminal, direction)` drive it — via `scrollLines()` in the normal buffer, and in the alternate buffer by synthesizing `DOM_DELTA_LINE` wheel events on `terminal.element`, xterm’s only injection point (`attachCustomWheelEventHandler` intercepts, it cannot inject), so xterm’s own table picks SGR mouse report vs cursor key from the DEC modes the TUI set. `measureTerminalGeometry(terminal)` takes the one layout-forcing read per gesture (row height + screen centre); `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession` (`scrollPage`) + the `SCROLL_KEYS` buttons in `components/shell/TerminalHotKeys.jsx`. |
| `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. |
-| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTexture(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the texture. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
+| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
| `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, envMapIntensity)` 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`, and the spec-level `environment.intensity` as `envMapIntensity` on every lit material (`basic` is unlit and takes none). 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/threejsEnvironment.js b/client/src/lib/threejsEnvironment.js
index 605985ff10..c1fa8cf642 100644
--- a/client/src/lib/threejsEnvironment.js
+++ b/client/src/lib/threejsEnvironment.js
@@ -113,31 +113,43 @@ export function createSculptEnvironmentScene(preset) {
return null;
}
-/** Release every geometry and material a preset scene allocated. */
+/**
+ * Release everything a preset scene allocated on the GPU. `node.dispose()` is
+ * the one that matters for `RoomEnvironment`: it is built from `InstancedMesh`,
+ * whose per-instance matrix buffer is uploaded separately from the geometry and
+ * is not freed by disposing geometry and material alone.
+ */
export function disposeSculptEnvironmentScene(scene) {
scene?.traverse?.((node) => {
node.geometry?.dispose?.();
const material = node.material;
if (Array.isArray(material)) material.forEach((entry) => entry?.dispose?.());
else material?.dispose?.();
+ node.dispose?.();
});
}
/**
- * PMREM-prefilter a preset into the texture `scene.environment` wants, or null
- * for `none`. The source scene and the generator are both released here; the
- * CALLER owns the returned texture and must dispose it.
+ * PMREM-prefilter a preset into the render target whose `.texture` is what
+ * `scene.environment` wants, or null for `none`. The source scene and the
+ * generator are both released here; the CALLER owns the returned target and must
+ * `dispose()` it.
+ *
+ * The TARGET is returned rather than the texture because the framebuffer and
+ * depth attachment behind it are only freed by `WebGLRenderTarget.dispose()` —
+ * disposing the texture alone leaks them on every preset swap. Same ownership
+ * shape as `OpenWorldGalaxySky`'s PMREM effect.
*
* @param {THREE.WebGLRenderer} renderer the live renderer (PMREM needs a GL context)
* @param {string} preset one of `THREEJS_ENVIRONMENT_PRESETS`
*/
-export function createSculptEnvironmentTexture(renderer, preset) {
+export function createSculptEnvironmentTarget(renderer, preset) {
if (!renderer) return null;
const scene = createSculptEnvironmentScene(preset);
if (!scene) return null;
const pmrem = new THREE.PMREMGenerator(renderer);
- const texture = pmrem.fromScene(scene, 0.04).texture;
+ const target = pmrem.fromScene(scene, 0.04);
pmrem.dispose();
disposeSculptEnvironmentScene(scene);
- return texture;
+ return target;
}
diff --git a/client/src/lib/threejsEnvironment.test.js b/client/src/lib/threejsEnvironment.test.js
index 47ee4ce9a8..a6b9cc4b87 100644
--- a/client/src/lib/threejsEnvironment.test.js
+++ b/client/src/lib/threejsEnvironment.test.js
@@ -12,7 +12,7 @@ import {
DEFAULT_THREEJS_ENVIRONMENT,
THREEJS_RENDER_PROFILE,
createSculptEnvironmentScene,
- createSculptEnvironmentTexture,
+ createSculptEnvironmentTarget,
disposeSculptEnvironmentScene,
resolveSculptEnvironment,
} from './threejsEnvironment.js';
@@ -81,22 +81,36 @@ describe('createSculptEnvironmentScene', () => {
});
it('releases every geometry and material the preset allocated', () => {
- const scene = createSculptEnvironmentScene('studio');
- const geometries = [];
- const materials = [];
+ for (const preset of ['neutral', 'studio']) {
+ const scene = createSculptEnvironmentScene(preset);
+ const spies = [];
+ scene.traverse((node) => {
+ if (node.geometry) spies.push(vi.spyOn(node.geometry, 'dispose'));
+ if (node.material) spies.push(vi.spyOn(node.material, 'dispose'));
+ });
+ disposeSculptEnvironmentScene(scene);
+ expect(spies.length).toBeGreaterThan(0);
+ for (const spy of spies) expect(spy).toHaveBeenCalled();
+ }
+ });
+
+ // RoomEnvironment is built from InstancedMesh, whose per-instance matrix
+ // buffer is uploaded separately and survives disposing geometry + material.
+ it('releases an instanced mesh’s own GPU buffers too', () => {
+ const scene = createSculptEnvironmentScene('neutral');
+ const instanced = [];
scene.traverse((node) => {
- if (node.geometry) geometries.push(vi.spyOn(node.geometry, 'dispose'));
- if (node.material) materials.push(vi.spyOn(node.material, 'dispose'));
+ if (node.isInstancedMesh) instanced.push(vi.spyOn(node, 'dispose'));
});
+ expect(instanced.length).toBeGreaterThan(0);
disposeSculptEnvironmentScene(scene);
- expect(geometries.length).toBeGreaterThan(0);
- for (const spy of [...geometries, ...materials]) expect(spy).toHaveBeenCalled();
+ for (const spy of instanced) expect(spy).toHaveBeenCalled();
});
});
-describe('createSculptEnvironmentTexture', () => {
+describe('createSculptEnvironmentTarget', () => {
it('returns null without building anything for none or a missing renderer', () => {
- expect(createSculptEnvironmentTexture(null, 'studio')).toBeNull();
- expect(createSculptEnvironmentTexture({}, 'none')).toBeNull();
+ expect(createSculptEnvironmentTarget(null, 'studio')).toBeNull();
+ expect(createSculptEnvironmentTarget({}, 'none')).toBeNull();
});
});