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: paginate heavy Media/Memory lists and guard CoS WebGL

[._.]/ Adam Eivydae5b11499d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4b3de16860..120685414d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,8 @@
## Fixed
+- **Brain Memory and Media History no longer paint every record at once.** A live install with ~1.5k imported ChatGPT memories was mounting full Markdown trees for every card (~180k DOM nodes / multi-MB of text), and Media History mounted ~1.8k gallery cards with images in one grid — both tabs froze on open. Memory now shows a plain teaser for imported transcripts (full thread still opens in the conversation viewer) and both lists use a progressive "Show more" window so search still covers the full set while only a page of cards mounts. CoS 3D avatars also probe WebGL before creating a canvas, so headless/no-GPU displays degrade to a hint instead of unhandled `WebGLRenderer` rejections.
+
- **The pre-episode arc-spine check now resolves at the altitude it judged at.** That checkpoint deliberately verifies the arc spine with the episode lineup hidden — no episodes have been planned in earnest yet, so it only asks whether the premise, principals, engine, and volume allocation are safe to expand. The auto-resolver behind it, though, was still handed the full episode lineup and the general "correct an episode synopsis when the contradiction originates there" instruction, so it answered spine findings by rewriting episode synopses the gate had never read. Those edits could not close what was flagged, the arc and volume text stayed unfixed, and the next spine verification came back with twice the blockers — a round that got reverted wholesale and paused the run. (Observed on a run that went in with 3 blocking findings, spent its round editing 3 episode synopses, and came back with 6.) Spine rounds now render the resolver the same episode-empty plan the verifier saw, tell it to fix the arc and volumes only, and discard any episode edits it returns anyway, so a customized or stale installed prompt can't re-open the blast radius. Nothing changes for the full arc gate that runs after episodes exist: it still verifies and repairs episode synopses, which is the only place an episode-scoped contradiction can converge. Sparse finding-keyed patches and the blocker-count rollback are untouched.
- **Arc rollback now rejects equal-count severity regressions.** The best-draft guard already reverted any auto-resolve candidate that increased the total number of blocking findings, but an unchanged count was always accepted as a potentially narrower restatement. That allowed a resolver to trade a medium continuity gap for a new high-severity canon violation while still reporting the same total. Equal-count candidates are now ordered by severity before they can replace the checkpoint: more high findings, or more medium findings at the same high count, is a regression and is reverted through the same bounded corrective-pass path. The pause message names the severity escalation explicitly instead of presenting two identical counts as if one were numerically larger.
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index cc57038a9a..67445b7ad6 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router';
import * as api from '../../../services/api';
import {Plus,
@@ -13,7 +13,6 @@ import {Plus,
MessageSquareText} from 'lucide-react';
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
-import MarkdownOutput from '../../cos/MarkdownOutput';
import ConversationViewer from '../ConversationViewer';
import {
@@ -29,6 +28,27 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';
import CopyableId from '../../ui/CopyableId';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
+// Progressive list: imported ChatGPT corpora routinely top 1k+ records with
+// multi-KB transcripts. Mounting every card (and its Markdown tree) freezes
+// the tab and can push the DOM past 100k nodes. Show a window, load more on
+// demand; search still runs over the full in-memory set.
+const INITIAL_VISIBLE = 40;
+const LOAD_MORE = 40;
+
+// Plain-text teaser for imported transcripts — avoids mounting full markdown
+// for every card. The full thread is one click away via ConversationViewer.
+export function transcriptTeaser(content, maxLen = 220) {
+ if (typeof content !== 'string' || !content) return '';
+ const plain = content
+ .replace(/!\[[^\]]*]\([^)]*\)/g, '') // images
+ .replace(/\[([^\]]*)]\([^)]*\)/g, '$1') // links → label
+ .replace(/[#>*_`~-]+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ if (plain.length <= maxLen) return plain;
+ return `${plain.slice(0, maxLen).trimEnd()}…`;
+}
+
export default function MemoryTab({ onRefresh }) {
const navigate = useNavigate();
const [activeType, setActiveType] = useState('memories');
@@ -43,6 +63,7 @@ export default function MemoryTab({ onRefresh }) {
const [backendStatus, setBackendStatus] = useState(null);
// The chatgpt-import conversation currently open in the full-transcript viewer.
const [viewerRecord, setViewerRecord] = useState(null);
+ const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const fetchRecords = useCallback(async () => {
@@ -87,6 +108,25 @@ export default function MemoryTab({ onRefresh }) {
fetchBackendStatus();
}, [fetchBackendStatus]);
+ // Reset the progressive window whenever the user changes tab/filter/search
+ // so a "Show more" from memories doesn't leave people stuck deep into a
+ // short people list.
+ useEffect(() => {
+ setVisibleCount(INITIAL_VISIBLE);
+ }, [activeType, statusFilter, searchQuery]);
+
+ const filteredRecords = useMemo(() => {
+ const q = searchQuery.toLowerCase();
+ if (!q) return records;
+ return records.filter((r) => {
+ const fields = [
+ r.name, r.title, r.context, r.content, r.notes, r.oneLiner,
+ r.nextAction, r.mood, ...(r.tags || []), ...(r.followUps || []),
+ ];
+ return fields.some((f) => f?.toLowerCase().includes(q));
+ });
+ }, [records, searchQuery]);
+
const handleSave = async () => {
let result;
switch (activeType) {
@@ -545,13 +585,13 @@ export default function MemoryTab({ onRefresh }) {
)}
</div>
{record.content && (
- // Imported ChatGPT transcripts carry markdown (inline images,
- // asset links) — render them rich, but cap the height with an
- // internal scroll so a long transcript preview doesn't make
- // the card a mile tall (the full thread is in the viewer).
+ // Imported ChatGPT transcripts can be multi-KB markdown with
+ // images. Rendering full MarkdownOutput for every card was
+ // ballooning the Memory tab past 100k DOM nodes. Show a
+ // plain teaser here; the full thread opens in ConversationViewer.
// Hand-written memories stay plain pre-wrap text.
record.source === 'chatgpt-import'
- ? <div className="text-sm text-gray-400 mt-1 max-h-72 overflow-y-auto pr-1"><MarkdownOutput content={record.content} /></div>
+ ? <p className="text-sm text-gray-400 mt-1 line-clamp-3 break-words">{transcriptTeaser(record.content)}</p>
: <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap break-words">{record.content}</p>
)}
{record.source === 'chatgpt-import' && record.sourceRef && (
@@ -773,26 +813,26 @@ export default function MemoryTab({ onRefresh }) {
<div className="flex items-center justify-center h-32">
<BrailleSpinner text="Loading" />
</div>
- ) : (() => {
- const q = searchQuery.toLowerCase();
- const filtered = q
- ? records.filter(r => {
- const fields = [r.name, r.title, r.context, r.content, r.notes, r.oneLiner, r.nextAction, r.mood, ...(r.tags || []), ...(r.followUps || [])];
- return fields.some(f => f?.toLowerCase().includes(q));
- })
- : records;
- return filtered.length === 0 ? (
- <p className="text-gray-500 text-center py-8">
- {searchQuery
- ? `No matches for "${searchQuery}"`
- : `No ${DESTINATIONS[activeType]?.label?.toLowerCase() || 'records'} yet. Add one or capture thoughts in the Inbox.`}
- </p>
- ) : (
- <div className="space-y-2">
- {filtered.map(record => renderRecord(record))}
- </div>
- );
- })()}
+ ) : filteredRecords.length === 0 ? (
+ <p className="text-gray-500 text-center py-8">
+ {searchQuery
+ ? `No matches for "${searchQuery}"`
+ : `No ${DESTINATIONS[activeType]?.label?.toLowerCase() || 'records'} yet. Add one or capture thoughts in the Inbox.`}
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {filteredRecords.slice(0, visibleCount).map(record => renderRecord(record))}
+ {filteredRecords.length > visibleCount && (
+ <button
+ type="button"
+ onClick={() => setVisibleCount((n) => n + LOAD_MORE)}
+ className="w-full py-2.5 text-xs text-port-accent hover:text-white bg-port-border/30 hover:bg-port-border/50 rounded-lg transition-colors min-h-[44px]"
+ >
+ Show more ({filteredRecords.length - visibleCount} remaining)
+ </button>
+ )}
+ </div>
+ )}
{viewerRecord && (
<ConversationViewer record={viewerRecord} onClose={() => setViewerRecord(null)} />
diff --git a/client/src/components/brain/tabs/MemoryTab.transcriptTeaser.test.js b/client/src/components/brain/tabs/MemoryTab.transcriptTeaser.test.js
new file mode 100644
index 0000000000..7272ee6917
--- /dev/null
+++ b/client/src/components/brain/tabs/MemoryTab.transcriptTeaser.test.js
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { transcriptTeaser } from './MemoryTab.jsx';
+
+describe('transcriptTeaser', () => {
+ it('returns empty for non-strings', () => {
+ expect(transcriptTeaser(null)).toBe('');
+ expect(transcriptTeaser(undefined)).toBe('');
+ expect(transcriptTeaser(42)).toBe('');
+ });
+
+ it('strips markdown images and link targets, keeps labels', () => {
+ const out = transcriptTeaser('Hello ![img](http://x/y.png) and [docs](http://example.com/a).');
+ expect(out).toBe('Hello and docs.');
+ expect(out).not.toMatch(/http/);
+ });
+
+ it('collapses whitespace and truncates with an ellipsis', () => {
+ const long = `${'word '.repeat(80)}end`;
+ const out = transcriptTeaser(long, 40);
+ expect(out.endsWith('…')).toBe(true);
+ expect(out.length).toBeLessThanOrEqual(41);
+ });
+
+ it('leaves short plain text unchanged', () => {
+ expect(transcriptTeaser('Short note.')).toBe('Short note.');
+ });
+});
diff --git a/client/src/components/cos/CoSCanvasGuard.jsx b/client/src/components/cos/CoSCanvasGuard.jsx
new file mode 100644
index 0000000000..48fd4d03cb
--- /dev/null
+++ b/client/src/components/cos/CoSCanvasGuard.jsx
@@ -0,0 +1,65 @@
+import { Component, useState } from 'react';
+import { isWebGLAvailable } from '../../lib/webglSupport';
+import CoSAvatarFrame from './CoSAvatarFrame';
+
+/**
+ * Gate CoS 3D avatar canvases on WebGL availability and catch render-time
+ * failures so a missing GPU never leaves an unhandled promise rejection or a
+ * blank panel. Callers pass the r3f `<Canvas>…</Canvas>` as children.
+ */
+
+class AvatarErrorBoundary extends Component {
+ constructor(props) {
+ super(props);
+ this.state = { failed: false };
+ }
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ componentDidCatch(err) {
+ console.warn(`⚠️ CoS avatar failed: ${err?.message || err}`);
+ }
+
+ render() {
+ return this.state.failed ? this.props.fallback : this.props.children;
+ }
+}
+
+function WebGLUnavailableHint({ background = false }) {
+ return (
+ <div
+ className={`${background ? 'relative w-full h-full min-h-full' : 'relative w-full max-w-[8rem] lg:max-w-[12rem] aspect-[5/6]'} flex flex-col items-center justify-center rounded-lg border border-port-border bg-port-card/60 text-center p-3`}
+ >
+ <div className="text-2xl mb-2" aria-hidden="true">🖥️</div>
+ <div className="text-xs font-semibold text-gray-200 mb-1">3D unavailable</div>
+ <div className="text-[10px] text-gray-400 leading-snug">
+ This display has no WebGL. Pick the SVG or ASCII avatar in CoS Config.
+ </div>
+ </div>
+ );
+}
+
+export default function CoSCanvasGuard({
+ label = 'Interactive 3D avatar. Drag to rotate.',
+ background = false,
+ fallback = null,
+ children,
+}) {
+ // Probe once on mount — availability doesn't flip mid-session.
+ const [supported] = useState(() => isWebGLAvailable());
+ const resolvedFallback = fallback || <WebGLUnavailableHint background={background} />;
+
+ if (!supported) return resolvedFallback;
+
+ return (
+ <CoSAvatarFrame label={label} background={background}>
+ <AvatarErrorBoundary fallback={resolvedFallback}>
+ {children}
+ </AvatarErrorBoundary>
+ </CoSAvatarFrame>
+ );
+}
+
+export { WebGLUnavailableHint };
diff --git a/client/src/components/cos/CyberCoSAvatar.jsx b/client/src/components/cos/CyberCoSAvatar.jsx
index 05a6ee663b..98ef1f4eac 100644
--- a/client/src/components/cos/CyberCoSAvatar.jsx
+++ b/client/src/components/cos/CyberCoSAvatar.jsx
@@ -4,7 +4,7 @@ import { Float, MeshDistortMaterial, Sparkles } from '@react-three/drei';
import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
+import CoSCanvasGuard from './CoSCanvasGuard';
import CoSBackgroundCamera from './CoSBackgroundCamera';
// Holographic wireframe skull/head geometry
@@ -438,7 +438,7 @@ function Scene({ state, speaking, background }) {
export default function CyberCoSAvatar({ state, speaking, background = false }) {
return (
- <CoSAvatarFrame label="Cyber 3D avatar. Drag to rotate." background={background}>
+ <CoSCanvasGuard label="Cyber 3D avatar. Drag to rotate." background={background}>
<Canvas
camera={{ position: [0, 0, 3.5], fov: 45 }}
style={{ width: '100%', height: '100%', background: 'transparent' }}
@@ -446,6 +446,6 @@ export default function CyberCoSAvatar({ state, speaking, background = false })
>
<Scene state={state} speaking={speaking} background={background} />
</Canvas>
- </CoSAvatarFrame>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/components/cos/EsotericCoSAvatar.jsx b/client/src/components/cos/EsotericCoSAvatar.jsx
index d4fad4ef96..7649c43cef 100644
--- a/client/src/components/cos/EsotericCoSAvatar.jsx
+++ b/client/src/components/cos/EsotericCoSAvatar.jsx
@@ -4,8 +4,8 @@ import { Float, MeshDistortMaterial, Sparkles, Stars } from '@react-three/drei';
import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
import CoSBackgroundCamera from './CoSBackgroundCamera';
+import CoSCanvasGuard from './CoSCanvasGuard';
// Central mystical core - an artifact of unknown origin
function EsotericCore({ color, state, speaking }) {
@@ -205,7 +205,7 @@ function Scene({ state, speaking, background }) {
export default function EsotericCoSAvatar({ state, speaking, background = false }) {
return (
- <CoSAvatarFrame label="Esoteric 3D avatar. Drag to rotate." background={background}>
+ <CoSCanvasGuard label="Esoteric 3D avatar. Drag to rotate." background={background}>
<Canvas
camera={{ position: [0, 0, 5], fov: 45 }}
style={{ width: '100%', height: '100%', background: 'transparent' }}
@@ -213,6 +213,6 @@ export default function EsotericCoSAvatar({ state, speaking, background = false
>
<Scene state={state} speaking={speaking} background={background} />
</Canvas>
- </CoSAvatarFrame>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/components/cos/MiniCharacterCoSAvatar.jsx b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
index 237ccfcb28..9a61cd9ac9 100644
--- a/client/src/components/cos/MiniCharacterCoSAvatar.jsx
+++ b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
@@ -1,10 +1,10 @@
-import { useRef, useMemo, useEffect, useState, Suspense, Component } from 'react';
+import { useRef, useMemo, useEffect, useState, Suspense } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
import CoSBackgroundCamera from './CoSBackgroundCamera';
+import CoSCanvasGuard from './CoSCanvasGuard';
import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
// Kenney Mini Characters (CC0) ship 32 named clips. We map the CoS agent
@@ -148,25 +148,6 @@ function MissingModelHint({ background = false, bundled = false }) {
);
}
-// Error boundary so a corrupt/missing GLB or a GET that returns a non-GLTF
-// body (the HEAD probe only confirms r.ok, not valid GLTF) degrades to the
-// missing-model hint instead of white-screening the whole CoS page.
-class AvatarErrorBoundary extends Component {
- constructor(props) {
- super(props);
- this.state = { failed: false };
- }
- static getDerivedStateFromError() {
- return { failed: true };
- }
- componentDidCatch(err) {
- console.warn(`⚠️ Mini-character avatar failed to load: ${err?.message || err}`);
- }
- render() {
- return this.state.failed ? this.props.fallback : this.props.children;
- }
-}
-
function LoadingPlaceholder({ background = false }) {
return (
<div className={`${background ? 'relative w-full h-full min-h-full' : 'relative w-full max-w-[8rem] lg:max-w-[12rem] aspect-[5/6]'} flex items-center justify-center`}>
@@ -193,18 +174,20 @@ export default function MiniCharacterCoSAvatar({ state, speaking, background = f
if (!modelPresent) return <MissingModelHint background={background} bundled={bundled} />;
return (
- <CoSAvatarFrame label="Mini-character avatar. Drag to rotate." background={background}>
- <AvatarErrorBoundary fallback={<MissingModelHint background={background} bundled={bundled} />}>
- <Canvas
- camera={{ position: [0, 0.2, 3.0], fov: 40 }}
- style={{ width: '100%', height: '100%', background: 'transparent' }}
- gl={{ alpha: true, antialias: true }}
- >
- <Suspense fallback={null}>
- <Scene state={state} speaking={speaking} background={background} variant={variant} />
- </Suspense>
- </Canvas>
- </AvatarErrorBoundary>
- </CoSAvatarFrame>
+ <CoSCanvasGuard
+ label="Mini-character avatar. Drag to rotate."
+ background={background}
+ fallback={<MissingModelHint background={background} bundled={bundled} />}
+ >
+ <Canvas
+ camera={{ position: [0, 0.2, 3.0], fov: 40 }}
+ style={{ width: '100%', height: '100%', background: 'transparent' }}
+ gl={{ alpha: true, antialias: true }}
+ >
+ <Suspense fallback={null}>
+ <Scene state={state} speaking={speaking} background={background} variant={variant} />
+ </Suspense>
+ </Canvas>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/components/cos/MuseCoSAvatar.jsx b/client/src/components/cos/MuseCoSAvatar.jsx
index cba7adc198..883399d973 100644
--- a/client/src/components/cos/MuseCoSAvatar.jsx
+++ b/client/src/components/cos/MuseCoSAvatar.jsx
@@ -1,4 +1,4 @@
-import { useRef, useMemo, useEffect, useState, useCallback, Suspense, Component } from 'react';
+import { useRef, useMemo, useEffect, useState, useCallback, Suspense } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { useGLTF, Sparkles } from '@react-three/drei';
import * as THREE from 'three';
@@ -12,8 +12,8 @@ import {
MUSE_ROOT_MOTION_CLIPS,
} from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
import CoSBackgroundCamera from './CoSBackgroundCamera';
+import CoSCanvasGuard from './CoSCanvasGuard';
import { withInPlaceClips, inPlaceClipName } from '../../utils/animationClips';
import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
@@ -314,25 +314,6 @@ function MissingModelHint({ background = false }) {
);
}
-// Error boundary so a corrupt/non-GLTF body (the HEAD probe only confirms
-// r.ok, not valid GLTF) degrades to the missing-model hint instead of
-// white-screening the whole CoS page.
-class AvatarErrorBoundary extends Component {
- constructor(props) {
- super(props);
- this.state = { failed: false };
- }
- static getDerivedStateFromError() {
- return { failed: true };
- }
- componentDidCatch(err) {
- console.warn(`⚠️ Muse avatar failed to load: ${err?.message || err}`);
- }
- render() {
- return this.state.failed ? this.props.fallback : this.props.children;
- }
-}
-
function LoadingPlaceholder({ background = false }) {
return (
<div className={`${background ? 'relative w-full h-full min-h-full' : 'relative w-full max-w-[8rem] lg:max-w-[12rem] aspect-[5/6]'} flex items-center justify-center`}>
@@ -361,19 +342,21 @@ export default function MuseCoSAvatar({ state, speaking, background = false }) {
if (!modelPresent) return <MissingModelHint background={background} />;
return (
- <CoSAvatarFrame label="Muse 3D avatar. Drag to rotate." background={background}>
- <AvatarErrorBoundary fallback={<MissingModelHint background={background} />}>
- <Canvas
- camera={{ position: [0, 0, 3.3], fov: 45 }}
- style={{ width: '100%', height: '100%', background: 'transparent' }}
- gl={{ alpha: true, antialias: true }}
- >
- <Suspense fallback={null}>
- <Scene state={state} speaking={speaking} background={background} />
- </Suspense>
- </Canvas>
- </AvatarErrorBoundary>
- </CoSAvatarFrame>
+ <CoSCanvasGuard
+ label="Muse 3D avatar. Drag to rotate."
+ background={background}
+ fallback={<MissingModelHint background={background} />}
+ >
+ <Canvas
+ camera={{ position: [0, 0, 3.3], fov: 45 }}
+ style={{ width: '100%', height: '100%', background: 'transparent' }}
+ gl={{ alpha: true, antialias: true }}
+ >
+ <Suspense fallback={null}>
+ <Scene state={state} speaking={speaking} background={background} />
+ </Suspense>
+ </Canvas>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/components/cos/NexusCoSAvatar.jsx b/client/src/components/cos/NexusCoSAvatar.jsx
index cc8fe891ad..b99d1c03af 100644
--- a/client/src/components/cos/NexusCoSAvatar.jsx
+++ b/client/src/components/cos/NexusCoSAvatar.jsx
@@ -4,7 +4,7 @@ import { Float, MeshDistortMaterial, Sparkles } from '@react-three/drei';
import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
+import CoSCanvasGuard from './CoSCanvasGuard';
import CoSBackgroundCamera from './CoSBackgroundCamera';
// Central brain-like neural core
@@ -371,7 +371,7 @@ function Scene({ state, speaking, background }) {
export default function NexusCoSAvatar({ state, speaking, background = false }) {
return (
- <CoSAvatarFrame label="Nexus 3D avatar. Drag to rotate." background={background}>
+ <CoSCanvasGuard label="Nexus 3D avatar. Drag to rotate." background={background}>
<Canvas
camera={{ position: [0, 0.2, 3.5], fov: 45 }}
style={{ width: '100%', height: '100%', background: 'transparent' }}
@@ -379,6 +379,6 @@ export default function NexusCoSAvatar({ state, speaking, background = false })
>
<Scene state={state} speaking={speaking} background={background} />
</Canvas>
- </CoSAvatarFrame>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/components/cos/SigilCoSAvatar.jsx b/client/src/components/cos/SigilCoSAvatar.jsx
index 670a7a78ce..1c704b7497 100644
--- a/client/src/components/cos/SigilCoSAvatar.jsx
+++ b/client/src/components/cos/SigilCoSAvatar.jsx
@@ -4,7 +4,7 @@ import { Float, MeshDistortMaterial, Sparkles } from '@react-three/drei';
import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
-import CoSAvatarFrame from './CoSAvatarFrame';
+import CoSCanvasGuard from './CoSCanvasGuard';
import CoSBackgroundCamera from './CoSBackgroundCamera';
function SigilCore({ color, state, speaking }) {
@@ -286,7 +286,7 @@ function Scene({ state, speaking, background }) {
export default function SigilCoSAvatar({ state, speaking, background = false }) {
return (
- <CoSAvatarFrame label="Sigil 3D avatar. Drag to rotate." background={background}>
+ <CoSCanvasGuard label="Sigil 3D avatar. Drag to rotate." background={background}>
<Canvas
camera={{ position: [0, 0.1, 3.7], fov: 45 }}
style={{ width: '100%', height: '100%', background: 'transparent' }}
@@ -294,6 +294,6 @@ export default function SigilCoSAvatar({ state, speaking, background = false })
>
<Scene state={state} speaking={speaking} background={background} />
</Canvas>
- </CoSAvatarFrame>
+ </CoSCanvasGuard>
);
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5296f7e2e5..7a37be8398 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -119,6 +119,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
| `uuid.js` | `uuidv4()` — spec-valid v4 uuid that also works on **insecure origins**. Reach for this instead of `crypto.randomUUID()`, which only exists in a secure context (HTTPS / localhost) and throws `crypto.randomUUID is not a function` for the many users who reach PortOS over plain HTTP via Tailscale. Falls back to `crypto.getRandomValues` (available on insecure origins), then `Math.random`. |
+| `webglSupport.js` | `isWebGLAvailable()` — memoized probe for a creatable WebGL/WebGL2 context. CoS 3D avatars (and similar r3f mounts) call this before `<Canvas>` so headless Chrome / no-GPU displays degrade to a hint instead of unhandled `WebGLRenderer` rejections. |
| `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |
## Page-scoped pure helpers
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 7aed531839..f44ba9d5ed 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -143,5 +143,6 @@ export * from './quotaBurnPatch.js';
export * from './tribeCadence.js';
export * from './universeBuilderExpand.js';
export * from './uuid.js';
+export * from './webglSupport.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/lib/webglSupport.js b/client/src/lib/webglSupport.js
new file mode 100644
index 0000000000..3436958881
--- /dev/null
+++ b/client/src/lib/webglSupport.js
@@ -0,0 +1,42 @@
+/**
+ * Detect whether the browser can create a WebGL context.
+ *
+ * Used before mounting react-three-fiber `<Canvas>` so CoS 3D avatars (and
+ * similar) degrade cleanly instead of throwing unhandled
+ * `THREE.WebGLRenderer: Error creating WebGL context` rejections on headless
+ * Chrome, remote desktops, or GPUs with WebGL disabled.
+ *
+ * Result is memoized for the page lifetime — context creation is not free,
+ * and availability does not change mid-session in practice.
+ */
+
+let cached = null;
+
+export function isWebGLAvailable() {
+ if (cached !== null) return cached;
+ if (typeof document === 'undefined') {
+ cached = false;
+ return cached;
+ }
+ try {
+ const canvas = document.createElement('canvas');
+ const gl =
+ canvas.getContext('webgl2', { failIfMajorPerformanceCaveat: false }) ||
+ canvas.getContext('webgl', { failIfMajorPerformanceCaveat: false }) ||
+ canvas.getContext('experimental-webgl', { failIfMajorPerformanceCaveat: false });
+ cached = !!gl;
+ // Drop the context immediately so we don't hold a GPU slot just for the probe.
+ if (gl && typeof gl.getExtension === 'function') {
+ const lose = gl.getExtension('WEBGL_lose_context');
+ lose?.loseContext?.();
+ }
+ } catch {
+ cached = false;
+ }
+ return cached;
+}
+
+/** Test-only: clear the memo so cases can flip availability. */
+export function __resetWebGLAvailableCache() {
+ cached = null;
+}
diff --git a/client/src/lib/webglSupport.test.js b/client/src/lib/webglSupport.test.js
new file mode 100644
index 0000000000..ad36954ce6
--- /dev/null
+++ b/client/src/lib/webglSupport.test.js
@@ -0,0 +1,46 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { __resetWebGLAvailableCache, isWebGLAvailable } from './webglSupport.js';
+
+afterEach(() => {
+ __resetWebGLAvailableCache();
+ vi.restoreAllMocks();
+});
+
+describe('isWebGLAvailable', () => {
+ it('returns true when webgl2 context can be created', () => {
+ const lose = { loseContext: vi.fn() };
+ const gl = { getExtension: vi.fn(() => lose) };
+ vi.spyOn(document, 'createElement').mockReturnValue({
+ getContext: (type) => (type === 'webgl2' ? gl : null),
+ });
+ expect(isWebGLAvailable()).toBe(true);
+ expect(lose.loseContext).toHaveBeenCalled();
+ // Memoized
+ expect(isWebGLAvailable()).toBe(true);
+ expect(document.createElement).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to webgl when webgl2 is missing', () => {
+ const gl = { getExtension: vi.fn(() => null) };
+ vi.spyOn(document, 'createElement').mockReturnValue({
+ getContext: (type) => (type === 'webgl' ? gl : null),
+ });
+ expect(isWebGLAvailable()).toBe(true);
+ });
+
+ it('returns false when no context can be created', () => {
+ vi.spyOn(document, 'createElement').mockReturnValue({
+ getContext: () => null,
+ });
+ expect(isWebGLAvailable()).toBe(false);
+ });
+
+ it('returns false when getContext throws', () => {
+ vi.spyOn(document, 'createElement').mockReturnValue({
+ getContext: () => {
+ throw new Error('WebGL disabled');
+ },
+ });
+ expect(isWebGLAvailable()).toBe(false);
+ });
+});
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index f7f0735b4d..e22ca733e1 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -30,6 +30,12 @@ const FILTERS = [
{ id: 'video', label: 'Videos' },
];
+// Progressive grid: a mature install can hold 1k–2k+ gallery items. Mounting
+// every MediaCard + <img> at once freezes the tab and spikes memory. Search/
+// filter still run over the full list; only the painted window is limited.
+const INITIAL_VISIBLE = 60;
+const LOAD_MORE = 60;
+
export default function MediaHistory() {
const navigate = useNavigate();
const [items, setItems] = useState([]);
@@ -40,6 +46,7 @@ export default function MediaHistory() {
const [selected, setSelected] = useState([]); // video ids
const [stitching, setStitching] = useState(false);
const [favoritesOnly, setFavoritesOnly] = useState(false);
+ const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE);
const { annotations, toggleStar, updateAnnotation, getCardProps } = useMediaAnnotations();
// URL-driven preview (`?preview=<filename>`) so the lightbox is deep-linkable.
// Match against the full `items` list (not the filtered view) so a shared link
@@ -86,6 +93,17 @@ export default function MediaHistory() {
() => favoritesOnly ? kindFiltered.filter((i) => annotations[i.key]?.starred) : kindFiltered,
[kindFiltered, favoritesOnly, annotations]
);
+
+ // Reset the painted window when the user changes what they're looking at so
+ // "Show more" progress from one filter doesn't hide a short result set.
+ useEffect(() => {
+ setVisibleCount(INITIAL_VISIBLE);
+ }, [filter, query, favoritesOnly]);
+
+ const visibleItems = useMemo(
+ () => filtered.slice(0, visibleCount),
+ [filtered, visibleCount]
+ );
const counts = useMemo(() => {
const c = { all: 0, image: 0, video: 0 };
for (const i of searched) {
@@ -244,34 +262,45 @@ export default function MediaHistory() {
: <>Nothing here yet. Try <Link to="/media/image" className="text-port-accent hover:underline">Image</Link> or <Link to="/media/video" className="text-port-accent hover:underline">Video</Link>.</>}
</div>
) : (
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {filtered.map((it) => {
- const inStitch = stitchMode && it.kind === 'video';
- const idx = inStitch ? selected.indexOf(it.id) : -1;
- return (
- <MediaCard
- key={it.key}
- item={it}
- onPreview={(media) => setPreview(media)}
- onClick={inStitch ? () => toggleSelect(it.id) : undefined}
- onRemix={!stitchMode ? handleRemix : undefined}
- onSendToImage={!stitchMode ? handleSendToImage : undefined}
- onSendToVideo={!stitchMode ? handleSendToVideo : undefined}
- onSendTo3d={!stitchMode ? handleSendTo3d : undefined}
- onContinue={!stitchMode ? handleContinue : undefined}
- onUpscale={!stitchMode && it.kind === 'video' ? handleUpscale : undefined}
- onDelete={!stitchMode ? handleDelete : undefined}
- selectionLabel={idx !== -1 ? idx + 1 : null}
- selected={idx !== -1}
- disabled={stitchMode && it.kind !== 'video'}
- hideActions={stitchMode}
- {...getCardProps(it.key)}
- onToggleStar={!stitchMode ? toggleStar : undefined}
- onAnnotate={!stitchMode && it.kind === 'image' ? (m) => navigate(`/media/annotate/${encodeURIComponent(m.key)}`) : undefined}
- />
- );
- })}
- </div>
+ <>
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
+ {visibleItems.map((it) => {
+ const inStitch = stitchMode && it.kind === 'video';
+ const idx = inStitch ? selected.indexOf(it.id) : -1;
+ return (
+ <MediaCard
+ key={it.key}
+ item={it}
+ onPreview={(media) => setPreview(media)}
+ onClick={inStitch ? () => toggleSelect(it.id) : undefined}
+ onRemix={!stitchMode ? handleRemix : undefined}
+ onSendToImage={!stitchMode ? handleSendToImage : undefined}
+ onSendToVideo={!stitchMode ? handleSendToVideo : undefined}
+ onSendTo3d={!stitchMode ? handleSendTo3d : undefined}
+ onContinue={!stitchMode ? handleContinue : undefined}
+ onUpscale={!stitchMode && it.kind === 'video' ? handleUpscale : undefined}
+ onDelete={!stitchMode ? handleDelete : undefined}
+ selectionLabel={idx !== -1 ? idx + 1 : null}
+ selected={idx !== -1}
+ disabled={stitchMode && it.kind !== 'video'}
+ hideActions={stitchMode}
+ {...getCardProps(it.key)}
+ onToggleStar={!stitchMode ? toggleStar : undefined}
+ onAnnotate={!stitchMode && it.kind === 'image' ? (m) => navigate(`/media/annotate/${encodeURIComponent(m.key)}`) : undefined}
+ />
+ );
+ })}
+ </div>
+ {filtered.length > visibleCount && (
+ <button
+ type="button"
+ onClick={() => setVisibleCount((n) => n + LOAD_MORE)}
+ className="w-full py-2.5 text-xs text-port-accent hover:text-white bg-port-border/30 hover:bg-port-border/50 rounded-lg transition-colors min-h-[44px]"
+ >
+ Show more ({filtered.length - visibleCount} remaining)
+ </button>
+ )}
+ </>
)}
<MediaPreview