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
Add Casting, Environments and Objects pages over the catalog (#11905)
[._.]/191912466429
diff --git a/client/src/App.jsx b/client/src/App.jsxindex ee5ffecf55..57f14e26cb 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -71,6 +71,7 @@ const RoundEditor = lazyWithReload(() => import('./pages/RoundEditor'));const RoundsGuide = lazyWithReload(() => import('./pages/RoundsGuide'));const CatalogIngest = lazyWithReload(() => import('./pages/CatalogIngest'));const CatalogIngredient = lazyWithReload(() => import('./pages/CatalogIngredient'));+const CreativeLibrary = lazyWithReload(() => import('./pages/CreativeLibrary'));const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));@@ -606,6 +607,12 @@ export default function App() {<Route path="catalog" element={<Catalog />} /><Route path="catalog/ingest" element={<CatalogIngest />} /><Route path="catalog/:type/:id" element={<CatalogIngredient />} />+ <Route path="casting" element={<CreativeLibrary key="casting" libraryId="casting" />} />+ <Route path="casting/:id" element={<CatalogIngredient />} />+ <Route path="environments" element={<CreativeLibrary key="environments" libraryId="environments" />} />+ <Route path="environments/:id" element={<CatalogIngredient />} />+ <Route path="objects" element={<CreativeLibrary key="objects" libraryId="objects" />} />+ <Route path="objects/:id" element={<CatalogIngredient />} /><Route path="code-animation" element={<CodeAnimation />} /><Route path="code-animation/:jobId" element={<CodeAnimation />} /><Route path="code-animation/production" element={<CodeAnimation />} />diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex 5bbba7b034..6946241645 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -15,6 +15,7 @@ import { RECENT_KEY, RECENT_CAP, resolveRecentNavEntries } from '../utils/navWorimport { filterNavByFeatures } from '../lib/navFeatures.js';import { safeReadJsonStorage } from '../lib/safeStorage.js';import { escapeRegExp } from '../lib/textUtils.js';+import { ingredientPath } from '../lib/creativeLibraries.js';import { onActivateKeyDown } from '../lib/a11yKeyboard.js';const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse, Video };@@ -269,7 +270,7 @@ export default function CmdKSearch() {id: ing.id,name: ing.name,type: ing.type,- path: `/catalog/${encodeURIComponent(ing.type)}/${encodeURIComponent(ing.id)}`,+ path: ingredientPath(ing),})),[catalogResults]);diff --git a/client/src/components/QuickIdeaCapture.jsx b/client/src/components/QuickIdeaCapture.jsxindex e262e56300..7907295e28 100644--- a/client/src/components/QuickIdeaCapture.jsx+++ b/client/src/components/QuickIdeaCapture.jsx@@ -18,6 +18,7 @@ import toast from './ui/Toast';import TagPicker from './TagPicker';import { createCatalogIngredient } from '../services/apiCatalog';import { CATALOG_TYPES, getCatalogType } from '../lib/catalogTypes';+import { ingredientPath } from '../lib/creativeLibraries';const TYPES = CATALOG_TYPES;@@ -76,7 +77,7 @@ export default function QuickIdeaCapture() {toast.success(<span>Saved {typeMeta.label.toLowerCase()}.{' '}- <Link to={`/catalog/${created.type}/${created.id}`} className="underline">Open</Link>+ <Link to={ingredientPath(created)} className="underline">Open</Link></span>,);};diff --git a/client/src/components/catalog/CatalogCard.jsx b/client/src/components/catalog/CatalogCard.jsxindex 69aff2794d..581ff1e086 100644--- a/client/src/components/catalog/CatalogCard.jsx+++ b/client/src/components/catalog/CatalogCard.jsx@@ -13,6 +13,7 @@ import { Sparkles, Trash2 } from 'lucide-react';import MediaImage from '../MediaImage';import InlineConfirmRow from '../ui/InlineConfirmRow';import { payloadSnippet } from '../../lib/catalogTypes';+import { ingredientPath, ingredientCoverUrl } from '../../lib/creativeLibraries';function TypeBadge({ type, getType }) {const meta = getType(type);@@ -24,18 +25,18 @@ function TypeBadge({ type, getType }) {);}-// Card thumbnail: the ingredient's portrait (or most recent reference image),-// resolved from the media library at /data/images/<key>. With no image we show a+// Card thumbnail: the ingredient's portrait (or most recent reference image)+// from the media library, else its universe canon image (ingredientCoverUrl). With no image we show a// dimmed Sparkles placeholder; with one we render through <MediaImage>, which// tolerates a not-yet-arrived peer asset (shows "Syncing" and auto-swaps to the// live image on the asset-arrived event) instead of permanently breaking on a// transient 404. Either way the slot keeps a fixed footprint so the grid aligns.-function CardThumb({ mediaKey, alt }) {+function CardThumb({ src, alt }) {return (<div className="w-14 h-14 shrink-0 rounded-md overflow-hidden border border-port-border bg-port-bg flex items-center justify-center">- {mediaKey ? (+ {src ? (<MediaImage- src={`/data/images/${mediaKey}`}+ src={src}alt={alt}className="w-full h-full object-cover"loading="lazy"@@ -96,10 +97,10 @@ export default function CatalogCard({/>)}<Link- to={`/catalog/${encodeURIComponent(it.type)}/${encodeURIComponent(it.id)}`}+ to={ingredientPath(it)}className="flex gap-3 p-3 pl-11 pr-11 min-h-[88px]">- <CardThumb mediaKey={it.thumbnailKey} alt={name} />+ <CardThumb src={ingredientCoverUrl(it)} alt={name} /><span className="flex flex-col gap-2 min-w-0 flex-1"><span className="block text-white font-medium truncate">{name}</span><span className="flex items-center gap-1.5 flex-wrap">diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsxindex 0be136ff1c..84775918a0 100644--- a/client/src/components/creative-director/OverviewTab.jsx+++ b/client/src/components/creative-director/OverviewTab.jsx@@ -3,6 +3,7 @@ import { useState, useEffect, useRef } from 'react';import { Sparkles, Loader2 } from 'lucide-react';import { updateCreativeDirectorProject, applyCreativeDirectorAutoCast } from '../../services/apiCreativeDirector.js';import { selectProjectPreview, previewAspectClass, previewMaxWidthClass } from '../../lib/creativeDirectorPreview.js';+import { ingredientPath } from '../../lib/creativeLibraries.js';import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';import MediaImage from '../MediaImage.jsx';import ScenePreview from './ScenePreview.jsx';@@ -353,11 +354,8 @@ export default function OverviewTab({ project, onProjectUpdate, onAsyncWorkQueue{Array.isArray(project.cast) && project.cast.length > 0 ? (<div className="flex flex-col gap-1.5">{project.cast.map((member) => {- // Ingredient detail route is /catalog/:type/:id (matches CatalogCard);- // fall back to a non-link span if the cast member is missing its type.- const detailPath = member.type- ? `/catalog/${encodeURIComponent(member.type)}/${encodeURIComponent(member.ingredientId)}`- : null;+ // Fall back to a non-link span if the cast member is missing its type.+ const detailPath = member.type ? ingredientPath({ type: member.type, id: member.ingredientId }) : null;return (<div key={member.ingredientId} className="text-sm">{detailPathdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 2be60f2837..364438965e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -84,6 +84,7 @@ grep -i "what you want to do" client/src/lib/README.md| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. || `creativeDirectorStatus.js` | `describeCreativeDirectorStatus(project, { activeAgents, activeTab })` → `{ headline, tone, facts, next }` — the one "where it stands, what's next" status line for a CD project (stage in words, whether it waits on the user, a single `start`/`resume`/`edit-draft`/`goto`/`open-final` next action). Pure; rendered by `components/ui/RecordStatusLine`. |+| `creativeLibraries.js` | `CREATIVE_LIBRARIES` — the Casting / Environments / Objects pages as views over the catalog's character / place / object ingredients, with `libraryById` / `libraryForType` / `libraryForPathname`, `ingredientPath(ingredient)` (library detail route, else `/catalog/:type/:id`), `ingredientCoverUrl(ingredient)` (attached media, else the canon starred/first render, both under `/data/images`) and `usageSummary(usage)` ("1 universe · 2 videos" from the list endpoint's link counts). || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `federatedMediaSupports(status, feature, capability)` mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (`lyrics`, `inputAssets`) from the status-root `features` list, retaining only the legacy `inputAssets` capability block for peers on the previous build because that signal is genuinely per-model, and `peerMediaProviderSnapshot(peer)` returns the status payload to ask it against. `peerModelAcceptsInput(capability, role, status)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. || `fableLoomReadiness.js` | Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting. |diff --git a/client/src/lib/creativeLibraries.js b/client/src/lib/creativeLibraries.jsnew file mode 100644index 0000000000..0afc4c734d--- /dev/null+++ b/client/src/lib/creativeLibraries.js@@ -0,0 +1,56 @@+// Casting, Environments and Objects: focused library pages over the catalog's+// character, place and object ingredients. The catalog row stays the single+// record; these entries only say which page owns a type and how to name it.++export const CREATIVE_LIBRARIES = Object.freeze([+ Object.freeze({ id: 'casting', type: 'character', path: '/casting', label: 'Casting', singular: 'cast member', empty: 'No cast yet.' }),+ Object.freeze({ id: 'environments', type: 'place', path: '/environments', label: 'Environments', singular: 'environment', empty: 'No environments yet.' }),+ Object.freeze({ id: 'objects', type: 'object', path: '/objects', label: 'Objects', singular: 'object', empty: 'No objects yet.' }),+]);++export const libraryById = (id) => CREATIVE_LIBRARIES.find((lib) => lib.id === id) || null;+export const libraryForType = (type) => CREATIVE_LIBRARIES.find((lib) => lib.type === type) || null;++// The library whose page a pathname sits under (`/casting/cat-chr-1` → Casting).+export const libraryForPathname = (pathname = '') =>+ CREATIVE_LIBRARIES.find((lib) => pathname === lib.path || pathname.startsWith(`${lib.path}/`)) || null;++// Detail route for an ingredient: its library page when it has one, otherwise+// the generic catalog editor.+export function ingredientPath(ingredient) {+ const id = encodeURIComponent(ingredient?.id || '');+ const lib = libraryForType(ingredient?.type);+ return lib ? `${lib.path}/${id}` : `/catalog/${encodeURIComponent(ingredient?.type || 'idea')}/${id}`;+}++// Cover image for a card. Attached catalog media wins; canon-mirrored rows fall+// back to the universe's starred or first render. Both are gallery files under+// /data/images (only canon reference sheets live under /data/image-refs).+export function ingredientCoverUrl(ingredient) {+ const payload = ingredient?.payload && typeof ingredient.payload === 'object' ? ingredient.payload : {};+ const key = ingredient?.thumbnailKey+ || (typeof payload.primaryImageRef === 'string' && payload.primaryImageRef)+ || (Array.isArray(payload.imageRefs) ? payload.imageRefs.find((r) => typeof r === 'string' && r) : null);+ return key ? `/data/images/${key}` : null;+}++const USAGE_LABELS = [+ ['universe', 'universe', 'universes'],+ ['music-video', 'video', 'videos'],+ ['creative-director', 'production', 'productions'],+ ['series', 'series', 'series'],+ ['issue', 'issue', 'issues'],+ ['work', 'work', 'works'],+];++// "1 universe · 2 videos" from the list endpoint's per-kind link counts.+export function usageSummary(usage) {+ if (!usage || typeof usage !== 'object') return '';+ return USAGE_LABELS+ .map(([kind, one, many]) => {+ const n = Number(usage[kind]) || 0;+ return n > 0 ? `${n} ${n === 1 ? one : many}` : null;+ })+ .filter(Boolean)+ .join(' · ');+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2601fa5ce0..4f3a3a2bcb 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -39,6 +39,7 @@ export * from './characterFramework.js';export * from './characterIntegrity.js';export * from './catalogTypes.js';export * from './creativeDirectorPlan.js';+export * from './creativeLibraries.js';export * from './creativeDirectorPreview.js';export * from './creativeDirectorStatus.js';export * from './editorialRoadmap.js';diff --git a/client/src/lib/layoutRoutes.js b/client/src/lib/layoutRoutes.jsindex 42aeb20530..4da3cf9ccc 100644--- a/client/src/lib/layoutRoutes.js+++ b/client/src/lib/layoutRoutes.js@@ -42,6 +42,9 @@ const EXACT_FULL_WIDTH_PATHS = [// body (#10994). Exact entries are the indexes whose detail routes are a// different component (and already classified, or intentionally padded).'/catalog',+ '/casting',+ '/environments',+ '/objects','/universes','/rounds','/story-builder',@@ -70,6 +73,10 @@ const FULL_WIDTH_PATH_PREFIXES = [// Catalog detail (/catalog/{type}/{id}) and Ingest (/catalog/ingest)// own their scroll. The /catalog index is an EXACT full-width entry above.'/catalog/',+ // Casting / Environments / Objects detail pages render the catalog editor.+ '/casting/',+ '/environments/',+ '/objects/','/cos',// Both the Creative Director index and its detail editor manage// their own internal scroll (flex-col h-full + overflow-auto body),diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.jsindex 04e5011a11..4df253035d 100644--- a/client/src/lib/navPresentation.js+++ b/client/src/lib/navPresentation.js@@ -97,6 +97,7 @@ import { AudioLines,Waypoints,AtSign,Drama,+ Mountain,UserRound,Video,ListTodo,@@ -172,6 +173,9 @@ export const NAV_PRESENTATION = {'/3d': { icon: Boxes },'/authors': { icon: FilePen },'/catalog': { icon: Sparkles },+ '/casting': { icon: Drama },+ '/environments': { icon: Mountain },+ '/objects': { icon: Package },'/creative-commission': { icon: CalendarClock },'/code-animation': { icon: FileCode2 },'/creative-director': { icon: Clapperboard },diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 51d2362e3d..7344be08c2 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -7,7 +7,7 @@ import { LEGACY_SHEET_VARIANT_ID, readSheetPointer, listSheetPointers } from '..*/import { useCallback, useEffect, useRef, useState } from 'react';-import { useNavigate, useParams, Link } from 'react-router';+import { useNavigate, useParams, useLocation, Link } from 'react-router';import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown, Upload, Mic, Square } from 'lucide-react';import toast from '../components/ui/Toast';import FilePickerButton from '../components/ui/FilePickerButton';@@ -50,6 +50,7 @@ import TagPicker from '../components/TagPicker';import GenericIngredientFields from '../components/GenericIngredientFields';import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';+import { libraryForPathname, ingredientPath } from '../lib/creativeLibraries';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';import { timeAgo, formatDateTime } from '../utils/formatters';@@ -133,6 +134,10 @@ export default function CatalogIngredient() {activeVisitRef.current = { id, generation: activeVisitRef.current.generation + 1 };}const navigate = useNavigate();+ // Opened from Casting / Environments / Objects → Back and post-delete return+ // there; otherwise to the catalog.+ const { pathname } = useLocation();+ const backPath = libraryForPathname(pathname)?.path || '/catalog';// Merged type registry (system + user-defined). Falls back synchronously to// the static built-ins so the editor renders before the fetch resolves.const { getType: getMergedType } = useCatalogTypes();@@ -175,7 +180,7 @@ export default function CatalogIngredient() {if (!d?.ingredient) {setLoading(false);toast.error('Ingredient not found');- navigate('/catalog');+ navigate(backPath);return;}const r = d.ingredient;@@ -196,10 +201,10 @@ export default function CatalogIngredient() {if (cancelled) return;setLoading(false);toast.error(err?.message || 'Failed to load ingredient');- navigate('/catalog');+ navigate(backPath);});return () => { cancelled = true; };- }, [id, navigate]);+ }, [id, navigate, backPath]);// Add an outbound edge (this ingredient → picked target). Optimistically// appends to local state so the panel updates without a refetch.@@ -403,7 +408,7 @@ export default function CatalogIngredient() {.catch((err) => { toast.error(err?.message || 'Delete failed'); return false; });if (ok) {toast.success('Deleted');- navigate('/catalog');+ navigate(backPath);}};@@ -501,7 +506,7 @@ export default function CatalogIngredient() {</div></div><div className="flex items-center gap-2">- <Link to="/catalog" className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm text-gray-400 hover:text-white">+ <Link to={backPath} className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm text-gray-400 hover:text-white"><ArrowLeft size={14} aria-hidden="true" /> Back</Link><button type="button" onClick={handleSave} disabled={saving}@@ -915,7 +920,7 @@ function RelationsPanel({ record, relations, evidence, onAdd, onRemove }) {const chip = (other) => {const badge = CATALOG_BADGE_BY_ID[other?.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';return (- <Link to={`/catalog/${encodeURIComponent(other?.type || 'idea')}/${encodeURIComponent(other?.id)}`}+ <Link to={ingredientPath({ type: other?.type, id: other?.id })}className="inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200 hover:opacity-80"><span className="truncate max-w-[16rem]">{other?.name || other?.id || '(unnamed)'}</span><span className={`text-[9px] uppercase tracking-wider px-1 py-0.5 rounded border ${badge}`}>{other?.type}</span>@@ -1505,7 +1510,7 @@ function SourcesPanel({ sources, evidence }) {{siblings.map((sib) => {const badge = CATALOG_BADGE_BY_ID[sib.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';return (- <Link key={sib.id} to={`/catalog/${encodeURIComponent(sib.type || 'idea')}/${encodeURIComponent(sib.id)}`}+ <Link key={sib.id} to={ingredientPath(sib)}className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200 hover:opacity-80"><span className="truncate max-w-[12rem]">{sib.name || sib.id}</span><span className={`text-[9px] uppercase tracking-wider px-1 py-0.5 rounded border ${badge}`}>{sib.type}</span>diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxindex deea105e69..820b02102a 100644--- a/client/src/pages/CatalogIngredient.test.jsx+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -416,7 +416,7 @@ describe('CatalogIngredient — character sheet', () => {// its own detail page.expect(screen.getByText('From the same source')).toBeTruthy();const siblingLink = screen.getByText('Sibling Place').closest('a');- expect(siblingLink.getAttribute('href')).toBe('/catalog/place/cat-plc-1');+ expect(siblingLink.getAttribute('href')).toBe('/environments/cat-plc-1');});it('renders no "From the same source" stub for a solo extraction or a manually-created ingredient (#7617)', async () => {diff --git a/client/src/pages/CreativeLibrary.jsx b/client/src/pages/CreativeLibrary.jsxnew file mode 100644index 0000000000..4cc7b84ffc--- /dev/null+++ b/client/src/pages/CreativeLibrary.jsx@@ -0,0 +1,221 @@+/**+ * CreativeLibrary — the Casting, Environments and Objects pages.+ *+ * One component, three kinds: each page is a type-scoped view over the+ * catalog's character / place / object ingredients (see lib/creativeLibraries).+ * The catalog row is the single record; universes, music videos and other+ * projects link to it. Filters live in the URL so a filtered view is shareable.+ */++import { useCallback, useEffect, useMemo, useState } from 'react';+import { Link, useNavigate } from 'react-router';+import { Drama, Mountain, Package, Plus, Search, Loader2, Sparkles, Library } from 'lucide-react';+import PageHeader from '../components/PageHeader';+import MediaImage from '../components/MediaImage';+import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';+import toast from '../components/ui/Toast';+import { listCatalogIngredients, getCatalogFacets, createCatalogIngredient } from '../services/apiCatalog';+import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';+import { usePagedCollection } from '../hooks/usePagedCollection';+import useUrlParams from '../hooks/useUrlParams';+import useCancelableDebounce from '../hooks/useCancelableDebounce';+import { libraryById, ingredientPath, ingredientCoverUrl, usageSummary } from '../lib/creativeLibraries';+import { formatCount } from '../utils/formatters';++const PAGE_SIZE = 48;+const LIBRARY_ICONS = { casting: Drama, environments: Mountain, objects: Package };+const UNLINKED = '__unlinked';++function LibraryTile({ ingredient }) {+ const name = ingredient.name || '(untitled)';+ const cover = ingredientCoverUrl(ingredient);+ const usage = usageSummary(ingredient.usage);+ return (+ <li className="min-w-0">+ <Link+ to={ingredientPath(ingredient)}+ className="group flex flex-col h-full bg-port-card border border-port-border rounded-lg overflow-hidden hover:border-port-accent/60"+ >+ <div className="aspect-[3/4] w-full bg-port-bg flex items-center justify-center overflow-hidden">+ {cover ? (+ <MediaImage src={cover} alt={name} className="w-full h-full object-cover" loading="lazy" />+ ) : (+ <Sparkles size={22} className="text-gray-600" aria-hidden="true" />+ )}+ </div>+ <span className="flex flex-col gap-0.5 px-2.5 py-2 min-w-0">+ <span className="text-sm text-white font-medium truncate">{name}</span>+ <span className="text-[11px] text-gray-500 truncate">{usage || 'Not used yet'}</span>+ </span>+ </Link>+ </li>+ );+}++export default function CreativeLibrary({ libraryId }) {+ const library = libraryById(libraryId);+ const navigate = useNavigate();+ const { getType } = useCatalogTypes();+ const typeMeta = getType(library.type);+ const Icon = LIBRARY_ICONS[library.id] || Library;++ const [searchParams, updateParams] = useUrlParams();+ const scope = searchParams.get('scope') || '';+ const urlQ = searchParams.get('q') || '';+ const [searchInput, setSearchInput] = useState(urlQ);+ const [scheduleQMirror] = useCancelableDebounce();+ useEffect(() => {+ scheduleQMirror(() => updateParams({ q: searchInput.trim() }, { replace: true }), 300);+ }, [searchInput, updateParams, scheduleQMirror]);++ const [facets, setFacets] = useState(null);+ useEffect(() => {+ let active = true;+ getCatalogFacets({ silent: true }).then((f) => { if (active) setFacets(f || null); }).catch(() => {});+ return () => { active = false; };+ }, []);+ const totalForType = facets?.types?.find((t) => t.type === library.type)?.count;++ const fetchPage = useCallback(async ({ cursor, signal }) => {+ const offset = cursor || 0;+ const filter = scope === UNLINKED ? { unlinked: true } : scope ? { refKind: 'universe', refId: scope } : {};+ const data = await listCatalogIngredients({ type: library.type, q: urlQ, ...filter, limit: PAGE_SIZE, offset, signal, silent: true });+ const items = Array.isArray(data?.items) ? data.items : [];+ return { items, nextCursor: items.length === PAGE_SIZE ? offset + items.length : null };+ }, [library.type, urlQ, scope]);+ const page = usePagedCollection(fetchPage);++ const [showForm, setShowForm] = useState(false);+ const [form, setForm] = useState({ name: '', content: '' });+ const [creating, setCreating] = useState(false);+ const contentKey = typeMeta?.primaryContentKey || 'description';++ const handleCreate = async (e) => {+ e.preventDefault();+ const name = form.name.trim();+ if (!name) return;+ const content = form.content.trim();+ setCreating(true);+ const created = await createCatalogIngredient(+ { type: library.type, name, payload: content ? { [contentKey]: content } : {}, tags: [] },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || `Failed to create ${library.singular}`); return null; });+ setCreating(false);+ if (!created) return;+ navigate(ingredientPath(created));+ };++ const universes = useMemo(() => facets?.universes || [], [facets]);++ return (+ <div className="flex h-full min-h-0 flex-col">+ <PageHeader+ icon={Icon}+ title={(+ <span className="inline-flex items-baseline gap-2">+ {library.label}+ {totalForType != null && (+ <span className="text-sm font-normal text-gray-500 whitespace-nowrap">{formatCount(totalForType)}</span>+ )}+ </span>+ )}+ actions={(+ <div className="flex items-center gap-2">+ <Link+ to={`/catalog?type=${encodeURIComponent(library.type)}`}+ className="inline-flex items-center gap-1.5 px-3 py-2 min-h-[40px] rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-gray-300 hover:text-white text-sm"+ >+ <Library size={16} aria-hidden="true" /> Catalog+ </Link>+ <button+ type="button"+ onClick={() => setShowForm((v) => !v)}+ className="inline-flex items-center gap-1.5 px-3 py-2 min-h-[40px] rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"+ >+ <Plus size={16} aria-hidden="true" /> New+ </button>+ </div>+ )}+ />+ <div className="flex-1 min-h-0 overflow-auto p-3 sm:p-4 flex flex-col gap-3">+ {showForm && (+ <form onSubmit={handleCreate} className="p-3 bg-port-card border border-port-border rounded-lg flex flex-col gap-3">+ <div>+ <label htmlFor="library-new-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Name</label>+ <input+ id="library-new-name"+ type="text"+ value={form.name}+ maxLength={200}+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div>+ <label htmlFor="library-new-content" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ {typeMeta?.primaryContentLabel || 'Description'} <span className="normal-case">(optional)</span>+ </label>+ <textarea+ id="library-new-content"+ rows={3}+ value={form.content}+ onChange={(e) => setForm((f) => ({ ...f, content: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div className="flex justify-end gap-2">+ <button type="button" onClick={() => setShowForm(false)} className="px-3 py-2 min-h-[40px] rounded-lg text-gray-400 hover:text-white text-sm">Cancel</button>+ <button+ type="submit"+ disabled={creating || !form.name.trim()}+ className="inline-flex items-center gap-2 px-4 py-2 min-h-[40px] rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ >+ {creating && <Loader2 size={14} className="animate-spin" aria-hidden="true" />} Create+ </button>+ </div>+ </form>+ )}++ <div className="relative">+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />+ <label htmlFor="library-search" className="sr-only">Search {library.label}</label>+ <input+ id="library-search"+ type="search"+ value={searchInput}+ onChange={(e) => setSearchInput(e.target.value)}+ placeholder="Search by name or description"+ className="w-full pl-9 pr-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"+ />+ </div>++ <div className="flex items-center gap-2 -mx-3 px-3 overflow-x-auto scrollbar-hide touch-pan-x sm:mx-0 sm:px-0 sm:flex-wrap" role="group" aria-label="Filter">+ {[{ id: '', label: 'All' }, ...universes.map((u) => ({ id: u.refId, label: u.name })), { id: UNLINKED, label: 'Not in a universe' }].map((chip) => (+ <button+ key={chip.id || 'all'}+ type="button"+ aria-pressed={scope === chip.id}+ onClick={() => updateParams({ scope: chip.id })}+ className={`shrink-0 whitespace-nowrap text-xs px-3 py-2 sm:py-1.5 rounded-full border ${+ scope === chip.id ? 'bg-port-accent border-port-accent text-white' : 'border-port-border text-gray-300 hover:text-white'+ }`}+ >+ {chip.label}+ </button>+ ))}+ </div>++ {page.loaded && page.items.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-sm text-gray-400">+ {urlQ || scope ? `No ${library.label.toLowerCase()} match this filter.` : library.empty}+ </div>+ ) : (+ <ul className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-3">+ {page.items.map((it) => <LibraryTile key={it.id} ingredient={it} />)}+ </ul>+ )}+ <InfiniteScrollFooter hasMore={page.hasMore} loading={page.loading} error={page.error} onLoadMore={page.loadMore} />+ </div>+ </div>+ );+}diff --git a/client/src/pages/CreativeLibrary.test.jsx b/client/src/pages/CreativeLibrary.test.jsxnew file mode 100644index 0000000000..cbe358c280--- /dev/null+++ b/client/src/pages/CreativeLibrary.test.jsx@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const navigateMock = vi.hoisted(() => vi.fn());+vi.mock('react-router', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, useNavigate: () => navigateMock };+});++vi.mock('../services/apiCatalog', () => ({+ listCatalogIngredients: vi.fn(),+ createCatalogIngredient: vi.fn(),+ getCatalogFacets: vi.fn(),+}));+vi.mock('../services/apiCatalogTypes', () => ({ listCatalogTypes: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+vi.mock('../components/MediaImage', () => ({+ default: ({ src, alt, ...rest }) => <img src={src} alt={alt} {...rest} />,+}));++import CreativeLibrary from './CreativeLibrary';+import { listCatalogIngredients, createCatalogIngredient, getCatalogFacets } from '../services/apiCatalog';+import { listCatalogTypes } from '../services/apiCatalogTypes';++const renderLibrary = (libraryId, entry) => render(+ <MemoryRouter initialEntries={[entry]}>+ <CreativeLibrary libraryId={libraryId} />+ </MemoryRouter>,+);++describe('CreativeLibrary', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listCatalogTypes.mockResolvedValue([]);+ getCatalogFacets.mockResolvedValue({+ types: [{ type: 'character', count: 2 }],+ universes: [{ refId: 'u-1', name: 'Example Universe', count: 3 }],+ });+ });++ it('lists only its type, links tiles to the library detail route, and shows canon images and usage', async () => {+ listCatalogIngredients.mockResolvedValue({ items: [+ { id: 'cat-chr-1', type: 'character', name: 'Ada', payload: { primaryImageRef: 'ada.png' }, thumbnailKey: null, usage: { universe: 1, 'music-video': 2 } },+ { id: 'cat-chr-2', type: 'character', name: 'Bo', payload: {}, thumbnailKey: 'bo.png', usage: {} },+ ] });+ renderLibrary('casting', '/casting');++ const ada = await screen.findByRole('link', { name: /Ada/ });+ expect(ada).toHaveAttribute('href', '/casting/cat-chr-1');+ expect(screen.getByRole('img', { name: 'Ada' })).toHaveAttribute('src', '/data/images/ada.png');+ expect(screen.getByRole('img', { name: 'Bo' })).toHaveAttribute('src', '/data/images/bo.png');+ expect(screen.getByText('1 universe · 2 videos')).toBeInTheDocument();+ expect(screen.getByText('Not used yet')).toBeInTheDocument();+ expect(listCatalogIngredients).toHaveBeenCalledWith(expect.objectContaining({ type: 'character', offset: 0 }));+ });++ it('scopes to a universe or to unlinked records from the URL', async () => {+ listCatalogIngredients.mockResolvedValue({ items: [] });+ renderLibrary('environments', '/environments?scope=u-1');+ await waitFor(() => expect(listCatalogIngredients).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'place', refKind: 'universe', refId: 'u-1' }),+ ));+ expect(await screen.findByText('No environments match this filter.')).toBeInTheDocument();++ fireEvent.click(await screen.findByRole('button', { name: 'Not in a universe' }));+ await waitFor(() => expect(listCatalogIngredients).toHaveBeenLastCalledWith(+ expect.objectContaining({ type: 'place', unlinked: true }),+ ));+ });++ it('creates a record of its type and opens it', async () => {+ listCatalogIngredients.mockResolvedValue({ items: [] });+ createCatalogIngredient.mockResolvedValue({ id: 'cat-obj-9', type: 'object', name: 'Reel can' });+ renderLibrary('objects', '/objects');++ fireEvent.click(await screen.findByRole('button', { name: /New/ }));+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Reel can' } });+ fireEvent.change(screen.getByLabelText(/Description/), { target: { value: 'Dented tin.' } });+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ await waitFor(() => expect(navigateMock).toHaveBeenCalledWith('/objects/cat-obj-9'));+ expect(createCatalogIngredient).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'object', name: 'Reel can', payload: { description: 'Dented tin.' } }),+ { silent: true },+ );+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 0b6939934d..fb2d8e4a23 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -41,9 +41,12 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.apps.submodules', path: `/apps/${PORTOS_APP_ID}/submodules`, label: 'PortOS Submodules', section: 'Apps', previousPaths: ['/devtools/submodules'], aliases: ['submodules', 'devtools-submodules', 'portos-submodules'], keywords: ['git', 'slashdo', 'vendored', 'update submodule'] },{ id: 'nav.templates', path: '/templates', label: 'Templates', section: 'Main', aliases: ['templates', 'app-templates'], keywords: ['app template', 'create app', 'pre-configured', 'starter'] },- { id: 'nav.catalog', path: '/catalog', label: 'Catalog', section: 'Create', aliases: ['catalog', 'ingredients', 'cast', 'creative-catalog'], keywords: ['character', 'place', 'object', 'idea', 'scene', 'concept', 'inventory', 'reference', 'creative'] },+ { id: 'nav.catalog', path: '/catalog', label: 'Catalog', section: 'Create', aliases: ['catalog', 'ingredients', 'creative-catalog'], keywords: ['character', 'place', 'object', 'idea', 'scene', 'concept', 'inventory', 'reference', 'creative'] },{ id: 'nav.catalog.ingest', path: '/catalog/ingest', label: 'Catalog Ingest', section: 'Create', aliases: ['catalog-ingest', 'ingest', 'paste-scrap', 'extract-ingredients'], keywords: ['paste', 'snippet', 'scene', 'idea', 'extract', 'scrap', 'import-catalog'] },{ id: 'nav.catalog.settings', path: '/catalog?settings=1', label: 'Catalog Types', section: 'Create', previousPaths: ['/settings/catalog'], aliases: ['catalog settings', 'catalog-settings', 'settings-catalog', 'catalog-types'], keywords: ['catalog', 'types', 'labels', 'character', 'place', 'object', 'taxonomy'] },+ { id: 'nav.create.casting', path: '/casting', label: 'Casting', section: 'Create', aliases: ['casting', 'cast', 'characters', 'actors', 'casting-sheets', 'cast-list'], keywords: ['character', 'casting sheet', 'turnaround', 'wardrobe', 'looks', 'performer', 'actor', 'reference'] },+ { id: 'nav.create.environments', path: '/environments', label: 'Environments', section: 'Create', aliases: ['environments', 'environment', 'sets', 'locations', 'places', 'set-list'], keywords: ['place', 'set', 'location', 'clean plate', 'background', 'scene setting', 'reference'] },+ { id: 'nav.create.objects', path: '/objects', label: 'Objects', section: 'Create', aliases: ['objects', 'props', 'prop-list', 'items'], keywords: ['object', 'prop', 'artifact', 'talisman', 'macguffin', 'reference'] },{ id: 'nav.media', path: '/media', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },{ id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'Create', tabGroup: 'media', tabId: 'image', previousPaths: ['/image-gen'], aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },{ id: 'nav.media.video', path: '/video/generate', label: 'Generate Video', tabLabel: 'Video', section: 'Create', tabGroup: 'media', tabId: 'video', previousPaths: ['/video-gen', '/media/video'], aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx', 'episode composer', 'continuous video', 'multi-scene'] },diff --git a/server/services/catalogDB.facets.db.test.js b/server/services/catalogDB.facets.db.test.jsindex 212e5b4f02..b7f9eb1351 100644--- a/server/services/catalogDB.facets.db.test.js+++ b/server/services/catalogDB.facets.db.test.js@@ -160,6 +160,18 @@ describe.skipIf(!runDb)('catalogDB facets + album filters (#1762)', () => {await query('DELETE FROM creative_director_projects WHERE id = $1', [cdId]).catch(() => {});});+ it('counts usage per kind from live targets only, so a deleted universe stops counting', async () => {+ const ing = await catalogDB.createIngredient({ type: 'character', name: `Usage ${nonce}` });+ createdIngredientIds.add(ing.id);+ await catalogDB.linkIngredientToRef(ing.id, 'universe', UNI_ID, 'cast-character');+ await catalogDB.linkIngredientToRef(ing.id, 'universe', UNI_ID, 'mentioned');+ await catalogDB.linkIngredientToRef(ing.id, 'universe', DEAD_UNI_ID, 'cast-character');+ await catalogDB.linkIngredientToRef(ing.id, 'series', SER_ID, 'cast');++ const { items } = await catalogDB.listIngredients({ ids: [ing.id], limit: 5 });+ expect(items[0].usage).toEqual({ universe: 1, series: 1 });+ });+it('getCatalogFacets aggregates type/universe/series/tag facets + bucket counts', async () => {const linked = await catalogDB.createIngredient({ type: 'character', name: `FacetLinked ${nonce}`, tags: [TAG] });const seriesLinked = await catalogDB.createIngredient({ type: 'character', name: `FacetSeries ${nonce}` });diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.jsindex 5e45945e51..7f308c2325 100644--- a/server/services/catalogDB/ingredients.js+++ b/server/services/catalogDB/ingredients.js@@ -25,6 +25,8 @@ import {rowToRevision,HAS_LIVE_HOMING_REF,HAS_ANY_HOMING_REF,+ HOMING_REF_KINDS_SQL,+ liveHomingTargetSql,} from './shared.js';import { normalizeTags } from './tags.js';@@ -324,6 +326,18 @@ const THUMBNAIL_KEY_SUBQUERY = `(LIMIT 1) AS thumbnail_key`;+// Per-kind count of the distinct records each row is linked to ({ universe: 1,+// series: 2 }), for the "used in" line on library cards. Same light-path scope+// as the thumbnail subquery.+const REF_USAGE_SUBQUERY = `(+ SELECT jsonb_object_agg(u.ref_kind, u.n) FROM (+ SELECT r.ref_kind, COUNT(DISTINCT r.ref_id) AS n FROM catalog_ingredient_refs r+ WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false+ AND (r.ref_kind NOT IN (${HOMING_REF_KINDS_SQL}) OR ${liveHomingTargetSql('r')})+ GROUP BY r.ref_kind+ ) u+ ) AS ref_usage`;+export async function listIngredients({ ids, type, tag, query: q, refKind = null, refId = null, unlinked = false, orphaned = false, scrapId = null, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {const conditions = ['deleted = false'];const params = [];@@ -415,13 +429,13 @@ export async function listIngredients({ ids, type, tag, query: q, refKind = null// don't pay for the correlated subquery. The field rides ALONGSIDE// rowToIngredient's shape (attached below), so the sync/revision payloads// that share rowToIngredient stay untouched.- const cols = includeEmbedding ? '*' : `${INGREDIENT_LIGHT_COLS}, ${THUMBNAIL_KEY_SUBQUERY}`;+ const cols = includeEmbedding ? '*' : `${INGREDIENT_LIGHT_COLS}, ${THUMBNAIL_KEY_SUBQUERY}, ${REF_USAGE_SUBQUERY}`;const result = await query(`SELECT ${cols} FROM catalog_ingredients ${where} ${orderBy} LIMIT $${idx++} OFFSET $${idx}`,params,);return {- items: result.rows.map((row) => ({ ...rowToIngredient(row), thumbnailKey: row.thumbnail_key ?? null })),+ items: result.rows.map((row) => ({ ...rowToIngredient(row), thumbnailKey: row.thumbnail_key ?? null, usage: row.ref_usage ?? {} })),nextOffset: offset + result.rows.length,};}diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.jsindex 787945e5e6..15fce70e2b 100644--- a/server/services/catalogDBMedia.test.js+++ b/server/services/catalogDBMedia.test.js@@ -208,6 +208,20 @@ describe('listIngredients card thumbnail', () => {const { items } = await catalogDB.listIngredients({ limit: 10 });expect(items[0].thumbnailKey).toBeNull();});++ it('returns per-kind link counts as usage, defaulting to an empty object', async () => {+ const db = await import('../lib/db.js');+ db.query.mockResolvedValueOnce({ rows: [+ ingredientRow({ id: 'cat-chr-a', ref_usage: { universe: 1, 'creative-director': 2 } }),+ ingredientRow({ id: 'cat-chr-b', ref_usage: null }),+ ] });+ const { items } = await catalogDB.listIngredients({ limit: 10 });+ const sql = db.query.mock.calls.at(-1)[0].replace(/\s+/g, ' ');+ expect(sql).toMatch(/COUNT\(DISTINCT r\.ref_id\)/i);+ expect(sql).toMatch(/r\.deleted = false/i);+ expect(items[0].usage).toEqual({ universe: 1, 'creative-director': 2 });+ expect(items[1].usage).toEqual({});+ });});describe('getMaxSequences includes the media cursor', () => {