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 "Pick from Catalog" to Universe Builder canon panels
[._.]/ Adam Eivye397666cd4cb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cb9ad5639a..fcc382db22 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@## Added+- **[catalog-universe-builder-picker] "Pick from Catalog" on Universe Builder canon panels.** Each Characters / Places / Objects section in Universe Builder (Bible + Cast/Places/Objects tabs) now has a "Pick from Catalog" button next to "Render all" / bulk-lock. It opens the shared Ingredient Picker scoped to that type; picking an ingredient copies its payload into a new embedded canon entry, stamps the catalog row's id onto the entry as `ingredientId`, and links the ingredient back to the universe (`catalog_ingredient_refs`, role `canon-character` / `canon-place` / `canon-object`) so the "Appears in" panel populates. The `ingredientId` stamp ties the embedded entry to its durable catalog row and lets the boot-time bible→catalog backfill recreate the SAME catalog id on every federated peer instead of minting a divergent one. Already-linked ingredients are excluded from the picker so you can't double-add the same character.- **[catalog-pipeline-series-cast] "Cast (from Catalog)" panel on Series, Issue, and Writers Room pages.** A new reusable panel surfaces every catalog ingredient linked to the active series / issue / work bible — drawn from the existing `catalog_ingredient_refs` table — and lets you attach more via the existing Ingredient Picker or unlink with a click. Series records carry no embedded `characters[]` array, so the cast is purely additive and replicates through the existing catalog sync. The panel lives in the Series bible sidebar above "Canon", at the top of the active stage scroll on Issue (visible across every stage tab), and above the work editor in Writers Room when a work is selected.- **[catalog-bulk-import] Bulk-ingest endpoint for the Catalog.** A new "Bulk Import" panel on `/catalog/ingest` accepts JSON, CSV (`type,name,description,tags` header), or simple markdown (`## <Type>: <Name>` headings with paragraph body and optional `tags:` line) and creates ingredients directly — no per-row review screen. Each row is re-validated against the same Zod schema the single-create endpoint uses, so one bad row rolls back the entire batch; vector embeddings run in parallel before the transaction (same as the scrap-commit path), so bulk-imported rows are search-ready immediately rather than waiting for the embeddings backfill. `POST /api/catalog/bulk-import` is Zod-validated (2 MB payload cap), stamps optional `defaults.tags` plus an optional `universe`/`series`/`work`/`issue` ref onto every row in the same transaction, and surfaces parser warnings (e.g. `## Plce: …` typos in markdown that don't match a known type) in the response so users notice typos that would otherwise be silently skipped.- **[catalog-export-bundle] Export a catalog slice as a portable bundle.** `GET /api/catalog/export?refKind=universe|series|issue|work&refId=…&format=json|markdown|yaml` walks the ref table for the target, hydrates each ingredient + its scraps + ref-links, and returns an `attachment` bundle. Pairs with bulk import for round-trip portability (export → edit → re-import) — useful for sharing a universe's cast outside peer-sync or seeding a fresh install from a community pack. Relations and media-ref hydration ship with their own PLAN items.diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex 5cfff662d3..f8edfa1b80 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -14,9 +14,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import {- Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus,+ Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus, Sparkles,} from 'lucide-react';import toast from '../ui/Toast';+import IngredientPicker from '../IngredientPicker';+import { linkCatalogIngredient } from '../../services/apiCatalog';import {extractUniverseCanon,refineUniverseCharacter,@@ -45,6 +47,33 @@ const capImageRefs = (refs) => (: refs);+// Build an embedded canon entry from a picked catalog ingredient. The+// ingredient's `payload` already carries the same field names the universe+// canon sanitizer whitelists (name / physicalDescription / description / …),+// so we spread it and overlay the canonical name + the durable `ingredientId`+// stamp that ties this embedded entry back to its catalog row.+//+// `id` is intentionally omitted — the server's `ensureId` mints a fresh+// kind-prefixed id (`chr-`/`plc-`/`obj-`) on save. We must NOT carry the+// catalog id into `entry.id`; identity lives in `ingredientId` so the+// peer-reconciliation backfill (`migrateBibleToCatalog`) recreates the same+// catalog row id on every peer instead of minting a divergent one.+export function buildCanonEntryFromIngredient(ingredient) {+ if (!ingredient || typeof ingredient !== 'object') return null;+ const payload = (ingredient.payload && typeof ingredient.payload === 'object')+ ? ingredient.payload+ : {};+ const entry = { ...payload };+ // Strip any id/timestamps the payload may carry from its origin record so+ // the server mints fresh ones and doesn't collide with an existing entry.+ delete entry.id;+ delete entry.createdAt;+ delete entry.updatedAt;+ entry.name = String(ingredient.name || payload.name || '').trim() || 'Untitled';+ entry.ingredientId = ingredient.id;+ return entry;+}+// `descField` is the writable field bound to the inline description editor in// `CanonCard`. `descFor` (used for the render prompt + the read-only fallback// view) prefers the primary then the legacy/sibling field — so for characters@@ -100,6 +129,9 @@ export default function UniverseCanonSection({const togglingLockRef = useRef(null);const [extractText, setExtractText] = useState('');const [extractOpen, setExtractOpen] = useState(false);+ // Which kind's "Pick from Catalog" modal is open (a KINDS entry, or null).+ const [catalogPickerKind, setCatalogPickerKind] = useState(null);+ const [catalogLinking, setCatalogLinking] = useState(false);// Per-canon-entry usage map: `{ characters: { [entryId]: [{seriesId, seriesName, issueCount, ...}] }, ... }`.// Loaded lazily — usage is a derived view and shouldn't block the initial// paint. Refetched after mutations that change the canon shape (extract /@@ -489,6 +521,49 @@ export default function UniverseCanonSection({if (errMsg) toast.error(`Render failed: ${errMsg}`);}, []);+ // "Pick from Catalog" → copy a shared catalog ingredient into this universe+ // as a new embedded canon entry and link the ingredient back to the universe+ // via catalog_ingredient_refs (role `canon-<kind>`). The embedded entry+ // carries the catalog id as `ingredientId` so the two records stay tied and+ // peer-reconciliation preserves the same id on every peer.+ const handlePickFromCatalog = useCallback(async (kind, ingredient) => {+ const picked = Array.isArray(ingredient) ? ingredient[0] : ingredient;+ if (!picked || !universe || catalogLinking) return;+ const kindKey = kind.key;+ const list = Array.isArray(universe[kindKey]) ? universe[kindKey] : [];+ // Dedup by ingredientId — re-picking an already-linked ingredient is a+ // no-op (mirrors the server-side canon name dedup, but keyed on the+ // durable ingredient identity so renames don't slip a duplicate in).+ if (list.some((e) => e?.ingredientId && e.ingredientId === picked.id)) {+ toast.error(`${picked.name || 'Ingredient'} is already in this universe`);+ setCatalogPickerKind(null);+ return;+ }+ const entry = buildCanonEntryFromIngredient(picked);+ if (!entry) return;+ setCatalogLinking(true);+ setCatalogPickerKind(null);+ const capturedId = universeId;+ const nextList = [...list, entry];+ // Optimistic append so the new row shows immediately; the server response+ // (with the minted entry id) replaces it.+ onUniverseChange({ ...universe, [kindKey]: nextList });+ const updated = await updateUniverse(universeId, { [kindKey]: nextList })+ .catch((err) => { toast.error(`Add from Catalog failed: ${err.message}`); return null; });+ if (!updated) { if (mountedRef.current) setCatalogLinking(false); return; }+ if (mountedRef.current && currentUniverseIdRef.current === capturedId) onUniverseChange(updated);+ // Link the catalog ingredient back to the universe so the "Appears in"+ // panel populates. Non-fatal: the embedded entry already carries the+ // ingredientId, so a failed link still keeps the records tied.+ await linkCatalogIngredient(+ picked.id,+ { refKind: 'universe', refId: universeId, role: `canon-${kind.apiKind}` },+ { silent: true },+ ).catch((err) => { toast.error(`Linked entry, but catalog ref failed: ${err.message}`); });+ if (mountedRef.current) setCatalogLinking(false);+ toast.success(`Added ${picked.name || 'ingredient'} from Catalog`);+ }, [universe, universeId, onUniverseChange, mountedRef, catalogLinking]);+// Inline-edit channel for canon fields the user types/picks directly// (setting intExt + timeOfDay chips, primaryImageRef pinning, wardrobe// edits). Optimistic — UI updates before the server roundtrip so chip@@ -679,14 +754,31 @@ export default function UniverseCanonSection({compact={!!kindFilter}onRenderAll={() => handleRenderAll(kind)}renderingAll={renderAllKindKey === kind.key}+ onPickFromCatalog={() => setCatalogPickerKind(kind)}+ catalogLinking={catalogLinking}/>))}+ {/* Single shared picker — `catalogPickerKind` carries the KINDS entry+ whose "Pick from Catalog" button opened it, so the picker scopes its+ search to that ingredient type. */}+ <IngredientPicker+ open={!!catalogPickerKind}+ onClose={() => setCatalogPickerKind(null)}+ onSelect={(picked) => { if (catalogPickerKind) handlePickFromCatalog(catalogPickerKind, picked); }}+ type={catalogPickerKind?.apiKind}+ excludeIds={catalogPickerKind+ ? (Array.isArray(universe[catalogPickerKind.key]) ? universe[catalogPickerKind.key] : [])+ .map((e) => e?.ingredientId).filter(Boolean)+ : []}+ refKind="universe"+ refId={universeId}+ /></section>);}-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false }) {// Universe-only character wiring — `null` for non-character kinds so// CanonCard's gate stays `kind === 'characters' && characterExtensions`.// Memoized so the BASE object is stable across re-renders that aren't@@ -722,6 +814,19 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rendeconst controls = (<>+ {onPickFromCatalog ? (+ <button+ type="button"+ onClick={onPickFromCatalog}+ disabled={catalogLinking}+ title={`Add an existing ${kind.singular} from the shared Catalog`}+ aria-label={`Pick ${kind.singular} from Catalog`}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed border border-port-border hover:border-port-accent/50"+ >+ {catalogLinking ? <Loader2 size={11} className="animate-spin" /> : <Sparkles size={11} />}+ Pick from Catalog+ </button>+ ) : null}{onRenderAll ? (<buttontype="button"diff --git a/client/src/components/universe/UniverseCanonSection.picker.test.jsx b/client/src/components/universe/UniverseCanonSection.picker.test.jsxnew file mode 100644index 0000000000..2580cbd1b5--- /dev/null+++ b/client/src/components/universe/UniverseCanonSection.picker.test.jsx@@ -0,0 +1,161 @@+/**+ * Focused tests for the "Pick from Catalog" wiring on UniverseCanonSection:+ * - the pure `buildCanonEntryFromIngredient` payload→entry projection+ * (stamps `ingredientId`, never leaks the catalog id into `entry.id`),+ * - the component flow: button → IngredientPicker → updateUniverse ++ * linkCatalogIngredient with role `canon-<kind>`.+ *+ * The peer-reconciliation invariant the PLAN calls out lives in the helper+ * test: identity must travel as `ingredientId` so the boot-time backfill+ * (`migrateBibleToCatalog`) recreates the SAME catalog row id on every peer.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++vi.mock('../../services/apiCatalog', () => ({+ listCatalogIngredients: vi.fn(),+ linkCatalogIngredient: vi.fn(),+}));++vi.mock('../../services/apiUniverseBuilder', () => ({+ extractUniverseCanon: vi.fn(),+ refineUniverseCharacter: vi.fn(),+ differentiateUniverseCast: vi.fn(),+ updateUniverse: vi.fn(),+ getUniverseCanonUsage: vi.fn(),+ setUniverseCanonLock: vi.fn(),+ setUniverseCanonLockAll: vi.fn(),+ expandUniverseCharacter: vi.fn(),+}));++vi.mock('../../services/apiSystem', () => ({ generateImage: vi.fn() }));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },+}));++import UniverseCanonSection, { buildCanonEntryFromIngredient } from './UniverseCanonSection';+import { listCatalogIngredients, linkCatalogIngredient } from '../../services/apiCatalog';+import { updateUniverse, getUniverseCanonUsage } from '../../services/apiUniverseBuilder';++const baseUniverse = (over = {}) => ({+ id: 'uni-1',+ name: 'Test World',+ characters: [],+ places: [],+ objects: [],+ ...over,+});++const renderSection = (props = {}) => render(+ <MemoryRouter>+ <UniverseCanonSection+ universe={baseUniverse(props.universe)}+ universeId="uni-1"+ onUniverseChange={props.onUniverseChange || vi.fn()}+ imageCfg={{}}+ kindFilter="characters"+ {...props}+ />+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ getUniverseCanonUsage.mockResolvedValue({});+ listCatalogIngredients.mockResolvedValue({ items: [] });+ linkCatalogIngredient.mockResolvedValue({ success: true });+});++describe('buildCanonEntryFromIngredient', () => {+ it('stamps ingredientId and keeps payload fields, never leaking the catalog id into entry.id', () => {+ const ingredient = {+ id: 'cat-chr-abc123',+ type: 'character',+ name: 'Rust Vega',+ payload: {+ id: 'foreign-id-should-be-dropped',+ physicalDescription: 'Lanky drifter in a sun-bleached coat',+ personality: 'wry',+ createdAt: '2020-01-01',+ updatedAt: '2020-01-02',+ },+ };+ const entry = buildCanonEntryFromIngredient(ingredient);+ expect(entry.ingredientId).toBe('cat-chr-abc123');+ expect(entry.id).toBeUndefined(); // server mints a fresh kind-prefixed id+ expect(entry.createdAt).toBeUndefined();+ expect(entry.updatedAt).toBeUndefined();+ expect(entry.name).toBe('Rust Vega');+ expect(entry.physicalDescription).toBe('Lanky drifter in a sun-bleached coat');+ expect(entry.personality).toBe('wry');+ });++ it('falls back to payload.name then a placeholder when the ingredient name is blank', () => {+ expect(buildCanonEntryFromIngredient({ id: 'x', payload: { name: 'From Payload' } }).name)+ .toBe('From Payload');+ expect(buildCanonEntryFromIngredient({ id: 'x', payload: {} }).name).toBe('Untitled');+ });++ it('returns null for non-object input', () => {+ expect(buildCanonEntryFromIngredient(null)).toBeNull();+ expect(buildCanonEntryFromIngredient('nope')).toBeNull();+ });+});++describe('UniverseCanonSection — Pick from Catalog', () => {+ it('opens the picker, then appends + links the picked ingredient with role canon-character', async () => {+ const onUniverseChange = vi.fn();+ updateUniverse.mockResolvedValue(baseUniverse({+ characters: [{ id: 'chr-server-minted', name: 'Rust Vega', ingredientId: 'cat-chr-abc123' }],+ }));+ listCatalogIngredients.mockResolvedValue({+ items: [{ id: 'cat-chr-abc123', type: 'character', name: 'Rust Vega', payload: { physicalDescription: 'drifter' } }],+ });++ renderSection({ onUniverseChange });++ fireEvent.click(screen.getByRole('button', { name: /pick character from catalog/i }));++ // Picker fetches and lists the catalog character; click its row.+ const row = await screen.findByRole('button', { name: /rust vega/i });+ fireEvent.click(row);++ await waitFor(() => expect(updateUniverse).toHaveBeenCalled());++ // updateUniverse received a full `characters` array whose new entry stamps+ // the catalog id as ingredientId (and carries no `id`).+ const [, patch] = updateUniverse.mock.calls[0];+ expect(Array.isArray(patch.characters)).toBe(true);+ const appended = patch.characters[patch.characters.length - 1];+ expect(appended.ingredientId).toBe('cat-chr-abc123');+ expect(appended.id).toBeUndefined();++ await waitFor(() => expect(linkCatalogIngredient).toHaveBeenCalledWith(+ 'cat-chr-abc123',+ { refKind: 'universe', refId: 'uni-1', role: 'canon-character' },+ { silent: true },+ ));+ });++ it('refuses to add an ingredient already linked by ingredientId', async () => {+ const onUniverseChange = vi.fn();+ listCatalogIngredients.mockResolvedValue({+ items: [{ id: 'cat-chr-dup', type: 'character', name: 'Dup', payload: {} }],+ });++ renderSection({+ onUniverseChange,+ universe: { characters: [{ id: 'chr-1', name: 'Dup', ingredientId: 'cat-chr-dup' }] },+ });++ fireEvent.click(screen.getByRole('button', { name: /pick character from catalog/i }));+ // Already-linked ingredients are excluded from the picker list, so the+ // happy path can't even surface a duplicate. Assert the exclusion holds:+ // the picker shows its empty state rather than the duplicate row.+ await waitFor(() => expect(listCatalogIngredients).toHaveBeenCalled());+ expect(screen.queryByRole('button', { name: /^dup$/i })).toBeNull();+ expect(updateUniverse).not.toHaveBeenCalled();+ });+});