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

refactor: replace UniverseCanonSection's 28-prop KindSection with a per-kind context

[._.]/ Adam Eivy6f4039649886
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 97e2ec6a5e..10e445eaad 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,7 @@
- **The Sprite Manager page no longer carries its three header panels inline.** `ImportPanel`, `NewSpritePanel`, and `SpriteSearch` were independent top-level components sharing `Sprites.jsx` with the detail/render orchestration; each is now its own file in `client/src/components/sprites/`, leaving the page at 606 lines of routing, render tracking, and workflow wiring. Pure move — same props, handlers, and markup. (#3390)
- **`/api/universe-builder` is a directory of sub-routers, not one 987-line file.** The 36 endpoints split along the service seams they already delegated to — `expand.js`, `vision.js`, `styleReferences.js`, `referenceSheets.js`, `merge.js`, `crud.js`, `render.js`, `canon.js` — behind a thin `routes/universeBuilder/index.js`, with the zod fragments and image resolvers more than one router composes moved to `shared.js`. Mount order is the load-bearing part and is documented at the mount: every sub-router owning a single-segment static path (`/expand`, `/duplicates`, `/merge*`, …) mounts ahead of `crud.js`, whose `GET /:id` would otherwise swallow it. Verified by resolving 520 method+URL combinations against the old and new routers and confirming every one lands on the same handler. (#3392)
- **Typing in the Writers Room no longer re-renders the storyboard sidebar.** `WorkEditor`'s body textarea shared a render with `<StoryboardPanel>` — a heavy tree of bibles, boards, scene cards, and image config with zero dependency on the prose — so every keystroke re-rendered the whole sidebar. The panel is now memoized and every prop it receives is referentially stable across keystrokes (the run/style handlers are `useCallback`s and `onJumpToScene` reads the body through a ref instead of a dep), leaving one re-render on the clean → dirty flip and none after. Three hooks came out with it — `useLiveSuggest`, `useSidebarResize`, `useTokenPopover` — plus `WorkEditorVersions` / `WorkEditorVoicePanel` as their own files. Behavior is unchanged. (#3387)
+- **A canon trunk's wiring travels by context, not a 36-prop bag.** `KindSection` inside `UniverseCanonSection.jsx` took every handler, spinner id, and job map as an individually threaded prop, so adding one capability meant editing the call site, the signature, and its defaults. The bag is now published once per kind through `KindSectionContext` and read where it's used, and the inline add-entry mini-form moved to `CanonAddEntryForm.jsx` (its name/description draft resets on unmount instead of by hand). `KindSection` takes zero props; behavior, markup, and classes are unchanged. (#3388)
- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.
## Better audit 2026-08-03 (UX, City scene, game/music/writing focus) — PRs #3401–#3404
diff --git a/client/src/components/universe/CanonAddEntryForm.jsx b/client/src/components/universe/CanonAddEntryForm.jsx
new file mode 100644
index 0000000000..97985311d4
--- /dev/null
+++ b/client/src/components/universe/CanonAddEntryForm.jsx
@@ -0,0 +1,69 @@
+/**
+ * Manual "Add <kind>" mini-form for a canon trunk in `UniverseCanonSection`.
+ *
+ * Collects a name + optional description and hands them to `onAddEntry`, which
+ * owns persistence (optimistic append → `updateUniverse` → revert on failure).
+ * Mirrors CategoryEditor's `adding`/`newLabel` bucket-add shape.
+ *
+ * Draft state lives here and the component is unmounted by its owner whenever
+ * the form is closed, so cancel/save both reset the fields for free — the same
+ * net behavior as the previous inline version, which cleared them by hand.
+ */
+import { useState } from 'react';
+import { Loader2 } from 'lucide-react';
+import { BIBLE_LIMITS } from '../../lib/bibleLimits';
+
+export default function CanonAddEntryForm({ kind, creating = false, onAddEntry = null, onClose }) {
+ const [newName, setNewName] = useState('');
+ const [newDesc, setNewDesc] = useState('');
+
+ const submitAdd = async () => {
+ if (!newName.trim() || !onAddEntry || creating) return;
+ // `onAddEntry` resolves false on a duplicate name or a failed save — keep
+ // the form open in that case so the typed draft isn't thrown away.
+ const ok = await onAddEntry({ name: newName, description: newDesc });
+ if (ok) onClose();
+ };
+
+ return (
+ <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">
+ <input
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') submitAdd(); }}
+ placeholder={`${kind.singular[0].toUpperCase()}${kind.singular.slice(1)} name`}
+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
+ maxLength={BIBLE_LIMITS.NAME_MAX}
+ autoFocus
+ aria-label={`New ${kind.singular} name`}
+ />
+ <textarea
+ value={newDesc}
+ onChange={(e) => setNewDesc(e.target.value)}
+ placeholder={`Describe this ${kind.singular} (optional — image-gen-ready prose)`}
+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
+ rows={2}
+ maxLength={kind.descFieldMax}
+ aria-label={`New ${kind.singular} description`}
+ />
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={submitAdd}
+ disabled={!newName.trim() || creating}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded"
+ >
+ {creating ? <Loader2 size={12} className="animate-spin" /> : null}
+ Save
+ </button>
+ <button
+ type="button"
+ onClick={onClose}
+ className="text-xs px-2 py-1 bg-port-bg hover:bg-port-border text-gray-300 rounded"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/universe/KindSectionContext.jsx b/client/src/components/universe/KindSectionContext.jsx
new file mode 100644
index 0000000000..0a6657d0f1
--- /dev/null
+++ b/client/src/components/universe/KindSectionContext.jsx
@@ -0,0 +1,48 @@
+/**
+ * Per-kind context for one canon trunk (Characters / Places / Objects) inside
+ * `UniverseCanonSection`.
+ *
+ * `KindSection` used to take ~30 props — the whole handler + job-state bag was
+ * threaded manually through JSX, so adding one capability meant touching the
+ * call site, the signature, and every default. The bag is now published once
+ * per kind by the parent and read where it's needed, which keeps the call site
+ * a single `<KindSection />` and makes the section's dependencies explicit at
+ * the point of use.
+ *
+ * The value is intentionally a fresh object per parent render — identical to
+ * the previous prop-threading behavior, where every inline arrow (`onRender`,
+ * `onToggleLock`, …) also reallocated each render. Nothing downstream is
+ * memoized on the bag's identity, so there's no re-render regression here.
+ *
+ * Shape (all supplied by `UniverseCanonSection`):
+ * kind, universeId, all, totalCount, filtered, usage, seriesNameMap,
+ * fullList, castList, compact,
+ * renderingJobs, externalPendingByEntryId,
+ * refiningId, expandingId, togglingLockId, bulkLocking, renderingAll,
+ * catalogLinking, creating,
+ * onRender, onRenderAll, onRenderCleanPlate, onJobCompleted, onJobFailed,
+ * onPreview, onRefine, onExpandCharacter, onSheetCompleted, onSheetDeleted,
+ * onToggleLock, onBulkLock, onPatchEntry, onDescribeImages,
+ * onCorrectFromImage, onPickFromCatalog, onAddEntry
+ */
+import { createContext, useContext } from 'react';
+
+const KindSectionContext = createContext(null);
+
+export function KindSectionProvider({ value, children }) {
+ return (
+ <KindSectionContext.Provider value={value}>
+ {children}
+ </KindSectionContext.Provider>
+ );
+}
+
+// Fail fast rather than silently rendering a section with no handlers — a
+// missing provider is always a wiring bug, never a valid state.
+export function useKindSection() {
+ const ctx = useContext(KindSectionContext);
+ if (!ctx) throw new Error('useKindSection must be used inside a KindSectionProvider');
+ return ctx;
+}
+
+export default KindSectionContext;
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 97e42f1c0b..b5855830bf 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -38,6 +38,8 @@ import { useAsyncAction } from '../../hooks/useAsyncAction';
import useMounted from '../../hooks/useMounted';
import { useCanonPatch } from '../../hooks/useCanonPatch';
import CanonCard from '../pipeline/CanonCard';
+import CanonAddEntryForm from './CanonAddEntryForm';
+import { KindSectionProvider, useKindSection } from './KindSectionContext';
import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';
import { buildUniverseSectionRenderTag } from '../../lib/universeRunTag';
import { universeStylePreset } from '../../lib/universeStylePreset';
@@ -657,6 +659,85 @@ export default function UniverseCanonSection({
const charCount = (universe.characters || []).length;
+ // Everything one canon trunk needs, published through KindSectionContext so
+ // the call site stays a bare `<KindSection />` instead of a ~30-prop bag.
+ // Rebuilt per render (same as the inline arrows it replaces) — see the
+ // identity note in KindSectionContext.jsx.
+ const buildKindSectionContext = (kind) => ({
+ kind,
+ universeId,
+ all: filteredByKind[kind.key] || [],
+ totalCount: (universe[kind.key] || []).length,
+ filtered: !!seriesFilter,
+ usage: usage?.[kind.key] || null,
+ renderingJobs,
+ onRender: (entry) => handleRenderRef(kind, entry),
+ onJobCompleted: (entryId, filename, completedJobId) => {
+ // Discriminate by which pending map owns the completed jobId.
+ // As of #1395 BOTH paths are persisted server-side by the
+ // `appendEntryImageRef` completion hook (section-local renders now
+ // carry a durable `universeRun.entryRef` tag too), so neither
+ // client path PATCHes — they only mirror the ref into the draft:
+ // - section-local renders (`generateImage`) populate
+ // `renderingJobs[entryId]`; `handleRefCompleted` clears the
+ // spinner + stamps the draft optimistically.
+ // - external batch renders flow through the page-level
+ // `externalPendingByEntryId`; `handleExternalCanonRefCompleted`
+ // stamps the draft + clears the pending queue.
+ const isExternal = completedJobId
+ && externalPendingByEntryId?.[entryId] === completedJobId;
+ if (isExternal) {
+ handleExternalCanonRefCompleted(kind.key, entryId, filename);
+ onExternalCanonJobSettled?.(entryId, completedJobId);
+ } else {
+ handleRefCompleted(kind.key, entryId, filename);
+ }
+ },
+ onJobFailed: (entryId, errMsg, failedJobId) => {
+ const isExternal = failedJobId
+ && externalPendingByEntryId?.[entryId] === failedJobId;
+ if (isExternal) {
+ onExternalCanonJobSettled?.(entryId, failedJobId);
+ if (errMsg) toast.error(`Render failed: ${errMsg}`);
+ } else {
+ handleRefFailed(entryId, errMsg);
+ }
+ },
+ onPreview: openPreview,
+ onRefine: handleRefineCharacter,
+ refiningId,
+ onExpandCharacter: handleExpandCharacter,
+ expandingId,
+ onSheetCompleted: handleSheetCompleted,
+ onSheetDeleted: handleSheetDeleted,
+ onToggleLock: (entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked),
+ togglingLockId,
+ onPatchEntry: (entryId, patch) => handlePatchEntry(kind, entryId, patch),
+ onRenderCleanPlate: (entry) => handleRenderCleanPlate(kind, entry),
+ onDescribeImages: (entry) => setDescribeTarget({ kind, entry }),
+ onCorrectFromImage: (entry) => setCorrectTarget({ kind, entry }),
+ seriesNameMap: usage?.seriesNameMap || null,
+ onBulkLock: (nextLocked) => handleBulkLockKind(kind, nextLocked),
+ bulkLocking: bulkLockingKindKey === kind.key,
+ fullList: Array.isArray(universe[kind.key]) ? universe[kind.key] : [],
+ // The universe-wide character list — feeds the attachment target
+ // picker in ObjectAttachmentsEditor for the objects kind (#1288).
+ castList: Array.isArray(universe.characters) ? universe.characters : [],
+ externalPendingByEntryId,
+ // Single-kind view (`?kind=places`, sidebar deep-links) — the
+ // outer canon section already supplies the h2 + description + card
+ // chrome, so KindSection drops its own bordered wrapper + duplicate
+ // header. Multi-kind view keeps the chrome so Characters / Places /
+ // Objects stay visually separated.
+ compact: !!kindFilter,
+ onRenderAll: () => handleRenderAll(kind),
+ renderingAll: renderAllKindKey === kind.key,
+ onPickFromCatalog: () => setCatalogPickerKind(kind),
+ catalogLinking,
+ onAddEntry: (payload) => handleCreateEntry(kind, payload),
+ creating: creatingKindKey === kind.key,
+ });
+
return (
// `id="canon"` is the scroll target for `/universes/:id#canon`
// deep-links (legacy `/canon` route redirect + PipelineSeries "Manage
@@ -763,81 +844,9 @@ export default function UniverseCanonSection({
) : null}
{KINDS.filter((kind) => !kindFilter || kind.key === kindFilter).map((kind) => (
- <KindSection
- key={kind.key}
- kind={kind}
- universeId={universeId}
- all={filteredByKind[kind.key] || []}
- totalCount={(universe[kind.key] || []).length}
- filtered={!!seriesFilter}
- usage={usage?.[kind.key] || null}
- renderingJobs={renderingJobs}
- onRender={(entry) => handleRenderRef(kind, entry)}
- onJobCompleted={(entryId, filename, completedJobId) => {
- // Discriminate by which pending map owns the completed jobId.
- // As of #1395 BOTH paths are persisted server-side by the
- // `appendEntryImageRef` completion hook (section-local renders now
- // carry a durable `universeRun.entryRef` tag too), so neither
- // client path PATCHes — they only mirror the ref into the draft:
- // - section-local renders (`generateImage`) populate
- // `renderingJobs[entryId]`; `handleRefCompleted` clears the
- // spinner + stamps the draft optimistically.
- // - external batch renders flow through the page-level
- // `externalPendingByEntryId`; `handleExternalCanonRefCompleted`
- // stamps the draft + clears the pending queue.
- const isExternal = completedJobId
- && externalPendingByEntryId?.[entryId] === completedJobId;
- if (isExternal) {
- handleExternalCanonRefCompleted(kind.key, entryId, filename);
- onExternalCanonJobSettled?.(entryId, completedJobId);
- } else {
- handleRefCompleted(kind.key, entryId, filename);
- }
- }}
- onJobFailed={(entryId, errMsg, failedJobId) => {
- const isExternal = failedJobId
- && externalPendingByEntryId?.[entryId] === failedJobId;
- if (isExternal) {
- onExternalCanonJobSettled?.(entryId, failedJobId);
- if (errMsg) toast.error(`Render failed: ${errMsg}`);
- } else {
- handleRefFailed(entryId, errMsg);
- }
- }}
- onPreview={openPreview}
- onRefine={handleRefineCharacter}
- refiningId={refiningId}
- onExpandCharacter={handleExpandCharacter}
- expandingId={expandingId}
- onSheetCompleted={handleSheetCompleted}
- onSheetDeleted={handleSheetDeleted}
- onToggleLock={(entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked)}
- togglingLockId={togglingLockId}
- onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
- onRenderCleanPlate={(entry) => handleRenderCleanPlate(kind, entry)}
- onDescribeImages={(entry) => setDescribeTarget({ kind, entry })}
- onCorrectFromImage={(entry) => setCorrectTarget({ kind, entry })}
- seriesNameMap={usage?.seriesNameMap || null}
- onBulkLock={(nextLocked) => handleBulkLockKind(kind, nextLocked)}
- bulkLocking={bulkLockingKindKey === kind.key}
- fullList={Array.isArray(universe[kind.key]) ? universe[kind.key] : []}
- // The universe-wide character list — feeds the attachment target
- // picker in ObjectAttachmentsEditor for the objects kind (#1288).
- castList={Array.isArray(universe.characters) ? universe.characters : []}
- externalPendingByEntryId={externalPendingByEntryId}
- // Single-kind view (`?kind=places`, sidebar deep-links) — the
- // outer canon section already supplies the h2 + description + card
- // chrome, so KindSection drops its own bordered wrapper + duplicate
- // header. Multi-kind view keeps the chrome so Characters / Places /
- // Objects stay visually separated.
- compact={!!kindFilter}
- onRenderAll={() => handleRenderAll(kind)}
- renderingAll={renderAllKindKey === kind.key}
- onPickFromCatalog={() => setCatalogPickerKind(kind)}
- catalogLinking={catalogLinking}
- onAddEntry={(payload) => handleCreateEntry(kind, payload)}
- creating={creatingKindKey === kind.key}
- />
+ <KindSectionProvider key={kind.key} value={buildKindSectionContext(kind)}>
+ <KindSection />
+ </KindSectionProvider>
))}
{/* Single shared picker — `catalogPickerKind` carries the KINDS entry
@@ -898,7 +907,21 @@ export default function UniverseCanonSection({
);
}
-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, onDescribeImages = null, onCorrectFromImage = null, seriesNameMap, onBulkLock, bulkLocking, fullList, castList = [], externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false, onAddEntry = null, creating = false }) {
+// One canon trunk (Characters / Places / Objects). Every input arrives through
+// KindSectionContext — see that module for the published shape and why the bag
+// isn't prop-threaded any more.
+function KindSection() {
+ const {
+ kind, universeId, all, totalCount, filtered, usage, renderingJobs,
+ onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId,
+ onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted,
+ onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate,
+ onDescribeImages = null, onCorrectFromImage = null, seriesNameMap,
+ onBulkLock, bulkLocking, fullList, castList = [],
+ externalPendingByEntryId = null, compact = false, onRenderAll = null,
+ renderingAll = false, onPickFromCatalog = null, catalogLinking = false,
+ onAddEntry = null, creating = false,
+ } = useKindSection();
// 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
@@ -926,23 +949,11 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
);
const Icon = kind.icon;
- // Manual-add form state — local to the section (mirrors CategoryEditor's
- // `adding`/`newLabel` bucket-add form). Persistence is the parent's job via
- // `onAddEntry`; this just collects a name + optional description and resets
- // on a successful save.
+ // Whether the manual-add mini-form is open. The form owns its own name/desc
+ // draft (CanonAddEntryForm) and unmounts when closed, so cancel/save reset
+ // the fields for free; only the disclosure bit lives here because the "Add"
+ // button in the controls strip toggles it.
const [adding, setAdding] = useState(false);
- const [newName, setNewName] = useState('');
- const [newDesc, setNewDesc] = useState('');
- const submitAdd = async () => {
- if (!newName.trim() || !onAddEntry || creating) return;
- const ok = await onAddEntry({ name: newName, description: newDesc });
- if (ok) {
- setNewName('');
- setNewDesc('');
- setAdding(false);
- }
- };
- const cancelAdd = () => { setAdding(false); setNewName(''); setNewDesc(''); };
// Bulk lock-state summary computed off the FULL list (not the series-filtered
// view) so the buttons reflect the universe-wide state the bulk action will
@@ -1037,45 +1048,12 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
);
const addForm = adding ? (
- <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">
- <input
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => { if (e.key === 'Enter') submitAdd(); }}
- placeholder={`${kind.singular[0].toUpperCase()}${kind.singular.slice(1)} name`}
- className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
- maxLength={BIBLE_LIMITS.NAME_MAX}
- autoFocus
- aria-label={`New ${kind.singular} name`}
- />
- <textarea
- value={newDesc}
- onChange={(e) => setNewDesc(e.target.value)}
- placeholder={`Describe this ${kind.singular} (optional — image-gen-ready prose)`}
- className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"
- rows={2}
- maxLength={kind.descFieldMax}
- aria-label={`New ${kind.singular} description`}
- />
- <div className="flex items-center gap-2">
- <button
- type="button"
- onClick={submitAdd}
- disabled={!newName.trim() || creating}
- className="inline-flex items-center gap-1 text-xs px-2 py-1 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded"
- >
- {creating ? <Loader2 size={12} className="animate-spin" /> : null}
- Save
- </button>
- <button
- type="button"
- onClick={cancelAdd}
- className="text-xs px-2 py-1 bg-port-bg hover:bg-port-border text-gray-300 rounded"
- >
- Cancel
- </button>
- </div>
- </div>
+ <CanonAddEntryForm
+ kind={kind}
+ creating={creating}
+ onAddEntry={onAddEntry}
+ onClose={() => setAdding(false)}
+ />
) : null;
const list = all.length === 0 ? (