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

feat(catalog): Settings UI + generic editor for user-defined ingredient types

[._.]/ Adam Eivy58971a0b35d9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 806442f288..f07098dfae 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
## Added
+- **[catalog-user-defined-types] Define your own Catalog ingredient types in Settings → Catalog.** The catalog shipped six built-in types (character / place / object / idea / scene / concept); you can now add your own — wardrobe, vehicle, faction, magic-system, prompt-fragment, anything — without a code change. A new Settings → Catalog tab lists the built-ins read-only and lets you build custom types from a flat field list: each type is `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string' | 'longtext' | 'tags' | 'ref', maxLength? }] }`. User types persist in `data/settings.json` (`catalogUserTypes`) — not a new table — and merge into the active type registry at boot and on every save, so they show up immediately as filter chips, in the "New" dropdown, and as a fully editable detail page driven by a single generic field renderer (no per-type React file). A `ref` field links to another catalog ingredient via the existing picker; `tags` reuses the tag chip input. Validity is enforced at the app layer (the registry + a Zod refinement on the ingredient `type`), building on the already-dropped DB `CHECK`. User types federate: they ride a new additive `catalogTypes` block in the catalog sync envelope (LWW-merged into each peer's own settings slice, skipping built-in-id collisions), gated by `PORTOS_SCHEMA_VERSIONS.catalog` bumped to 8 — a peer on an older catalog schema rejects a forward-shaped push with a clean 412 rather than dropping the definitions and then choking on ingredients of an unknown type. Deleting a type that still has ingredients is refused unless you force it (the orphaned rows survive under a fallback editor). No DB migration — settings-only.
+
- **[catalog-scrap-chunking] Long scrap pastes are now chunked so extraction doesn't silently degrade.** Pasting (or ingesting via URL / file / voice) a very long scrap — a whole screenplay, a 50k-word manuscript — used to land as a single row and a single LLM extraction pass, quietly overflowing the model's context and dropping ingredients from the tail. Inputs over ~12k characters now split into a parent row plus N child chunks (preferring paragraph, then sentence, then word boundaries so nothing is cut mid-word and the text reassembles exactly); the extractor runs each chunk independently (two at a time) and unions the results, de-duplicating by name + type so the same character mentioned in three chunks appears once. Short pastes behave exactly as before — one row, one pass. The chunk parent/child structure federates to peers (the catalog sync wire version is bumped, so a peer on an older catalog schema declines a forward-shaped push cleanly rather than mis-applying it); existing scraps are left as-is.
- **[catalog-ask-retrieval] Ask now draws on your Creative Catalog.** Asking a question (`/api/ask`, the Ask page, voice) now retrieves matching catalog ingredients — characters, places, objects, ideas, scenes, concepts — alongside memory, brain notes, goals, autobiography, and calendar. Matches use a hybrid Reciprocal-Rank-Fusion search (full-text + vector embedding) sharing the same scoring/budget model as memory retrieval, capped at 4 catalog sources per answer and weighted between brain-notes and autobiography. Each surfaced ingredient is a clickable source chip that deep-links to its catalog detail page. Full-text matching works immediately; semantic (vector) matches appear once you've configured an embedding model and run the catalog embeddings backfill. A catalog hiccup never blocks an answer (the retriever is isolated in the parallel fan-out).
diff --git a/PLAN.md b/PLAN.md
index e315bad691..6c313f32fc 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -18,7 +18,7 @@ _Re-triaged then cleared 2026-05-30 (post-merge follow-up pass): the 6 review-su
The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`) in at least eight places: the Postgres CHECK constraint (`server/scripts/init-db.sql` + `server/lib/db.js:ensureSchema`), the Zod enum in `server/lib/catalogValidation.js`, the extraction prompt in `server/services/catalogExtraction.js`, the `TYPES` array + `PRIMARY_CONTENT_KEY` + `PRIMARY_CONTENT_LABEL` + `payloadSnippet` fallback chain in `client/src/pages/Catalog.jsx`, the type-specific editor branches in `client/src/pages/CatalogIngredient.jsx`, the `IngredientPicker.jsx` type filter, and the `search_tsv` generated column expression. Adding a seventh type today is an 8-file touch across server, client, and a Postgres migration. The items below collapse that surface so the catalog can grow into the long tail of creative shards (lore fragments, factions, magic systems, vehicles, wardrobe, dialogue snippets, beat cards, prompt fragments, voice-memo transcripts, mood references, etc.) without each new shard being a multi-PR effort.
-- [ ] [catalog-user-defined-types] **Allow user-defined ingredient types in the Settings → Catalog section.** Once `[catalog-type-table-vs-check]` lands, expose a Settings UI to add a user type: `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string'|'longtext'|'tags'|'ref', maxLength? }] }`. Persisted in the new `catalog_ingredient_types` table with `system: false`; the registry merges seeded + user types at boot. Editor component for user types is a generic form renderer driven by the `fields` array (no per-type React file). Unblocks the long tail of personal creative shards (wardrobe, vehicle, faction, magic-system, voice-line, prompt-fragment, etc.) without a code change per shard. Decision needed on whether user types federate to peers (probably yes, with the type row riding the catalog sync envelope and gated by `PORTOS_SCHEMA_VERSIONS.catalog`). _Precondition resolved 2026-05-30: `[catalog-type-table-vs-check]` landed as **option (b)** (DB `CHECK` dropped + `type VARCHAR(32)`; validity gated by the `INGREDIENT_TYPES` registry + Zod enum) — so user types do NOT need a `catalog_ingredient_types` table; they can persist in settings and merge into the registry at boot, and a user-typed row already inserts at the DB layer. Still open as a larger Settings-UI + generic-form-renderer feature; remains deferred until picked up deliberately._
+- [ ] [catalog-voice-tools-user-type-filter] **Surface user-defined catalog types to the voice `catalog_search` / `catalog_create` tools.** `server/services/voice/tools.js` still hardcodes `CATALOG_INGREDIENT_TYPES = ['character', 'place', 'object', 'idea', 'scene', 'concept']` (line ~454) for the `type` enum on the catalog voice tools. With `[catalog-user-defined-types]` shipped, a user-defined type is accepted by the create route but a voice "search my factions" can't filter on it — `catalog_search` silently drops an unknown `type` to `undefined` (no crash, just no filter). Make the tool's `type` enum (and the `catalog_create` type validation) derive from `getActiveCatalogTypes()` at `getToolSpecs()` time so user types are voice-addressable. Low priority — nothing throws today; this is a discoverability gap, not a bug.
_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._
diff --git a/client/src/App.jsx b/client/src/App.jsx
index e642116ae5..efa746380d 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -3,6 +3,7 @@ import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Layout from './components/Layout';
import { getSettings, updateSettings } from './services/api';
import BrailleSpinner from './components/BrailleSpinner';
+import { CatalogTypesProvider } from './hooks/useCatalogTypes.jsx';
import Dashboard from './pages/Dashboard';
import Apps from './pages/Apps';
import Ambient from './pages/Ambient';
@@ -152,6 +153,7 @@ function useTimezoneBootstrap() {
export default function App() {
useTimezoneBootstrap();
return (
+ <CatalogTypesProvider>
<Suspense fallback={<PageLoader />}>
<Routes>
<Route path="/ambient" element={<Ambient />} />
@@ -290,5 +292,6 @@ export default function App() {
</Route>
</Routes>
</Suspense>
+ </CatalogTypesProvider>
);
}
diff --git a/client/src/components/GenericIngredientFields.jsx b/client/src/components/GenericIngredientFields.jsx
new file mode 100644
index 0000000000..7cbbf1850e
--- /dev/null
+++ b/client/src/components/GenericIngredientFields.jsx
@@ -0,0 +1,137 @@
+/**
+ * GenericIngredientFields — the detail/edit renderer for USER-DEFINED catalog
+ * ingredient types. System types (character/place/object/idea/scene/concept)
+ * keep their hand-built editor sections in CatalogIngredient.jsx; a user type
+ * has no per-type React file, so this generic renderer maps each declared field
+ * `{ key, label, widget, maxLength? }` to a widget and reads/writes
+ * `payload[key]` through `onChange(key, value)`.
+ *
+ * Widget kinds (derived from the server field `kind` by
+ * `normalizeUserTypeForClient`):
+ * text — single-line <input> (server kind 'string')
+ * textarea — multi-line <textarea> (server kind 'longtext')
+ * tags — tag chip input (reuses TagPicker) (server kind 'tags')
+ * ref — catalog-ingredient id picker (IngredientPicker-backed) ('ref')
+ *
+ * Every field has an htmlFor/id pairing for screen-reader + click-to-focus.
+ */
+
+import { useState } from 'react';
+import { Link2, X } from 'lucide-react';
+import TagPicker from './TagPicker';
+import IngredientPicker from './IngredientPicker';
+
+const sharedInput = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent';
+
+// A single `ref` field — stores a catalog ingredient id in payload[key]. Opens
+// the shared IngredientPicker modal to choose the target.
+function RefField({ fieldKey, label, value, onChange }) {
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const inputId = `ingredient-${fieldKey}`;
+ return (
+ <div>
+ <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>
+ <div className="flex items-center gap-2">
+ <input
+ id={inputId}
+ type="text"
+ readOnly
+ value={value || ''}
+ placeholder="No ingredient linked"
+ onClick={() => setPickerOpen(true)}
+ className={`${sharedInput} cursor-pointer font-mono`}
+ />
+ <button
+ type="button"
+ onClick={() => setPickerOpen(true)}
+ className="inline-flex items-center gap-1 px-3 py-2 rounded border border-port-border text-gray-300 hover:text-white text-sm whitespace-nowrap"
+ >
+ <Link2 size={14} aria-hidden="true" /> {value ? 'Change' : 'Link'}
+ </button>
+ {value ? (
+ <button
+ type="button"
+ onClick={() => onChange(fieldKey, '')}
+ aria-label={`Clear ${label}`}
+ className="inline-flex items-center px-2 py-2 rounded border border-port-border text-gray-400 hover:text-port-error"
+ >
+ <X size={14} aria-hidden="true" />
+ </button>
+ ) : null}
+ </div>
+ <IngredientPicker
+ open={pickerOpen}
+ onClose={() => setPickerOpen(false)}
+ onSelect={(ing) => { onChange(fieldKey, ing?.id || ''); setPickerOpen(false); }}
+ />
+ </div>
+ );
+}
+
+// One generic field, dispatched by widget kind.
+function GenericField({ field, payload, onChange }) {
+ const { key, label, widget, maxLength } = field;
+ const inputId = `ingredient-${key}`;
+ const value = payload?.[key];
+
+ if (widget === 'tags') {
+ const arr = Array.isArray(value) ? value : [];
+ return (
+ <div>
+ <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>
+ <TagPicker id={inputId} value={arr} onChange={(next) => onChange(key, next)} placeholder="Add a value…" />
+ </div>
+ );
+ }
+ if (widget === 'ref') {
+ return <RefField fieldKey={key} label={label} value={typeof value === 'string' ? value : ''} onChange={onChange} />;
+ }
+ if (widget === 'textarea') {
+ return (
+ <div>
+ <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>
+ <textarea
+ id={inputId}
+ rows={3}
+ maxLength={maxLength}
+ value={value ?? ''}
+ onChange={(e) => onChange(key, e.target.value)}
+ className={sharedInput}
+ />
+ </div>
+ );
+ }
+ // default: 'text'
+ return (
+ <div>
+ <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>
+ <input
+ id={inputId}
+ type="text"
+ maxLength={maxLength}
+ value={value ?? ''}
+ onChange={(e) => onChange(key, e.target.value)}
+ className={sharedInput}
+ />
+ </div>
+ );
+}
+
+/**
+ * Render the generic editable fields for a user-defined type.
+ * fields — the type's `editorFields` ({ key, label, widget, maxLength? }).
+ * payload — the ingredient payload object.
+ * onChange — (key, value) => void, writes payload[key].
+ */
+export default function GenericIngredientFields({ fields = [], payload = {}, onChange }) {
+ if (!Array.isArray(fields) || fields.length === 0) {
+ return <p className="text-sm text-gray-500">This type has no fields yet — add some in Settings → Catalog.</p>;
+ }
+ return (
+ <div className="space-y-3">
+ {fields.map((field) => (
+ <GenericField key={field.key} field={field} payload={payload} onChange={onChange} />
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/components/GenericIngredientFields.test.jsx b/client/src/components/GenericIngredientFields.test.jsx
new file mode 100644
index 0000000000..384a0fad62
--- /dev/null
+++ b/client/src/components/GenericIngredientFields.test.jsx
@@ -0,0 +1,63 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+
+// TagPicker + IngredientPicker are exercised elsewhere; stub them to keep this
+// focused on the generic field dispatch + payload read/write.
+vi.mock('./TagPicker', () => ({
+ default: ({ id, value, onChange }) => (
+ <button type="button" data-testid={`tagpicker-${id}`} onClick={() => onChange([...(value || []), 'added'])}>
+ tags:{(value || []).join('|')}
+ </button>
+ ),
+}));
+vi.mock('./IngredientPicker', () => ({
+ default: ({ open, onSelect }) => (open ? (
+ <button type="button" data-testid="ingredientpicker" onClick={() => onSelect({ id: 'cat-chr-99' })}>pick</button>
+ ) : null),
+}));
+
+import GenericIngredientFields from './GenericIngredientFields';
+
+const fields = [
+ { key: 'motto', label: 'Motto', widget: 'text' },
+ { key: 'creed', label: 'Creed', widget: 'textarea' },
+ { key: 'aliases', label: 'Aliases', widget: 'tags' },
+ { key: 'leader', label: 'Leader', widget: 'ref' },
+];
+
+describe('GenericIngredientFields', () => {
+ it('renders a labeled widget per field with htmlFor/id pairing', () => {
+ render(<GenericIngredientFields fields={fields} payload={{}} onChange={() => {}} />);
+ // Label/id pairing — getByLabelText resolves only when wired.
+ expect(screen.getByLabelText('Motto')).toBeTruthy();
+ expect(screen.getByLabelText('Creed').tagName).toBe('TEXTAREA');
+ });
+
+ it('writes payload[key] for text + textarea fields', () => {
+ const onChange = vi.fn();
+ render(<GenericIngredientFields fields={fields} payload={{}} onChange={onChange} />);
+ fireEvent.change(screen.getByLabelText('Motto'), { target: { value: 'unity' } });
+ expect(onChange).toHaveBeenCalledWith('motto', 'unity');
+ });
+
+ it('routes tags through the tag widget', () => {
+ const onChange = vi.fn();
+ render(<GenericIngredientFields fields={fields} payload={{ aliases: ['a'] }} onChange={onChange} />);
+ fireEvent.click(screen.getByTestId('tagpicker-ingredient-aliases'));
+ expect(onChange).toHaveBeenCalledWith('aliases', ['a', 'added']);
+ });
+
+ it('stores a picked ingredient id for a ref field', () => {
+ const onChange = vi.fn();
+ render(<GenericIngredientFields fields={fields} payload={{}} onChange={onChange} />);
+ // Open the picker via the field's Link button, then select.
+ fireEvent.click(screen.getByRole('button', { name: /Link/i }));
+ fireEvent.click(screen.getByTestId('ingredientpicker'));
+ expect(onChange).toHaveBeenCalledWith('leader', 'cat-chr-99');
+ });
+
+ it('shows an empty-state hint when the type has no fields', () => {
+ render(<GenericIngredientFields fields={[]} payload={{}} onChange={() => {}} />);
+ expect(screen.getByText(/no fields yet/i)).toBeTruthy();
+ });
+});
diff --git a/client/src/components/settings/CatalogTypesTab.jsx b/client/src/components/settings/CatalogTypesTab.jsx
new file mode 100644
index 0000000000..4e5b212d92
--- /dev/null
+++ b/client/src/components/settings/CatalogTypesTab.jsx
@@ -0,0 +1,275 @@
+import { useState } from 'react';
+import { Sparkles, Plus, Trash2, Save, X, Loader2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import { createCatalogType, updateCatalogType, deleteCatalogType } from '../../services/apiCatalogTypes';
+import { useCatalogTypes } from '../../hooks/useCatalogTypes.jsx';
+import { USER_TYPE_FIELD_KINDS } from '../../lib/catalogTypes';
+
+/**
+ * Settings → Catalog tab. Lists the built-in (system) ingredient types
+ * read-only and lets the user define their own custom types — each with a flat
+ * list of typed fields the generic editor renders. Definitions persist in
+ * settings.json server-side (via the /api/catalog/types routes) and federate to
+ * peers; the local registry refreshes immediately on save.
+ *
+ * There is NO per-type React file — a user type is purely data: an id, a label,
+ * a primary content key, and a list of { key, label, kind } fields.
+ */
+
+const KIND_LABELS = { string: 'Short text', longtext: 'Long text', tags: 'Tags', ref: 'Ingredient link' };
+const slugify = (s) => String(s || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32);
+
+const emptyDraft = () => ({ id: '', label: '', primaryContentKey: '', fields: [] });
+
+export function CatalogTypesTab() {
+ const { types, refresh, loading } = useCatalogTypes();
+ const systemTypes = types.filter((t) => t.system !== false);
+ const userTypes = types.filter((t) => t.system === false);
+
+ // `editing` is null (none), 'new' (add form), or a user-type id (edit form).
+ const [editing, setEditing] = useState(null);
+ const [draft, setDraft] = useState(emptyDraft());
+ const [busy, setBusy] = useState(false);
+ const [armedDeleteId, setArmedDeleteId] = useState(null);
+
+ const startNew = () => { setDraft(emptyDraft()); setEditing('new'); };
+ const startEdit = (t) => {
+ setDraft({
+ id: t.id,
+ label: t.label,
+ primaryContentKey: t.primaryContentKey || '',
+ fields: (t.editorFields || []).map((f) => ({
+ key: f.key,
+ label: f.label,
+ // editorFields carry the widget kind; map back to the server field kind.
+ kind: f.widget === 'textarea' ? 'longtext' : f.widget === 'text' ? 'string' : f.widget,
+ })),
+ });
+ setEditing(t.id);
+ };
+ const cancel = () => { setEditing(null); setDraft(emptyDraft()); };
+
+ const addField = () => setDraft((d) => ({ ...d, fields: [...d.fields, { key: '', label: '', kind: 'string' }] }));
+ const updateField = (i, patch) => setDraft((d) => ({
+ ...d,
+ fields: d.fields.map((f, idx) => (idx === i ? { ...f, ...patch } : f)),
+ }));
+ const removeField = (i) => setDraft((d) => ({ ...d, fields: d.fields.filter((_, idx) => idx !== i) }));
+
+ const save = async () => {
+ const id = editing === 'new' ? slugify(draft.id || draft.label) : draft.id;
+ const label = draft.label.trim();
+ if (!id || !label) { toast.error('Type needs an id and a label'); return; }
+ const fields = draft.fields
+ .map((f) => ({ key: slugify(f.key || f.label).replace(/-/g, '_'), label: (f.label || f.key).trim(), kind: f.kind }))
+ .filter((f) => f.key && f.label);
+ const primaryContentKey = draft.primaryContentKey || fields[0]?.key || 'description';
+ const body = { id, label, primaryContentKey, fields };
+ setBusy(true);
+ const action = editing === 'new'
+ ? createCatalogType(body, { silent: true })
+ : updateCatalogType(id, body, { silent: true });
+ const ok = await action.then(() => true).catch((err) => {
+ toast.error(err?.message || 'Failed to save type');
+ return false;
+ });
+ setBusy(false);
+ if (!ok) return;
+ toast.success(`Saved type "${label}"`);
+ cancel();
+ refresh();
+ };
+
+ const confirmDelete = async (id, { force = false } = {}) => {
+ setBusy(true);
+ const ok = await deleteCatalogType(id, { force, silent: true })
+ .then(() => true)
+ .catch((err) => {
+ // 409 with the in-use code → offer a forced delete inline.
+ if (err?.code === 'CATALOG_TYPE_IN_USE' || /force=true/.test(err?.message || '')) {
+ toast.error('Type has ingredients — confirm again to delete anyway');
+ setArmedDeleteId(`force:${id}`);
+ } else {
+ toast.error(err?.message || 'Failed to delete type');
+ }
+ return false;
+ });
+ setBusy(false);
+ if (!ok) return;
+ toast.success('Type deleted');
+ setArmedDeleteId(null);
+ refresh();
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <div className="flex items-center justify-between gap-3 mb-2">
+ <div className="flex items-center gap-2">
+ <Sparkles size={16} className="text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Catalog types</h3>
+ </div>
+ {editing === null && (
+ <button type="button" onClick={startNew}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium">
+ <Plus size={14} aria-hidden="true" /> New type
+ </button>
+ )}
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ Define custom ingredient types for the Catalog. Built-in types are read-only;
+ your custom types federate to your other machines.
+ </p>
+
+ {loading && <p className="text-sm text-gray-500">Loading types…</p>}
+
+ {/* Built-in (system) types — read-only */}
+ <div className="mb-5">
+ <h4 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Built-in</h4>
+ <div className="flex flex-wrap gap-2">
+ {systemTypes.map((t) => (
+ <span key={t.id} className={`inline-block text-[11px] px-2 py-1 rounded border ${t.badgeColor}`}>
+ {t.label}
+ </span>
+ ))}
+ </div>
+ </div>
+
+ {/* User types */}
+ <div>
+ <h4 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Your types</h4>
+ {userTypes.length === 0 && editing !== 'new' && (
+ <p className="text-sm text-gray-500">No custom types yet.</p>
+ )}
+ <div className="space-y-2">
+ {userTypes.map((t) => (
+ <div key={t.id} className="flex items-center justify-between gap-3 p-3 bg-port-bg border border-port-border rounded">
+ <div className="min-w-0">
+ <div className="text-white text-sm font-medium truncate">{t.label}</div>
+ <div className="text-xs text-gray-500 font-mono">{t.id} · {(t.editorFields || []).length} field(s)</div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button type="button" onClick={() => startEdit(t)} disabled={editing !== null}
+ className="px-2 py-1.5 rounded border border-port-border text-gray-300 hover:text-white text-sm disabled:opacity-40">
+ Edit
+ </button>
+ {armedDeleteId === t.id || armedDeleteId === `force:${t.id}` ? (
+ <span className="inline-flex items-center gap-1">
+ <button type="button" disabled={busy}
+ onClick={() => confirmDelete(t.id, { force: armedDeleteId === `force:${t.id}` })}
+ className="inline-flex items-center gap-1 px-2 py-1.5 rounded bg-port-error/20 text-port-error hover:bg-port-error/30 text-sm">
+ {busy ? <Loader2 size={13} className="animate-spin" /> : <Trash2 size={13} />} Confirm
+ </button>
+ <button type="button" onClick={() => setArmedDeleteId(null)}
+ className="px-2 py-1.5 rounded text-gray-400 hover:text-white text-sm">Cancel</button>
+ </span>
+ ) : (
+ <button type="button" onClick={() => setArmedDeleteId(t.id)} disabled={editing !== null}
+ aria-label={`Delete ${t.label}`}
+ className="px-2 py-1.5 rounded border border-port-border text-gray-400 hover:text-port-error text-sm disabled:opacity-40">
+ <Trash2 size={13} />
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Add / edit field-builder */}
+ {editing !== null && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
+ <h3 className="text-lg font-semibold text-white">{editing === 'new' ? 'New type' : `Edit "${draft.label || draft.id}"`}</h3>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label htmlFor="catalog-type-label" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Label</label>
+ <input id="catalog-type-label" type="text" value={draft.label} maxLength={80}
+ onChange={(e) => setDraft((d) => ({ ...d, label: e.target.value }))}
+ placeholder="e.g. Faction"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm" />
+ </div>
+ <div>
+ <label htmlFor="catalog-type-id" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Id {editing !== 'new' && <span className="normal-case text-gray-600">(immutable)</span>}
+ </label>
+ <input id="catalog-type-id" type="text"
+ value={editing === 'new' ? draft.id : draft.id}
+ disabled={editing !== 'new'} maxLength={32}
+ onChange={(e) => setDraft((d) => ({ ...d, id: e.target.value }))}
+ placeholder="auto from label"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono disabled:opacity-50" />
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs uppercase tracking-wider text-gray-500">Fields</span>
+ <button type="button" onClick={addField}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white text-xs">
+ <Plus size={12} /> Add field
+ </button>
+ </div>
+ {draft.fields.length === 0 && <p className="text-sm text-gray-500">No fields — add at least one.</p>}
+ <div className="space-y-2">
+ {draft.fields.map((f, i) => (
+ <div key={i} className="grid grid-cols-1 sm:grid-cols-[1fr_1fr_160px_auto] gap-2 items-end">
+ <div>
+ <label htmlFor={`field-label-${i}`} className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Field label</label>
+ <input id={`field-label-${i}`} type="text" value={f.label} maxLength={80}
+ onChange={(e) => updateField(i, { label: e.target.value })}
+ placeholder="e.g. Headquarters"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />
+ </div>
+ <div>
+ <label htmlFor={`field-key-${i}`} className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Key</label>
+ <input id={`field-key-${i}`} type="text" value={f.key} maxLength={64}
+ onChange={(e) => updateField(i, { key: e.target.value })}
+ placeholder="auto from label"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm font-mono" />
+ </div>
+ <div>
+ <label htmlFor={`field-kind-${i}`} className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Kind</label>
+ <select id={`field-kind-${i}`} value={f.kind}
+ onChange={(e) => updateField(i, { kind: e.target.value })}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm">
+ {USER_TYPE_FIELD_KINDS.map((k) => <option key={k} value={k}>{KIND_LABELS[k] || k}</option>)}
+ </select>
+ </div>
+ <button type="button" onClick={() => removeField(i)} aria-label="Remove field"
+ className="px-2 py-1.5 rounded border border-port-border text-gray-400 hover:text-port-error">
+ <X size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <label htmlFor="catalog-type-primary" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Primary content field <span className="normal-case text-gray-600">(the body shown in the quick-create form)</span>
+ </label>
+ <select id="catalog-type-primary" value={draft.primaryContentKey}
+ onChange={(e) => setDraft((d) => ({ ...d, primaryContentKey: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm">
+ <option value="">(first field)</option>
+ {draft.fields.filter((f) => f.key || f.label).map((f, i) => (
+ <option key={i} value={slugify(f.key || f.label).replace(/-/g, '_')}>{f.label || f.key}</option>
+ ))}
+ </select>
+ </div>
+
+ <div className="flex justify-end gap-2">
+ <button type="button" onClick={cancel} className="px-3 py-2 rounded-lg text-gray-400 hover:text-white text-sm">Cancel</button>
+ <button type="button" onClick={save} disabled={busy}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white text-sm font-medium">
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} Save type
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default CatalogTypesTab;
diff --git a/client/src/components/settings/CatalogTypesTab.test.jsx b/client/src/components/settings/CatalogTypesTab.test.jsx
new file mode 100644
index 0000000000..4b637a614a
--- /dev/null
+++ b/client/src/components/settings/CatalogTypesTab.test.jsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+
+vi.mock('../../services/apiCatalogTypes', () => ({
+ listCatalogTypes: vi.fn(),
+ createCatalogType: vi.fn(),
+ updateCatalogType: vi.fn(),
+ deleteCatalogType: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+import { CatalogTypesTab } from './CatalogTypesTab';
+import { CatalogTypesProvider } from '../../hooks/useCatalogTypes.jsx';
+import { listCatalogTypes, createCatalogType, deleteCatalogType } from '../../services/apiCatalogTypes';
+import toast from '../ui/Toast';
+
+const renderTab = () => render(
+ <CatalogTypesProvider>
+ <CatalogTypesTab />
+ </CatalogTypesProvider>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listCatalogTypes.mockResolvedValue({ types: [] });
+});
+
+describe('CatalogTypesTab', () => {
+ it('lists built-in types read-only', async () => {
+ renderTab();
+ await waitFor(() => expect(screen.getByText('Built-in')).toBeTruthy());
+ expect(screen.getByText('Character')).toBeTruthy();
+ expect(screen.getByText('Concept')).toBeTruthy();
+ });
+
+ it('creates a user type through the field builder', async () => {
+ createCatalogType.mockResolvedValue({ types: [] });
+ renderTab();
+ await waitFor(() => expect(screen.getByText('Built-in')).toBeTruthy());
+
+ fireEvent.click(screen.getByRole('button', { name: /New type/i }));
+ fireEvent.change(screen.getByLabelText('Label'), { target: { value: 'Faction' } });
+ fireEvent.click(screen.getByRole('button', { name: /Add field/i }));
+ fireEvent.change(screen.getByLabelText('Field label'), { target: { value: 'Creed' } });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Save type/i }));
+ });
+
+ expect(createCatalogType).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'faction',
+ label: 'Faction',
+ fields: [expect.objectContaining({ key: 'creed', label: 'Creed' })],
+ }),
+ { silent: true },
+ );
+ expect(toast.success).toHaveBeenCalled();
+ });
+
+ it('arms then deletes a user type', async () => {
+ listCatalogTypes.mockResolvedValue({
+ types: [{ id: 'faction', label: 'Faction', system: false, primaryContentKey: 'creed', fields: [{ key: 'creed', label: 'Creed', kind: 'longtext' }] }],
+ });
+ deleteCatalogType.mockResolvedValue({ types: [] });
+ renderTab();
+ await waitFor(() => expect(screen.getByText('Faction')).toBeTruthy());
+
+ fireEvent.click(screen.getByLabelText(/Delete Faction/i));
+ const confirm = await screen.findByRole('button', { name: /Confirm/i });
+ await act(async () => { fireEvent.click(confirm); });
+
+ expect(deleteCatalogType).toHaveBeenCalledWith('faction', { force: false, silent: true });
+ });
+
+ it('surfaces the in-use guard and offers a forced delete', async () => {
+ listCatalogTypes.mockResolvedValue({
+ types: [{ id: 'faction', label: 'Faction', system: false, primaryContentKey: 'creed', fields: [] }],
+ });
+ const inUse = Object.assign(new Error('Catalog type "faction" has ingredients — pass ?force=true to delete it anyway'), { code: 'CATALOG_TYPE_IN_USE' });
+ deleteCatalogType.mockRejectedValueOnce(inUse).mockResolvedValueOnce({ types: [] });
+ renderTab();
+ await waitFor(() => expect(screen.getByText('Faction')).toBeTruthy());
+
+ fireEvent.click(screen.getByLabelText(/Delete Faction/i));
+ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /Confirm/i })); });
+ // First attempt was refused (non-force).
+ expect(deleteCatalogType).toHaveBeenLastCalledWith('faction', { force: false, silent: true });
+ expect(toast.error).toHaveBeenCalled();
+
+ // Confirm again → forced delete.
+ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /Confirm/i })); });
+ expect(deleteCatalogType).toHaveBeenLastCalledWith('faction', { force: true, silent: true });
+ });
+});
diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsx
index 8c84bcbae1..0c2b57e086 100644
--- a/client/src/components/settings/SettingsTabsHeader.jsx
+++ b/client/src/components/settings/SettingsTabsHeader.jsx
@@ -12,6 +12,7 @@ import TabPills from '../ui/TabPills';
const TABS = [
{ id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },
{ id: 'backup', label: 'Backup', to: '/settings/backup' },
+ { id: 'catalog', label: 'Catalog', to: '/settings/catalog' },
{ id: 'database', label: 'Database', to: '/settings/database' },
{ id: 'embeddings', label: 'Embeddings', to: '/settings/embeddings' },
{ id: 'general', label: 'General', to: '/settings/general' },
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b46746f5e3..b07ed30272 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -98,6 +98,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCityData` | CyberCity environment data + physics. | CyberCity only. |
| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
+| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
| `useNextEvalCountdown` | 1-second countdown to the next CoS evaluation tick. | Chief of Staff "next eval in Xs" displays. |
| `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 6cc25bcdd9..a3bfb18216 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -56,6 +56,8 @@ export * from './useOpenClawAttachments.js';
// === Settings-derived shared state ===
export * from './useCodeReviewDefaults.jsx';
+export { default as useCatalogTypes } from './useCatalogTypes.jsx';
+export * from './useCatalogTypes.jsx';
// === Sockets & lifecycle ===
export * from './usePrevious.js';
diff --git a/client/src/hooks/useCatalogTypes.jsx b/client/src/hooks/useCatalogTypes.jsx
new file mode 100644
index 0000000000..e6e43a85f0
--- /dev/null
+++ b/client/src/hooks/useCatalogTypes.jsx
@@ -0,0 +1,79 @@
+import { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
+import { listCatalogTypes } from '../services/apiCatalogTypes';
+import { CATALOG_TYPES, mergeCatalogTypes } from '../lib/catalogTypes';
+
+/**
+ * Catalog type registry hook + context.
+ *
+ * Fetches `GET /api/catalog/types` once (the FULL active registry — system +
+ * user-defined) and merges it with the static `CATALOG_TYPES` fallback so the
+ * Catalog list / picker / editor pick up user-defined types. The static
+ * registry is the SYNCHRONOUS fallback: first render (before the fetch
+ * resolves) returns the built-in six so the UI never blanks.
+ *
+ * Exposed:
+ * types — ordered merged list ({ id, label, badgeColor, primaryContentKey,
+ * primaryContentLabel, snippetFallbackKeys, editorFields?, system })
+ * getType — (id) => type | undefined
+ * ids — ordered id list
+ * loading — true until the first fetch resolves (fallback is live meanwhile)
+ * refresh — re-fetch (call after a Settings → Catalog mutation)
+ */
+
+const CatalogTypesContext = createContext(null);
+
+// Build the merged registry from a raw server array (or [] for fallback). The
+// server returns system + user entries; mergeCatalogTypes drops the system
+// ones (already in the static fallback) and normalizes the rest.
+const buildRegistry = (userTypesRaw) => mergeCatalogTypes(CATALOG_TYPES, userTypesRaw);
+
+// Shared fetch-and-merge state machine used by BOTH the Provider and the
+// standalone (provider-less) fallback. `enabled` gates the fetch effect so the
+// standalone path can stay dormant when a context is present. Synchronous
+// fallback to the static system registry so first render never blanks.
+function useRegistryFetcher(enabled = true) {
+ const [registry, setRegistry] = useState(() => buildRegistry([]));
+ const [loading, setLoading] = useState(true);
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+
+ const refresh = useCallback(() => listCatalogTypes({ silent: true })
+ .then((data) => {
+ if (!mountedRef.current) return;
+ const serverTypes = Array.isArray(data?.types) ? data.types : [];
+ setRegistry(buildRegistry(serverTypes.filter((t) => t && t.system === false)));
+ setLoading(false);
+ })
+ // Network/route failure → keep the static fallback; stop the spinner.
+ .catch(() => { if (mountedRef.current) setLoading(false); }), []);
+
+ useEffect(() => { if (enabled) refresh(); }, [enabled, refresh]);
+
+ return useMemo(() => ({
+ types: registry.list,
+ getType: (id) => registry.byId[id],
+ ids: registry.list.map((t) => t.id),
+ loading,
+ refresh,
+ }), [registry, loading, refresh]);
+}
+
+export function CatalogTypesProvider({ children }) {
+ const value = useRegistryFetcher(true);
+ return <CatalogTypesContext.Provider value={value}>{children}</CatalogTypesContext.Provider>;
+}
+
+/**
+ * Read the catalog type registry. When used outside a `CatalogTypesProvider`
+ * (e.g. a test that doesn't mount the provider) it falls back to a standalone
+ * fetch-and-merge so the hook is still usable in isolation.
+ */
+export function useCatalogTypes() {
+ const ctx = useContext(CatalogTypesContext);
+ // Hooks must run unconditionally — run the standalone fetcher but keep it
+ // dormant (no fetch) when a context already provides the registry.
+ const standalone = useRegistryFetcher(!ctx);
+ return ctx || standalone;
+}
+
+export default useCatalogTypes;
diff --git a/client/src/hooks/useCatalogTypes.test.jsx b/client/src/hooks/useCatalogTypes.test.jsx
new file mode 100644
index 0000000000..3b39676738
--- /dev/null
+++ b/client/src/hooks/useCatalogTypes.test.jsx
@@ -0,0 +1,58 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../services/apiCatalogTypes', () => ({
+ listCatalogTypes: vi.fn(),
+}));
+
+import { CatalogTypesProvider, useCatalogTypes } from './useCatalogTypes.jsx';
+import { listCatalogTypes } from '../services/apiCatalogTypes';
+
+// Tiny consumer that renders the hook output for assertions.
+function Probe() {
+ const { types, getType, ids, loading } = useCatalogTypes();
+ return (
+ <div>
+ <span data-testid="loading">{String(loading)}</span>
+ <span data-testid="ids">{ids.join(',')}</span>
+ <span data-testid="faction-label">{getType('faction')?.label || ''}</span>
+ <span data-testid="count">{types.length}</span>
+ </div>
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('useCatalogTypes', () => {
+ it('returns the static system fallback synchronously on first render', () => {
+ // Never resolves — first render must still show the built-in six.
+ listCatalogTypes.mockReturnValue(new Promise(() => {}));
+ render(<CatalogTypesProvider><Probe /></CatalogTypesProvider>);
+ expect(screen.getByTestId('ids').textContent).toBe('character,place,object,idea,scene,concept');
+ expect(screen.getByTestId('loading').textContent).toBe('true');
+ });
+
+ it('merges a user type from the server after the fetch resolves', async () => {
+ listCatalogTypes.mockResolvedValue({
+ types: [
+ { id: 'character', label: 'Character', system: true },
+ { id: 'faction', label: 'Faction', system: false, primaryContentKey: 'creed', fields: [{ key: 'creed', label: 'Creed', kind: 'longtext' }] },
+ ],
+ });
+ render(<CatalogTypesProvider><Probe /></CatalogTypesProvider>);
+ await waitFor(() => expect(screen.getByTestId('faction-label').textContent).toBe('Faction'));
+ // System types come first; the user type is appended (7 total).
+ expect(screen.getByTestId('count').textContent).toBe('7');
+ expect(screen.getByTestId('ids').textContent.endsWith(',faction')).toBe(true);
+ expect(screen.getByTestId('loading').textContent).toBe('false');
+ });
+
+ it('keeps the static fallback when the fetch fails', async () => {
+ listCatalogTypes.mockRejectedValue(new Error('offline'));
+ render(<CatalogTypesProvider><Probe /></CatalogTypesProvider>);
+ await waitFor(() => expect(screen.getByTestId('loading').textContent).toBe('false'));
+ expect(screen.getByTestId('count').textContent).toBe('6');
+ });
+});
diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.js
index bde37d7c64..1d43bda509 100644
--- a/client/src/lib/catalogTypes.js
+++ b/client/src/lib/catalogTypes.js
@@ -327,3 +327,80 @@ const UNION_SNIPPET_KEYS = (() => {
}
return out;
})();
+
+// --- User-defined types (client mirror) ----------------------------------
+// User types are defined in Settings → Catalog, persisted server-side in
+// settings.json, and served (merged with the system registry) via
+// `GET /api/catalog/types`. The `useCatalogTypes` hook fetches them and merges
+// with the static `CATALOG_TYPES` above so the Catalog list/picker/editor pick
+// them up. The static registry stays the synchronous fallback so first render
+// never blanks.
+
+/** Field kinds a user type may declare — mirror of the server constant. */
+export const USER_TYPE_FIELD_KINDS = Object.freeze(['string', 'longtext', 'tags', 'ref']);
+
+// Map a server field `kind` to the client editor widget kind. `string` → a
+// single-line input ('text'), `longtext` → a textarea, `tags`/`ref` keep their
+// names (the generic renderer special-cases them). Unknown kinds fall back to
+// 'text' so a forked-peer field never crashes the renderer.
+const FIELD_KIND_TO_WIDGET = { string: 'text', longtext: 'textarea', tags: 'tags', ref: 'ref' };
+
+/**
+ * Normalize a server-served user type (system:false) into the client registry
+ * shape the UI consumes — the same surface a static `CATALOG_TYPES` entry
+ * exposes, plus `system: false` and a generic `editorFields` list derived from
+ * the server `fields`. Returns `null` for a structurally-invalid entry.
+ */
+export function normalizeUserTypeForClient(raw) {
+ if (!raw || typeof raw !== 'object' || typeof raw.id !== 'string') return null;
+ const fields = Array.isArray(raw.fields) ? raw.fields : [];
+ const editorFields = fields
+ .filter((f) => f && typeof f.key === 'string')
+ .map((f) => ({
+ key: f.key,
+ label: typeof f.label === 'string' && f.label ? f.label : f.key,
+ widget: FIELD_KIND_TO_WIDGET[f.kind] || 'text',
+ ...(Number.isInteger(f.maxLength) ? { maxLength: f.maxLength } : {}),
+ }));
+ return {
+ id: raw.id,
+ label: typeof raw.label === 'string' && raw.label ? raw.label : raw.id,
+ badgeColor: raw.badgeColor || 'bg-gray-500/20 text-gray-300 border-gray-500/40',
+ primaryContentKey: raw.primaryContentKey || 'description',
+ primaryContentLabel: raw.primaryContentLabel
+ || editorFields.find((f) => f.key === raw.primaryContentKey)?.label
+ || 'Description',
+ snippetFallbackKeys: Array.isArray(raw.snippetFallbackKeys) && raw.snippetFallbackKeys.length
+ ? raw.snippetFallbackKeys
+ : [raw.primaryContentKey || 'description'],
+ editorFields,
+ system: false,
+ };
+}
+
+/**
+ * Merge the static system registry with normalized user types into an ordered
+ * list (system first) + a BY_ID lookup. `userTypes` is the raw server array
+ * (system entries are dropped — they're already in `staticTypes`); each user
+ * entry is normalized. A user id colliding with a system id is skipped (system
+ * wins). Returns `{ list, byId }`.
+ */
+export function mergeCatalogTypes(staticTypes = CATALOG_TYPES, userTypes = []) {
+ const list = staticTypes.map((t) => ({ ...t, system: true }));
+ const systemIds = new Set(staticTypes.map((t) => t.id));
+ const seen = new Set(systemIds);
+ for (const raw of Array.isArray(userTypes) ? userTypes : []) {
+ if (raw?.system) continue; // server may include system entries; skip — already present
+ const normalized = normalizeUserTypeForClient(raw);
+ if (!normalized || seen.has(normalized.id)) continue;
+ seen.add(normalized.id);
+ list.push(normalized);
+ }
+ const byId = Object.fromEntries(list.map((t) => [t.id, t]));
+ return { list, byId };
+}
+
+/** Look up a type by id from a merged `byId` map (from `mergeCatalogTypes`). */
+export function getCatalogTypeFrom(byId, id) {
+ return byId?.[id];
+}
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index 924dd24a27..6a40602bca 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -18,15 +18,16 @@ import {
deleteCatalogIngredient,
getCatalogStats,
} from '../services/apiCatalog';
-import { CATALOG_TYPES, getCatalogType, payloadSnippet } from '../lib/catalogTypes';
+import { payloadSnippet } from '../lib/catalogTypes';
+import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
// All type-derived UI (chips, badge color, inline-form primary content
-// key/label, snippet fallback) now flows from the shared registry. Adding a
-// type is one registry entry — no per-surface edit here.
-const TYPES = CATALOG_TYPES;
+// key/label, snippet fallback) flows from the merged registry (system +
+// user-defined). The static built-ins are the synchronous fallback inside the
+// hook, so adding a type — built-in or user — surfaces here automatically.
-function TypeBadge({ type }) {
- const meta = getCatalogType(type);
+function TypeBadge({ type, getType }) {
+ const meta = getType(type);
if (!meta) return null;
return (
<span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${meta.badgeColor}`}>
@@ -36,6 +37,9 @@ function TypeBadge({ type }) {
}
export default function Catalog() {
+ // Merged type registry (system + user-defined). `types` drives the filter
+ // chips + the New-form dropdown; `getType` resolves badge/primary-content.
+ const { types: TYPES, getType } = useCatalogTypes();
const [items, setItems] = useState([]);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
@@ -100,7 +104,7 @@ export default function Catalog() {
const content = form.content.trim();
const payload = {};
if (content) {
- payload[getCatalogType(form.type)?.primaryContentKey || 'description'] = content;
+ payload[getType(form.type)?.primaryContentKey || 'description'] = content;
}
setCreating(true);
const created = await createCatalogIngredient({
@@ -262,7 +266,7 @@ export default function Catalog() {
</div>
<div>
<label htmlFor="catalog-new-content" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
- {getCatalogType(form.type)?.primaryContentLabel || 'Description'}
+ {getType(form.type)?.primaryContentLabel || 'Description'}
<span className="normal-case text-gray-500"> (optional)</span>
</label>
<textarea
@@ -321,7 +325,7 @@ export default function Catalog() {
>
<span className="block text-white font-medium truncate">{name}</span>
<span className="flex items-center gap-1.5 flex-wrap">
- <TypeBadge type={it.type} />
+ <TypeBadge type={it.type} getType={getType} />
{(it.tags || []).slice(0, 4).map((tag) => (
<span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">
{tag}
diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsx
index 57ea8c6794..b1c0631c73 100644
--- a/client/src/pages/Catalog.test.jsx
+++ b/client/src/pages/Catalog.test.jsx
@@ -13,6 +13,12 @@ vi.mock('../components/ui/Toast', () => ({
default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
+// useCatalogTypes (via Catalog) fetches the type registry — mock the API so a
+// user-defined type surfaces as a filter chip + dropdown option.
+vi.mock('../services/apiCatalogTypes', () => ({
+ listCatalogTypes: vi.fn(),
+}));
+
import Catalog from './Catalog';
import {
listCatalogIngredients,
@@ -20,6 +26,7 @@ import {
deleteCatalogIngredient,
getCatalogStats,
} from '../services/apiCatalog';
+import { listCatalogTypes } from '../services/apiCatalogTypes';
import toast from '../components/ui/Toast';
const sample = [
@@ -37,6 +44,8 @@ beforeEach(() => {
vi.clearAllMocks();
listCatalogIngredients.mockResolvedValue({ items: sample });
getCatalogStats.mockResolvedValue({ total: 2, byType: { character: 1, place: 1 } });
+ // Default: system registry only (the hook merges with the static fallback).
+ listCatalogTypes.mockResolvedValue({ types: [] });
});
describe('Catalog page', () => {
@@ -148,4 +157,14 @@ describe('Catalog page', () => {
renderCatalog();
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('load failed'));
});
+
+ it('renders a user-defined type as a filter chip from the merged registry', async () => {
+ listCatalogTypes.mockResolvedValue({
+ types: [{ id: 'faction', label: 'Faction', system: false, badgeColor: 'bg-gray-500/20 text-gray-300 border-gray-500/40', primaryContentKey: 'creed', primaryContentLabel: 'Creed', snippetFallbackKeys: ['creed'], fields: [] }],
+ });
+ renderCatalog();
+ // The built-in chips render synchronously; the user chip appears after the
+ // type-registry fetch resolves.
+ await waitFor(() => expect(screen.getByRole('button', { name: /^Faction/i })).toBeTruthy());
+ });
});
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 4d17b9de5f..20d86a59a7 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -27,7 +27,9 @@ import { listImageGallery } from '../services/apiImageVideo';
import IngredientPicker from '../components/IngredientPicker';
import MediaImage from '../components/MediaImage';
import TagPicker from '../components/TagPicker';
+import GenericIngredientFields from '../components/GenericIngredientFields';
import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind, CHARACTER_LIST_FIELDS } from '../lib/catalogTypes';
+import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import { timeAgo } from '../utils/formatters';
// Per-type editor field list + badge color now come from the shared registry
@@ -59,6 +61,9 @@ function REFKIND_LABEL(kind) {
export default function CatalogIngredient() {
const { id } = useParams();
const navigate = useNavigate();
+ // 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();
const [record, setRecord] = useState(null);
const [loading, setLoading] = useState(true);
const [name, setName] = useState('');
@@ -273,12 +278,19 @@ export default function CatalogIngredient() {
);
}
- const typeDef = getCatalogType(record.type) || getCatalogType('idea');
+ // Resolve from the merged registry (system + user types) so a user-typed
+ // ingredient picks up its declared fields; fall back to the static 'idea'
+ // editor for an unknown/orphaned type.
+ const typeDef = getMergedType(record.type) || getCatalogType(record.type) || getCatalogType('idea');
const fields = typeDef.editorFields || getCatalogType('idea').editorFields;
// Grouped "character sheet" sections for the rich canon types
// (character/place/object); light types (idea/scene/concept) have none and
// fall back to the flat field list below.
const sections = typeDef.editorSections || null;
+ // A user-defined type has no hardcoded editor sections and carries
+ // generically-shaped editorFields ({ key, label, widget }); render the
+ // generic field renderer for it. System types keep their existing branches.
+ const isUserType = typeDef.system === false;
const badgeClass = CATALOG_BADGE_BY_ID[record.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
// Group refs by kind for the "Appears in" panel. Tolerates either an array
@@ -357,7 +369,9 @@ export default function CatalogIngredient() {
<TagPicker id="ingredient-tags" value={tags} onChange={setTags}
placeholder="mentor, antagonist, season-1" />
</div>
- {sections
+ {isUserType
+ ? <GenericIngredientFields fields={fields} payload={payload} onChange={updatePayload} />
+ : sections
? sections.map((section) => (
<SheetSection key={section.title} title={section.title}
fields={section.fields} payload={payload} onChange={updatePayload} />
@@ -910,7 +924,10 @@ function diffRevisionAgainstCurrent(revision, current, fields) {
}
const curPayload = current?.payload || {};
const revPayload = revision.payload || {};
- for (const [key, label] of fields.map(([k, l]) => [k, l])) {
+ // `fields` is either the system tuple form `[key, label, kind]` or the
+ // user-type object form `{ key, label, widget }` — normalize to [key, label].
+ const fieldPairs = (fields || []).map((f) => (Array.isArray(f) ? [f[0], f[1]] : [f.key, f.label]));
+ for (const [key, label] of fieldPairs) {
const from = revPayload[key] ?? '';
const to = curPayload[key] ?? '';
if (String(from) !== String(to)) out.push({ key, label, from: String(from), to: String(to) });
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index 47cf7f243f..b1f4c7b047 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -1,6 +1,7 @@
import { useParams, Navigate } from 'react-router-dom';
import { AutofixerTab } from '../components/settings/AutofixerTab';
import { BackupTab } from '../components/settings/BackupTab';
+import { CatalogTypesTab } from '../components/settings/CatalogTypesTab';
import { DatabaseTab } from '../components/settings/DatabaseTab';
import EmbeddingsTab from '../components/settings/EmbeddingsTab';
import { LocalLlmTab } from '../components/settings/LocalLlmTab';
@@ -31,6 +32,7 @@ export default function Settings() {
case 'general': return <GeneralTab />;
case 'autofixer': return <AutofixerTab />;
case 'backup': return <BackupTab />;
+ case 'catalog': return <CatalogTypesTab />;
case 'database': return <DatabaseTab />;
case 'embeddings': return <EmbeddingsTab />;
case 'local-llm': return <LocalLlmTab />;
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 1a33457c27..b0952f8d9c 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -51,6 +51,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiReferenceRepos.js` | Per-app reference-repo registry. |
| `apiReview.js` | Review hub. |
| `apiCodeReview.js` | Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model). |
+| `apiCatalogTypes.js` | User-defined catalog ingredient types (list active registry + create/update/delete user types). |
| `apiRuns.js` | Agent run history. |
| `apiScaffold.js` | App scaffolding templates. |
| `apiSchedules.js` | Automation schedules. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 57eeffcaaa..0cc8699794 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -14,6 +14,7 @@ export * from './apiHistory.js';
export * from './apiCommands.js';
export * from './apiGit.js';
export * from './apiCatalog.js';
+export * from './apiCatalogTypes.js';
export * from './apiMedia.js';
export * from './apiAgents.js';
export * from './apiPersonalities.js';
diff --git a/client/src/services/apiCatalogTypes.js b/client/src/services/apiCatalogTypes.js
new file mode 100644
index 0000000000..ba837ebb30
--- /dev/null
+++ b/client/src/services/apiCatalogTypes.js
@@ -0,0 +1,29 @@
+import { request } from './apiCore.js';
+
+// User-defined catalog ingredient TYPE API surface. Mirrors apiCatalog.js
+// style — every helper takes an optional `options` second arg so a caller with
+// its own `.catch` toast can pass `{ silent: true }` (avoids the double-toast
+// the shared `request` helper would otherwise produce).
+//
+// GET /types returns the FULL active registry (system + user) so the client can
+// merge it with the static fallback registry. The mutating routes persist
+// through settings.json server-side and return the refreshed active registry.
+
+const enc = encodeURIComponent;
+
+// List the active type registry (system + user-defined). Returns { types }.
+export const listCatalogTypes = (options) => request('/catalog/types', options);
+
+// Create a user-defined type. `body` is { id, label, primaryContentKey, fields }.
+export const createCatalogType = (body = {}, options) =>
+ request('/catalog/types', { method: 'POST', body: JSON.stringify(body), ...options });
+
+// Update a user-defined type (id is immutable; the path id wins).
+export const updateCatalogType = (id, body = {}, options) =>
+ request(`/catalog/types/${enc(id)}`, { method: 'PATCH', body: JSON.stringify(body), ...options });
+
+// Delete a user-defined type. Pass `{ force: true }` to delete a type that
+// still has ingredients (otherwise the server refuses with a 409). The orphaned
+// rows survive and render under the fallback editor.
+export const deleteCatalogType = (id, { force = false, ...options } = {}) =>
+ request(`/catalog/types/${enc(id)}${force ? '?force=true' : ''}`, { method: 'DELETE', ...options });