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([character-bible-simplify-followups]): bundled /simplify cleanups

[._.]/ Adam Eivybfe75a47c4a1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index be6e0226f9..2959799cd0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,7 @@
### Universe Builder
+- **Character bible / reference-sheet `/simplify` follow-ups.** Nine cleanups bundled from the simplify review during the character bible expansion PR. (1) `CanonCard`'s four character-only props collapsed into a single `characterExtensions` object so non-character call sites skip them entirely. (2) New `client/src/lib/bibleLimits.js` mirrors `server/lib/storyBible.js` `BIBLE_LIMITS` so client-side `max:` literals can't drift from the server caps. (3) Single-field `useFieldDraft` hook shared by `CharacterDetailEditor#DraftField` and a new per-row `WardrobeRow` sub-component (replaces the indexed `${idx}:${field}` drafts map). (4) `runPromptRefine` split into a lower-level `runPromptRefineRaw` so multi-field merges (`universeCharacterExpand`) can reuse the empty-guard + rationale-trim + log-tag scaffold. (5) `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` collapsed onto a `makePathResolver(rootOrGetter, { extensions, cache })` factory — preserves test-time late-binding semantics via thunk roots. (6) New `shortId(id, n=8)` helper in `fileUtils.js` replaces inline `String(x).slice(0, 8)` across the universe character family. (7) New `createImageGenWaiter` extracts the shared `imageGenEvents` completion-waiter pattern used by `sdapi.js#createCompletionWaiter` and `voice/tools.js#image_gen`. (8) `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` moved from `universeCharacterSheet.js` to `canonPrompt.js` alongside `RICH_SPEC`. (9) `CharacterReferenceSheetPanel#waitForImageRef` accepts an `AbortSignal` so unmount aborts the 3 s HEAD-poll loop instead of letting it issue requests against a dead component. Two sub-bullets deferred to dedicated PLAN entries (`[purge-reference-sheet-image-ref-on-sheet-delete]` and `[clear-pending-sheet-slot-on-entry-delete]`) — both gate on delete routes that don't exist yet.
- **Character bible expansion + artist reference sheet.** Universe canon characters now carry novelist + graphic-novelist depth and can render a single dense artist reference sheet styled to match the universe. `sanitizeCharacter` in `server/lib/storyBible.js` gains 15 prose fields (pronouns, age, coreTheme, speechAccent, visualNotes, silhouetteNotes, postureNotes, specialTraits, visualIdentity, motivations, likes, dislikes, mannerisms, relationships, skills) + 5 structured lists (stats, colorPalette, props, expressions, handGestures) + 1 operational pointer (`referenceSheetImageRef`). Stats are an open `[{label, value}]` list so non-human characters (ghosts, spiders, clouds, AIs) aren't shoehorned into human anatomy. Two new endpoints: `POST /api/universe-builder/:id/characters/:entryId/expand` runs one LLM call (new `universe-character-expand` stage) that fills BLANK extended fields without clobbering populated content; `POST /api/universe-builder/:id/characters/:entryId/render-reference-sheet` enqueues a media-job render driven by a rich TEXT prompt (no init image required) that works equally well across codex and local image-gen backends. The renderer emits a multi-paragraph layout-prescriptive prompt (turnaround, expression progression, color palette swatches, wardrobe + prop cards, hand gestures), routes through `mediaJobQueue` with the active `imageGen.mode` (codex → codex lane, local → GPU lane; external SD-API returns `UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE` rather than a silently-degraded render), and on `mediaJobEvents` completion copies the result into `data/image-refs/` then stamps `character.referenceSheetImageRef`. Completed renders are also filed into the universe's media collection (`Universe: <name>` bucket) via `universeBuilderCollectionHook` by attaching a `universeRun` tag to the enqueued job, alongside the rest of the universe's concept art. `/data/image-refs/` is now exposed as a static route so the UI can render the sheet inline. New UI: `CharacterDetailEditor.jsx` (sectioned collapsible editor for the extended fields) + `CharacterReferenceSheetPanel.jsx` (Generate / Regenerate / lightbox) embedded in `CanonCard.jsx` behind a single "Character details + reference sheet" toggle that only renders when the caller passes the universe wiring — the per-series NounsStage stays focused on naming + visual refs. New migration `022-character-extended-fields.js` is record-only (sanitizer fills defaults on next read). 18+ new server tests (storyBible extensions + universeCharacterSheet prompt builder + universeCharacterExpand merge semantics + route mocks).
- **CanonCard provenance chip now names the source series.** The "from series" chip on `CanonCard` (rendered by both the Universe Canon section and the per-issue Nouns stage) now reads `from <Series Name>` when an entry's `sourceSeriesId` resolves through a new `seriesNameMap` prop; the tooltip carries both name and id (`Introduced by series "<name>" (<id>)`). Map is sourced from a new top-level `seriesNameMap` field on the `GET /api/universe-builder/:id/canon-usage` response, which now lists every linked series — not just ones with a prose-match row — so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Missing-map / unknown-id cases keep the legacy `from series` label + id-only tooltip. New `SourceSeriesChip` helper extracted in `client/src/components/pipeline/CanonCard.jsx`; 4 vitest cases in `CanonCard.test.jsx` + 2 vitest cases in `server/services/canonUsage.test.js`.
diff --git a/DONE.md b/DONE.md
index a739d3ac3e..d0736dad41 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-18
+- **[character-bible-simplify-followups] Character bible / reference-sheet `/simplify` follow-ups.** Captured from the simplify review during the character bible expansion PR; nine of the eleven sub-bullets landed in this PR (the two skipped ones gate on delete routes that don't exist yet — `purgeReferenceSheetFromAllUniverses` + `clearPendingSheetSlot` — and are deferred until those land). Touched files: (1) `client/src/components/pipeline/CanonCard.jsx` + `client/src/components/universe/UniverseCanonSection.jsx` — bundled four character-only props (`universeId`, `onExpandCharacter`, `expanding`, `onSheetCompleted`) into a single `characterExtensions` object so the gate collapses to one truthiness check; NounsStage still passes nothing and stays focused. (2) New `client/src/lib/bibleLimits.js` mirrors `server/lib/storyBible.js` `BIBLE_LIMITS` verbatim; `CharacterDetailEditor.jsx`'s 25+ `max:` literals + `CanonCard.jsx`'s wardrobe `maxLength`s now reference the constants by name. (3) New `client/src/hooks/useFieldDraft.js` — single-field draft+blur hook used by `CharacterDetailEditor#DraftField` and a new per-row `WardrobeRow` sub-component (replaces the indexed `${idx}:${field}` drafts map in `WardrobeSection`). `ListRow`'s multi-column row-state (with sibling-draft "ride-along" race protection) was deliberately left as-is — splitting per-column would lose the protection. (4) `server/services/pipeline/refineHelpers.js` split into `runPromptRefineRaw` (lower-level: runStagedLLM + empty-guard + rationale-trim + optional logTag) and the existing `runPromptRefine` (single-field convenience wrapper built atop the raw variant); `server/services/universeCharacterExpand.js` now consumes `runPromptRefineRaw` with `logTag: null` so it can log a context-rich line after the merge. (5) New `makePathResolver(rootOrGetter, { extensions, cache })` factory in `server/lib/fileUtils.js`; collapses `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` onto one closure. Accepts a thunk for late-binding so existing test mutations of `PATHS.images` at mock-eval time still steer the resolver. (6) New `shortId(id, n=8)` helper in `fileUtils.js` (null-safe); replaces inline `String(x).slice(0, 8)` in `universeCharacterExpand.js`, `universeCharacterSheet.js`, and `universeCanon.js` (the in-scope universe character family). Other call sites (shell, agents, cos) intentionally left alone — outside scope. (7) New `server/services/imageGenWaiter.js` (`createImageGenWaiter`) extracts the shared `imageGenEvents` completion-waiter pattern used by `server/routes/sdapi.js#createCompletionWaiter` (now a thin error-shape wrapper) and `server/services/voice/tools.js#image_gen` (drops the inline duplicate). The `universeCharacterSheet.js#subscribeToSheetJob` pattern stays distinct — it uses a different events bus (`mediaJobEvents`), an internal dispatcher that bounds listeners, callback-style handlers, and a two-stage timeout with `onStarted` reset. (8) `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` moved from `universeCharacterSheet.js` to `server/lib/canonPrompt.js` alongside `RICH_SPEC` so per-page render prompts can reuse them. (9) `CharacterReferenceSheetPanel.jsx#waitForImageRef` accepts an `AbortSignal`; a new `pollAbortRef` is wired into a useEffect-cleanup so unmount aborts the 3 s HEAD-poll loop (and the in-flight fetch) instead of letting it issue requests against a dead component. Sentinel `null` return distinguishes "aborted" from "give up + toast." Coverage: all 5565 server tests pass; all 92 client tests pass. Test files updated: `server/services/universeCanon.test.js` adds `shortId` to its `fileUtils.js` mock so the new log-line consumer doesn't break the lock-semantics tests.
- **[coverautofiler-dispatcher-redundant-getseries] `fileCoverIntoAutoCollection` dispatcher — pass preloaded series into the universe leaf.** `server/services/pipeline/coverUniverseFiler.js`'s dispatcher now forwards its already-fetched series to `fileCoverIntoUniverseCollection` via an optional `_preloadedSeries` arg; the universe leaf accepts the preload, skips its initial `getSeries`, and preserves the mid-flight race-detection re-read. Net effect for the dominant (universe-linked) path: 2 `getSeries` calls per cover completion instead of 3. The series leaf intentionally does NOT accept a preload — its own first read is load-bearing for the early re-route check (a universe link added between the dispatcher's fetch and the leaf's entry must trigger the re-route into the universe leaf, otherwise the cover would land in the per-series collection and merely get orphaned by the post-`addItem` recovery instead of filed to the universe). Direct callers of the universe leaf (no preload) keep the old shape via a `?? await getSeries(...).catch(() => null)` fallback. +1 test in `coverUniverseFiler.test.js` spies on `seriesSvc.getSeries` and pins the post-optimization universe-path call count (2 total) via the capture-restore-assert pattern so a failing assertion doesn't leak the spy. All 21 cover-filer tests + 349 pipeline-service tests pass.
- **[importer-canonprompt-preview-fragments-helper] Share a per-kind preview-fragments helper between Importer and `canonPrompt.js`.** New `previewCanonFragments(kind, entry)` helper in the mirrored `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` returns `{ subtitle, body }` where `subtitle` is a single trimmed string and `body` is an ordered `[{ field, value }]` array of non-blank fields. Backed by a new `PREVIEW_SPEC` keyed by canonical kind name (`characters` → `{ subtitleField: 'role', bodyFields: ['physicalDescription','personality','background'] }`, `places` → `{ subtitleField: 'slugline', bodyFields: ['description'] }`, `objects` → `{ subtitleField: null, bodyFields: ['description','significance'] }`). Intentionally wider than `shortCanonDescriptorFragments` (which is scoped to the visual subset that drives render-prompts) — preview exists so the user can disambiguate which entry to commit, so it surfaces narrative-only fields (`personality`, `background`, `slugline`) that have no visual role. The three `CanonReviewSection` callsites in `client/src/pages/Importer.jsx` no longer pass `renderSubtitle`/`renderBody` props — `CanonReviewSection` now calls the helper directly with the `kind` prop it was already passing, collapsing 18 lines of inline ternaries + filter/join calls onto a single helper invocation. 11 new vitest cases in `server/lib/canonPrompt.test.js` cover null/non-object/unknown-kind edge shapes, kind plural/singular passthrough, per-kind field-presence semantics (characters: role subtitle + 3-field body, no description fallback; places: slugline + description only; objects: empty subtitle + description+significance), whitespace trimming, and confirms RICH-only fields (palette/era/weather/recurringDetails) are NOT in preview. PLAN.md's `'places' → 'settings'` alias note was stale — codebase already canonicalized on `'places'` as the kind name (`normalizeKind` returns `'places'` correctly), so no alias work was needed. All 5608 server tests + 92 client tests pass.
- **[extraction-after-comicscript-teleplay-stages] Extraction after comicScript / teleplay stages.** Resolves the deferred decision in favor of an opt-in, manually-triggered extraction: auto-extract stays prose-only (so the auto-pipeline isn't paying an extra LLM call per script stage on every issue), but writers can now pull canon from a script stage on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (stageId must be `comicScript` or `teleplay`) reads `issue.stages[stageId].output` as the corpus and calls the existing generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping the prose auto-extract uses, so script-derived entries survive later AI refines and stay attributable to the triggering series. Schema `extractCanonFromScriptSchema` accepts an optional `providerOverride`; the route also returns the merged universe plus `{ characters, places, objects }` counts so the UI toast can summarize the merge. Three precondition guards: `PIPELINE_CANON_EXTRACT_BAD_STAGE` (400) for any stage other than the two script stages, `PIPELINE_CANON_EXTRACT_NO_CORPUS` (400) when the script stage has no output, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE` (400) when the series isn't linked to a universe. New shared component `client/src/components/pipeline/stages/ExtractCanonButton.jsx` (BookOpen icon + "Extract canon" label) is gated on stage content + linked universe and surfaces a tooltip explaining the specific blocker when disabled. Wired into both script stages: `TeleplayStage.jsx` passes it through `TextStagePanel`'s `extraActions` slot; `ComicScriptStage.jsx` mounts it directly in its header actions next to the Image-gen settings button. Client helper `extractPipelineCanonFromScript(issueId, stageId, body, options)` in `apiPipeline.js` follows the project's silent/toast convention (helper passes `{ silent: true }` since the button owns its own error toast). 5 new vitest cases in `server/routes/pipeline.test.js` cover all three precondition guards plus the happy path for both stage IDs, asserting the corpus is forwarded and the autoLock/sourceSeriesId stamping matches the prose auto-extract semantics. All 5570 server tests + 92 client tests pass; client build clean.
diff --git a/PLAN.md b/PLAN.md
index 345f3a421c..d06eef4ca4 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -21,18 +21,9 @@ _Nothing currently parked — pick the next item from the Backlog._
### Universe-as-Canon — Phase 2 + extensions
-- [ ] [character-bible-simplify-followups] **Character bible / reference-sheet `/simplify` follow-ups.** Captured from the simplify review during the character bible expansion PR; each is deferred-but-cheap and shares the same surface area:
- - Bundle `CanonCard`'s four new character-only props (`universeId`, `onExpandCharacter`, `expanding`, `onSheetCompleted`) into a single `characterExtensions={…}` object; collapses the gate from 4 nulls per non-character call site to `characterExtensions && kind.key === 'characters'`. Touches `client/src/components/pipeline/CanonCard.jsx`, `client/src/components/universe/UniverseCanonSection.jsx` `KindSection`, and any other CanonCard consumer.
- - Mirror `server/lib/storyBible.js` `BIBLE_LIMITS` constants to the client (new `client/src/lib/bibleLimits.js`) and import in `client/src/components/universe/CharacterDetailEditor.jsx` so the editor's `max:` literals can't drift from the server caps.
- - Factor `WardrobeSection`'s draft+blur+pending-row editor (`client/src/components/pipeline/CanonCard.jsx:100-247`) into a shared `<EditableListRow>` / `useFieldDraft()` hook reused by both `WardrobeSection` and `CharacterDetailEditor.jsx`'s `ListRow`. Two implementations will drift.
- - Generalize `server/services/pipeline/refineHelpers.js#runPromptRefine` to handle multi-field merges so `universeCharacterExpand.js` can reuse its empty-guard + rationale-trim + log-tag scaffold instead of inlining them.
- - Collapse `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` in `server/lib/fileUtils.js` onto a shared `makePathResolver(root, { extensions, cache? })` factory — three near-identical 15-line helpers today.
- - Add a `shortId(id, n=8)` helper in a shared lib for the `String(x).slice(0, 8)` pattern that's now in ~12 console.log call sites across `universeCharacterExpand.js` / `universeCharacterSheet.js` / others.
- - Extract a reusable `subscribeToImageGenJob({ jobId, onComplete, onFailed, timeoutMs })` from `server/services/universeCharacterSheet.js#renderCharacterReferenceSheet`; mirrors the pattern in `server/services/voice/tools.js:1320-1338` and `server/routes/sdapi.js#createCompletionWaiter`.
- - Move `universeCharacterSheet.js`'s `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` next to `RICH_SPEC` in `server/lib/canonPrompt.js` so per-page render prompts can reuse them.
- - Active-purge `character.referenceSheetImageRef` when the underlying file in `data/image-refs/` is deleted. Today there is no delete-route for sheet files, and the GET-time lazy `pruneStaleReferenceSheets` masks staleness at read-time, but when a sheet-delete route lands it must also call into a `purgeReferenceSheetFromAllUniverses(filename)` helper mirroring `purgeImageRefFromAllUniverses` in `server/services/universeCanon.js:263`.
- - Prune `_latestPendingByCharacter` in `server/services/universeCharacterSheet.js:221` when a character or universe is deleted. Map grows bounded by characters ever rendered, but stale slot entries persist across the process lifetime — wire a `clearPendingSheetSlot(universeId, entryId)` helper into the character-delete + universe-delete paths once those exist.
- - Cancel `CharacterReferenceSheetPanel`'s `waitForImageRef` poll on unmount. The `mountedRef` guard prevents the state update at line 77, but the 3 s poll keeps issuing HEAD requests against the dead component. Plumb an `AbortSignal` from a `useEffect` cleanup so the loop exits early.
+- [ ] [purge-reference-sheet-image-ref-on-sheet-delete] **Active-purge `character.referenceSheetImageRef` when its sheet file is deleted.** Today there is no delete-route for sheet files; the GET-time lazy `pruneStaleReferenceSheets` masks staleness at read-time. When a sheet-delete route lands it must also call into a new `purgeReferenceSheetFromAllUniverses(filename)` helper mirroring `purgeImageRefFromAllUniverses` in `server/services/universeCanon.js:263`. Deferred from `[character-bible-simplify-followups]` because the delete route doesn't exist yet.
+- [ ] [clear-pending-sheet-slot-on-entry-delete] **Prune `_latestPendingByCharacter` on character / universe delete.** Map at `server/services/universeCharacterSheet.js:221` grows bounded by characters ever rendered, but stale slot entries persist across the process lifetime. Wire a `clearPendingSheetSlot(universeId, entryId)` helper into the character-delete + universe-delete paths once those exist. Deferred from `[character-bible-simplify-followups]` because the delete paths don't exist yet.
+- [ ] [characterdetaileditor-listrow-row-draft-hook] **Extract `ListRow`'s multi-column row-draft state in `CharacterDetailEditor.jsx` into a shared `useRowDraft` hook.** `useFieldDraft` shipped with `[character-bible-simplify-followups]` covers single-field draft+blur, but the `ListRow` component has multi-column row-level state with sibling-draft "ride-along" race protection (`{...row, ...drafts, [col]: v}` so a fast A-blur → B-blur sequence doesn't lose column A). Splitting per-column would lose that protection. A `useRowDraft(row, columns)` hook keyed by column name would expose the same `draftFor(col)`/`setDraft(col, v)`/`commit(col)` API and let CharacterDetailEditor's `ListRow` drop the inline state. Low priority — single consumer today; revisit when a second multi-column-row editor lands.
- [x] ~~**Drop the default `characters` category.**~~ Shipped via the Universe Builder redesign Phase A migration; default `characters` bucket retired, variations backfilled into `universe.characters[]`.
- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index 08099df680..ddb6a5efac 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -13,10 +13,12 @@
import { useEffect, useRef, useState } from 'react';
import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen } from 'lucide-react';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import useFieldDraft from '../../hooks/useFieldDraft';
import MediaJobThumb from './MediaJobThumb';
import EntryCard from '../universe/EntryCard';
import CharacterDetailEditor from '../universe/CharacterDetailEditor';
import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';
+import { BIBLE_LIMITS } from '../../lib/bibleLimits';
// Place metadata enums — kept in lock-step with `PLACE_INT_EXT` and
// `PLACE_TIME_OF_DAY` in `server/lib/storyBible.js`. Mirror is fine: a
@@ -93,15 +95,64 @@ function SourceSeriesChip({ sourceSeriesId, seriesName }) {
);
}
+// One wardrobe row — per-field drafts live inside `useFieldDraft` so the
+// state belongs to the row instance, not an indexed map in the parent.
+// `onCommit('name'|'description', value)` lets the parent decide between
+// patching an existing row, promoting a pending row once name is non-empty,
+// or skipping a no-op.
+function WardrobeRow({ wardrobe, editable, onCommit, onRemove }) {
+ const nameDraft = useFieldDraft(wardrobe.name, (v) => onCommit('name', v));
+ const descDraft = useFieldDraft(wardrobe.description, (v) => onCommit('description', v));
+ if (!editable) {
+ return (
+ <div className="space-y-1">
+ <div className="text-xs text-port-accent font-medium">{wardrobe.name}</div>
+ {wardrobe.description
+ ? <p className="text-[11px] text-gray-400 whitespace-pre-wrap">{wardrobe.description}</p>
+ : null}
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-1">
+ <div className="flex items-center gap-1.5">
+ <input
+ type="text"
+ value={nameDraft.value}
+ onChange={nameDraft.onChange}
+ onBlur={nameDraft.onBlur}
+ placeholder="Outfit name (e.g. Wedding)"
+ className="flex-1 min-w-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white"
+ maxLength={BIBLE_LIMITS.WARDROBE_NAME_MAX}
+ />
+ <button
+ type="button"
+ onClick={onRemove}
+ title={`Remove ${wardrobe.name || 'this outfit'}`}
+ className="shrink-0 text-gray-500 hover:text-port-error"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ <textarea
+ value={descDraft.value}
+ onChange={descDraft.onChange}
+ onBlur={descDraft.onBlur}
+ placeholder="What's the character wearing? (image-gen-ready prose)"
+ rows={2}
+ className="w-full px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white"
+ maxLength={BIBLE_LIMITS.WARDROBE_DESCRIPTION_MAX}
+ />
+ </div>
+ );
+}
+
// Wardrobes (A2) — collapsed summary by default; click to expand into an
-// inline editor when `editable`. Per-field edits are buffered in a draft
-// state and only PATCHed on blur, so a textarea keystroke doesn't fire a
+// inline editor when `editable`. Per-field edits are buffered inside each
+// `WardrobeRow` via `useFieldDraft`, so a keystroke doesn't fire a
// universe-wide round-trip per character.
function WardrobeSection({ wardrobes, editable, onChange }) {
const [open, setOpen] = useState(false);
- // Per-field drafts keyed by `${idx}:${field}`. `undefined` means the
- // textarea reflects the persisted value verbatim.
- const [drafts, setDrafts] = useState({});
// Pending new rows live entirely client-side until the user types a name
// — committing immediately would PATCH a nameless entry, the server-side
// sanitizer would drop it, and the row would vanish mid-type.
@@ -115,19 +166,8 @@ function WardrobeSection({ wardrobes, editable, onChange }) {
const summary = merged.map((w) => w.name).filter(Boolean).join(', ');
const isPending = (idx) => idx >= wardrobes.length;
- const draftValue = (idx, field, fallback) => {
- const key = `${idx}:${field}`;
- return key in drafts ? drafts[key] : (fallback ?? '');
- };
- const setDraft = (idx, field, value) => {
- setDrafts((prev) => ({ ...prev, [`${idx}:${field}`]: value }));
- };
- const commitField = (idx, field) => {
- const key = `${idx}:${field}`;
- if (!(key in drafts)) return;
- const value = drafts[key];
- setDrafts((prev) => { const next = { ...prev }; delete next[key]; return next; });
+ const commit = (idx, field, value) => {
if (isPending(idx)) {
const pendingIdx = idx - wardrobes.length;
const current = pendingNew[pendingIdx] || { name: '', description: '' };
@@ -137,35 +177,18 @@ function WardrobeSection({ wardrobes, editable, onChange }) {
// the persisted list (server sanitizer no longer drops it).
if (field === 'name' && value.trim()) {
const promoted = nextPending[pendingIdx];
- const remaining = nextPending.filter((_, i) => i !== pendingIdx);
- setPendingNew(remaining);
+ setPendingNew(nextPending.filter((_, i) => i !== pendingIdx));
onChange([...wardrobes, promoted]);
} else {
setPendingNew(nextPending);
}
return;
}
-
if ((wardrobes[idx]?.[field] || '') === value) return;
- const nextList = wardrobes.map((w, i) => (i === idx ? { ...w, [field]: value } : w));
- onChange(nextList);
+ onChange(wardrobes.map((w, i) => (i === idx ? { ...w, [field]: value } : w)));
};
+
const removeAt = (idx) => {
- // Selective draft pruning — keep drafts in earlier indices untouched
- // so editing outfit 3 while deleting outfit 1 doesn't lose the
- // outfit-3 keystrokes. Indices past the removed row shift down by 1.
- setDrafts((prev) => {
- const next = {};
- for (const [k, v] of Object.entries(prev)) {
- const sep = k.indexOf(':');
- if (sep < 0) continue;
- const i = Number(k.slice(0, sep));
- const field = k.slice(sep + 1);
- if (i < idx) next[k] = v;
- else if (i > idx) next[`${i - 1}:${field}`] = v;
- }
- return next;
- });
if (isPending(idx)) {
const pendingIdx = idx - wardrobes.length;
setPendingNew(pendingNew.filter((_, i) => i !== pendingIdx));
@@ -173,9 +196,13 @@ function WardrobeSection({ wardrobes, editable, onChange }) {
}
onChange(wardrobes.filter((_, i) => i !== idx));
};
+
const addOne = () => {
setOpen(true);
- setPendingNew((prev) => [...prev, { name: '', description: '' }]);
+ // Client-only id so React keys are stable across re-renders before the
+ // row promotes into the persisted list (server mints its own id then).
+ const id = `pending-wardrobe-${(crypto?.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36).slice(2))}`;
+ setPendingNew((prev) => [...prev, { id, name: '', description: '' }]);
};
return (
@@ -192,44 +219,13 @@ function WardrobeSection({ wardrobes, editable, onChange }) {
{open ? (
<div className="mt-1.5 pl-3 border-l border-port-border space-y-1.5">
{merged.map((w, i) => (
- <div key={w.id || i} className="space-y-1">
- {editable ? (
- <div className="flex items-center gap-1.5">
- <input
- type="text"
- value={draftValue(i, 'name', w.name)}
- onChange={(e) => setDraft(i, 'name', e.target.value)}
- onBlur={() => commitField(i, 'name')}
- placeholder="Outfit name (e.g. Wedding)"
- className="flex-1 min-w-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white"
- maxLength={120}
- />
- <button
- type="button"
- onClick={() => removeAt(i)}
- title={`Remove ${w.name || 'this outfit'}`}
- className="shrink-0 text-gray-500 hover:text-port-error"
- >
- <Trash2 size={12} />
- </button>
- </div>
- ) : (
- <div className="text-xs text-port-accent font-medium">{w.name}</div>
- )}
- {editable ? (
- <textarea
- value={draftValue(i, 'description', w.description)}
- onChange={(e) => setDraft(i, 'description', e.target.value)}
- onBlur={() => commitField(i, 'description')}
- placeholder="What's the character wearing? (image-gen-ready prose)"
- rows={2}
- className="w-full px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white"
- maxLength={800}
- />
- ) : w.description ? (
- <p className="text-[11px] text-gray-400 whitespace-pre-wrap">{w.description}</p>
- ) : null}
- </div>
+ <WardrobeRow
+ key={w.id || i}
+ wardrobe={w}
+ editable={editable}
+ onCommit={(field, value) => commit(i, field, value)}
+ onRemove={() => removeAt(i)}
+ />
))}
{editable ? (
<button
@@ -270,12 +266,10 @@ export default function CanonCard({
seriesNameMap = null,
// Universe-only character extensions. When provided + kind is 'characters',
// CanonCard reveals an Expand → CharacterDetailEditor section and a
- // Reference Sheet panel. NounsStage (series view) omits these so the
+ // Reference Sheet panel. NounsStage (series view) omits this so the
// per-series cast list stays focused on naming + visual refs.
- universeId = null,
- onExpandCharacter = null,
- expanding = false,
- onSheetCompleted = null,
+ // Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted }
+ characterExtensions = null,
}) {
const description = kind.descFor(entry);
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
@@ -384,22 +378,22 @@ export default function CanonCard({
/>
) : null}
{/* Universe-only: extended character detail editor + AI expand action.
- Hidden when the caller didn't pass the universe wiring (pipeline
+ Hidden when the caller didn't pass `characterExtensions` (pipeline
series view). Locked characters render read-only inputs. */}
- {kind.key === 'characters' && universeId && onPatchEntry ? (
+ {kind.key === 'characters' && characterExtensions && onPatchEntry ? (
<CharacterDetailsToggle>
<CharacterDetailEditor
entry={entry}
onPatch={(patch) => onPatchEntry(entry.id, patch)}
- onExpand={onExpandCharacter ? () => onExpandCharacter(entry.id) : null}
- expanding={expanding}
+ onExpand={characterExtensions.onExpandCharacter ? () => characterExtensions.onExpandCharacter(entry.id) : null}
+ expanding={!!characterExtensions.expanding}
disabled={locked}
/>
<CharacterReferenceSheetPanel
- universeId={universeId}
+ universeId={characterExtensions.universeId}
entry={entry}
locked={locked}
- onSheetCompleted={onSheetCompleted}
+ onSheetCompleted={characterExtensions.onSheetCompleted}
onOpenLightbox={(filename) => onPreview?.(filename, { isSheet: true })}
/>
</CharacterDetailsToggle>
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index 332bb29e7d..4eff50b11f 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -15,36 +15,38 @@ import {
ChevronDown, ChevronRight, Plus, Trash2, WandSparkles, Loader2,
Palette, Hand, Smile, Package, BookOpen, Eye, Activity,
} from 'lucide-react';
+import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';
+import useFieldDraft from '../../hooks/useFieldDraft';
const SECTIONS = Object.freeze([
{
key: 'identity', label: 'Identity', icon: BookOpen,
fields: [
- { name: 'pronouns', label: 'Pronouns', placeholder: 'she/her · they/them · it/its', max: 60, type: 'input' },
- { name: 'age', label: 'Age', placeholder: '27 · centuries old · unknown', max: 80, type: 'input' },
- { name: 'coreTheme', label: 'Core theme', placeholder: 'one-sentence essence', max: 500, type: 'textarea' },
- { name: 'speechAccent', label: 'Speech / accent', placeholder: 'clipped Edinburgh; rarely contracts; nautical metaphors', max: 500, type: 'textarea' },
- { name: 'visualNotes', label: 'Visual notes (at-a-glance)', placeholder: 'layered streetwear; faded mustard + charcoal; chunky boots', max: 1000, type: 'textarea' },
+ { name: 'pronouns', label: 'Pronouns', placeholder: 'she/her · they/them · it/its', max: L.PRONOUNS_MAX, type: 'input' },
+ { name: 'age', label: 'Age', placeholder: '27 · centuries old · unknown', max: L.AGE_MAX, type: 'input' },
+ { name: 'coreTheme', label: 'Core theme', placeholder: 'one-sentence essence', max: L.CORE_THEME_MAX, type: 'textarea' },
+ { name: 'speechAccent', label: 'Speech / accent', placeholder: 'clipped Edinburgh; rarely contracts; nautical metaphors', max: L.SPEECH_ACCENT_MAX, type: 'textarea' },
+ { name: 'visualNotes', label: 'Visual notes (at-a-glance)', placeholder: 'layered streetwear; faded mustard + charcoal; chunky boots', max: L.VISUAL_NOTES_MAX, type: 'textarea' },
],
},
{
key: 'personality', label: 'Personality & motivations', icon: Smile,
fields: [
- { name: 'motivations', label: 'Motivations', placeholder: 'what they WANT and what they fear losing', max: 2000, type: 'textarea' },
- { name: 'likes', label: 'Likes', placeholder: 'short prose; comma-separated', max: 1500, type: 'textarea' },
- { name: 'dislikes', label: 'Dislikes', placeholder: 'short prose; comma-separated', max: 1500, type: 'textarea' },
- { name: 'mannerisms', label: 'Mannerisms', placeholder: 'habitual physical / verbal tics', max: 1500, type: 'textarea' },
- { name: 'relationships', label: 'Relationships', placeholder: 'who they\'re connected to and the tenor of each connection', max: 2000, type: 'textarea' },
- { name: 'skills', label: 'Skills', placeholder: 'concrete abilities, soft and hard', max: 2000, type: 'textarea' },
+ { name: 'motivations', label: 'Motivations', placeholder: 'what they WANT and what they fear losing', max: L.MOTIVATIONS_MAX, type: 'textarea' },
+ { name: 'likes', label: 'Likes', placeholder: 'short prose; comma-separated', max: L.LIKES_MAX, type: 'textarea' },
+ { name: 'dislikes', label: 'Dislikes', placeholder: 'short prose; comma-separated', max: L.DISLIKES_MAX, type: 'textarea' },
+ { name: 'mannerisms', label: 'Mannerisms', placeholder: 'habitual physical / verbal tics', max: L.MANNERISMS_MAX, type: 'textarea' },
+ { name: 'relationships', label: 'Relationships', placeholder: 'who they\'re connected to and the tenor of each connection', max: L.RELATIONSHIPS_MAX, type: 'textarea' },
+ { name: 'skills', label: 'Skills', placeholder: 'concrete abilities, soft and hard', max: L.SKILLS_MAX, type: 'textarea' },
],
},
{
key: 'visualIdentity', label: 'Visual identity', icon: Eye,
fields: [
- { name: 'silhouetteNotes', label: 'Silhouette notes', placeholder: 'compact upper body; tapered lower half; short hair adds 5cm height', max: 2000, type: 'textarea' },
- { name: 'postureNotes', label: 'Posture notes', placeholder: 'slight forward lean; weight in left foot; shoulders loose', max: 1000, type: 'textarea' },
- { name: 'specialTraits', label: 'Special traits', placeholder: 'quick hands; scar on right eyebrow; observant', max: 2000, type: 'textarea' },
- { name: 'visualIdentity', label: 'Visual identity (design language)', placeholder: 'knobs + sights; urban utilitarian; analog tech feel', max: 1000, type: 'textarea' },
+ { name: 'silhouetteNotes', label: 'Silhouette notes', placeholder: 'compact upper body; tapered lower half; short hair adds 5cm height', max: L.SILHOUETTE_NOTES_MAX, type: 'textarea' },
+ { name: 'postureNotes', label: 'Posture notes', placeholder: 'slight forward lean; weight in left foot; shoulders loose', max: L.POSTURE_NOTES_MAX, type: 'textarea' },
+ { name: 'specialTraits', label: 'Special traits', placeholder: 'quick hands; scar on right eyebrow; observant', max: L.SPECIAL_TRAITS_MAX, type: 'textarea' },
+ { name: 'visualIdentity', label: 'Visual identity (design language)', placeholder: 'knobs + sights; urban utilitarian; analog tech feel', max: L.VISUAL_IDENTITY_MAX, type: 'textarea' },
],
},
]);
@@ -54,8 +56,8 @@ const LIST_SECTIONS = Object.freeze([
key: 'stats', label: 'Stats', icon: Activity, field: 'stats',
addLabel: 'Add stat', singular: 'stat',
columns: [
- { name: 'label', placeholder: 'Height · Eyes · Form', max: 80 },
- { name: 'value', placeholder: '5\'7" · amber · vapor', max: 200 },
+ { name: 'label', placeholder: 'Height · Eyes · Form', max: L.STAT_LABEL_MAX },
+ { name: 'value', placeholder: '5\'7" · amber · vapor', max: L.STAT_VALUE_MAX },
],
summary: (s) => `${s.label}${s.value ? `: ${s.value}` : ''}`,
},
@@ -63,9 +65,9 @@ const LIST_SECTIONS = Object.freeze([
key: 'colorPalette', label: 'Color palette', icon: Palette, field: 'colorPalette',
addLabel: 'Add swatch', singular: 'swatch',
columns: [
- { name: 'name', placeholder: 'amber', max: 80 },
- { name: 'hex', placeholder: '#f59e0b', max: 10, narrow: true },
- { name: 'role', placeholder: 'skin · jacket primary · boot leather', max: 120 },
+ { name: 'name', placeholder: 'amber', max: L.COLOR_NAME_MAX },
+ { name: 'hex', placeholder: '#f59e0b', max: L.COLOR_HEX_MAX, narrow: true },
+ { name: 'role', placeholder: 'skin · jacket primary · boot leather', max: L.COLOR_ROLE_MAX },
],
summary: (c) => `${c.name}${c.hex ? ` ${c.hex}` : ''}${c.role ? ` — ${c.role}` : ''}`,
swatchHex: (row) => row.hex,
@@ -74,9 +76,9 @@ const LIST_SECTIONS = Object.freeze([
key: 'props', label: 'Props', icon: Package, field: 'props',
addLabel: 'Add prop', singular: 'prop',
columns: [
- { name: 'name', placeholder: 'Radio · Map case', max: 120 },
- { name: 'purpose', placeholder: 'comms · navigation · talisman', max: 400 },
- { name: 'materials', placeholder: 'aluminum + ABS plastic', max: 200 },
+ { name: 'name', placeholder: 'Radio · Map case', max: L.PROP_NAME_MAX },
+ { name: 'purpose', placeholder: 'comms · navigation · talisman', max: L.PROP_PURPOSE_MAX },
+ { name: 'materials', placeholder: 'aluminum + ABS plastic', max: L.PROP_MATERIALS_MAX },
],
summary: (p) => `${p.name}${p.purpose ? ` (${p.purpose})` : ''}`,
},
@@ -84,8 +86,8 @@ const LIST_SECTIONS = Object.freeze([
key: 'expressions', label: 'Expression sheet', icon: Smile, field: 'expressions',
addLabel: 'Add expression', singular: 'expression',
columns: [
- { name: 'name', placeholder: 'neutral · curious · worried', max: 80 },
- { name: 'description', placeholder: 'wide eyes; lips parted; brow raised', max: 400 },
+ { name: 'name', placeholder: 'neutral · curious · worried', max: L.EXPRESSION_NAME_MAX },
+ { name: 'description', placeholder: 'wide eyes; lips parted; brow raised', max: L.EXPRESSION_DESC_MAX },
],
summary: (e) => `${e.name}${e.description ? ` — ${e.description}` : ''}`,
},
@@ -93,39 +95,33 @@ const LIST_SECTIONS = Object.freeze([
key: 'handGestures', label: 'Hand gestures', icon: Hand, field: 'handGestures',
addLabel: 'Add gesture', singular: 'gesture',
columns: [
- { name: 'name', placeholder: 'pointing · peace sign · gripping radio', max: 80 },
- { name: 'description', placeholder: 'open palm; index extended; relaxed', max: 300 },
+ { name: 'name', placeholder: 'pointing · peace sign · gripping radio', max: L.GESTURE_NAME_MAX },
+ { name: 'description', placeholder: 'open palm; index extended; relaxed', max: L.GESTURE_DESC_MAX },
],
summary: (g) => `${g.name}${g.description ? ` — ${g.description}` : ''}`,
},
]);
-// Buffered text input — local draft state, commits to onCommit on blur.
+// Buffered text input — wraps useFieldDraft, commits to onCommit on blur.
function DraftField({ field, value, onCommit, disabled, idPrefix }) {
- const [draft, setDraft] = useState(undefined);
- const current = draft !== undefined ? draft : (value || '');
- const commit = () => {
- if (draft === undefined) return;
- if (draft === (value || '')) { setDraft(undefined); return; }
- onCommit(draft);
- setDraft(undefined);
- };
+ const draft = useFieldDraft(value, onCommit);
+ // idPrefix scopes the field id to one editor instance so two open
+ // character cards don't render duplicate `chr-field-pronouns` DOM ids
+ // and break the label/input association.
+ const id = `chr-field-${idPrefix || 'unknown'}-${field.name}`;
const common = {
- value: current,
- onChange: (e) => setDraft(e.target.value),
- onBlur: commit,
+ id,
+ value: draft.value,
+ onChange: draft.onChange,
+ onBlur: draft.onBlur,
disabled,
placeholder: field.placeholder,
maxLength: field.max,
className: 'w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50',
- // idPrefix scopes the field id to one editor instance so two open
- // character cards don't render duplicate `chr-field-pronouns` DOM ids
- // and break the label/input association.
- id: `chr-field-${idPrefix || 'unknown'}-${field.name}`,
};
return (
<div className="space-y-0.5">
- <label htmlFor={common.id} className="block text-[10px] uppercase tracking-wider text-gray-500">
+ <label htmlFor={id} className="block text-[10px] uppercase tracking-wider text-gray-500">
{field.label}
</label>
{field.type === 'textarea'
diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsx
index 28e3371396..cfbbe40d1a 100644
--- a/client/src/components/universe/CharacterReferenceSheetPanel.jsx
+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx
@@ -22,17 +22,27 @@ import toast from '../ui/Toast';
// /data/image-refs/ AFTER the SSE 'completed' event fires (the listener is
// async, the event was sync), so claiming the file exists at SSE-completion
// time races and shows a 404 thumbnail. Returns true once the file is
-// reachable, false after ~3s of polling.
-async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150 } = {}) {
+// reachable, false after ~3s of polling, or `null` when the signal aborts
+// (so the caller can distinguish "give up + warn the user" from "navigated
+// away, ignore").
+async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150, signal } = {}) {
if (!filename) return false;
+ if (signal?.aborted) return null;
const url = `/data/image-refs/${filename}`;
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
+ if (signal?.aborted) return null;
// cache: 'no-store' so a transient 404 isn't cached by the browser and
- // poisoning subsequent <img> tags.
- const res = await fetch(url, { method: 'HEAD', cache: 'no-store' }).catch(() => null);
+ // poisoning subsequent <img> tags. `signal` aborts the in-flight HEAD too
+ // (not just the inter-attempt sleep).
+ const res = await fetch(url, { method: 'HEAD', cache: 'no-store', signal })
+ .catch(() => null);
+ if (signal?.aborted) return null;
if (res?.ok) return true;
- await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, intervalMs);
+ signal?.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
+ });
}
return false;
}
@@ -56,6 +66,10 @@ export default function CharacterReferenceSheetPanel({
// cleanup-only effect leaves the ref permanently false after React 18
// StrictMode's mount→cleanup→remount cycle in dev.
const mountedRef = useMounted();
+ // Cancels the in-flight `waitForImageRef` HEAD-poll loop on unmount or on
+ // a new render kicking off. Without this the loop keeps issuing requests
+ // against a dead component for the full ~3s budget.
+ const pollAbortRef = useRef(null);
const { status, filename, error, progress } = useMediaJobProgress(jobId);
@@ -73,8 +87,13 @@ export default function CharacterReferenceSheetPanel({
// gallery PNG into /data/image-refs/ and stamped the character.
// Verify the file is actually reachable before flipping the UI;
// otherwise the <img> renders a 404 that the browser caches.
- waitForImageRef(dest).then((ok) => {
+ pollAbortRef.current?.abort();
+ const controller = new AbortController();
+ pollAbortRef.current = controller;
+ waitForImageRef(dest, { signal: controller.signal }).then((ok) => {
+ if (pollAbortRef.current === controller) pollAbortRef.current = null;
if (!mountedRef.current) return;
+ if (ok === null) return; // aborted — caller already moved on
if (ok) onSheetCompleted?.(entryId, dest);
else toast.error('Sheet render finished but the image never appeared — refresh to see it');
});
@@ -86,6 +105,9 @@ export default function CharacterReferenceSheetPanel({
}
}, [jobId, status, filename, error, entry?.id, onSheetCompleted]);
+ // Abort any in-flight HEAD poll when the panel unmounts.
+ useEffect(() => () => { pollAbortRef.current?.abort(); }, []);
+
const handleGenerate = async () => {
if (jobId || !universeId || !entry?.id) return;
const queued = await renderCharacterReferenceSheet(universeId, entry.id)
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 13f9f904c2..36d6f9084a 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -558,6 +558,13 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
}
function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {
+ // Universe-only character wiring — `null` for non-character kinds so
+ // CanonCard's gate stays `kind === 'characters' && characterExtensions`.
+ // Memoized so re-renders don't pass fresh-by-identity props into every card.
+ const characterExtensions = useMemo(
+ () => (kind.key === 'characters' ? { universeId, onExpandCharacter, onSheetCompleted } : null),
+ [kind.key, universeId, onExpandCharacter, onSheetCompleted],
+ );
const Icon = kind.icon;
return (
<section className="rounded border border-port-border bg-port-bg/60">
@@ -594,10 +601,9 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
seriesNameMap={seriesNameMap}
- universeId={kind.key === 'characters' ? universeId : null}
- onExpandCharacter={kind.key === 'characters' ? onExpandCharacter : null}
- expanding={kind.key === 'characters' && expandingId === entry.id}
- onSheetCompleted={kind.key === 'characters' ? onSheetCompleted : null}
+ characterExtensions={characterExtensions
+ ? { ...characterExtensions, expanding: expandingId === entry.id }
+ : null}
/>
))}
</ul>
diff --git a/client/src/hooks/useFieldDraft.js b/client/src/hooks/useFieldDraft.js
new file mode 100644
index 0000000000..995d462fc5
--- /dev/null
+++ b/client/src/hooks/useFieldDraft.js
@@ -0,0 +1,28 @@
+// Local draft buffer that commits on blur. Bible-editor inputs buffer
+// keystrokes locally so a textarea keystroke doesn't fire a universe-wide
+// round-trip per character. `onChange` accepts either a synthetic event or
+// a raw string. `onBlur` is a no-op when the draft equals the persisted
+// value, so a focus-without-edit doesn't fire a redundant PATCH. Persisted
+// `null`/`undefined` coerces to `''` so the input doesn't flip between
+// controlled and uncontrolled.
+import { useState } from 'react';
+
+export default function useFieldDraft(persisted, onCommit) {
+ const [draft, setDraft] = useState(undefined);
+ const persistedStr = persisted == null ? '' : String(persisted);
+ const value = draft !== undefined ? draft : persistedStr;
+
+ const onChange = (e) => {
+ const next = e && e.target ? e.target.value : e;
+ setDraft(next);
+ };
+
+ const onBlur = () => {
+ if (draft === undefined) return;
+ if (draft === persistedStr) { setDraft(undefined); return; }
+ onCommit(draft);
+ setDraft(undefined);
+ };
+
+ return { value, onChange, onBlur };
+}
diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.js
new file mode 100644
index 0000000000..f0b2dc0ba8
--- /dev/null
+++ b/client/src/lib/bibleLimits.js
@@ -0,0 +1,67 @@
+// Client mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. Enforced by
+// `server/lib/storyBible.test.js` "client mirror" suite — if you update one
+// side, update the other and the drift test passes.
+export const BIBLE_LIMITS = Object.freeze({
+ NAME_MAX: 200,
+ ROLE_MAX: 200,
+ ALIAS_MAX: 100,
+ ALIASES_PER_ENTRY_MAX: 12,
+ PHYSICAL_DESCRIPTION_MAX: 2000,
+ PERSONALITY_MAX: 2000,
+ BACKGROUND_MAX: 2000,
+ NOTES_MAX: 4000,
+ IMAGE_REF_MAX: 500,
+ IMAGE_REFS_PER_ENTRY_MAX: 12,
+ PRONOUNS_MAX: 60,
+ AGE_MAX: 80,
+ CORE_THEME_MAX: 500,
+ SPEECH_ACCENT_MAX: 500,
+ VISUAL_NOTES_MAX: 1000,
+ SILHOUETTE_NOTES_MAX: 2000,
+ POSTURE_NOTES_MAX: 1000,
+ SPECIAL_TRAITS_MAX: 2000,
+ VISUAL_IDENTITY_MAX: 1000,
+ MOTIVATIONS_MAX: 2000,
+ LIKES_MAX: 1500,
+ DISLIKES_MAX: 1500,
+ MANNERISMS_MAX: 1500,
+ RELATIONSHIPS_MAX: 2000,
+ SKILLS_MAX: 2000,
+ STAT_LABEL_MAX: 80,
+ STAT_VALUE_MAX: 200,
+ STATS_PER_CHARACTER_MAX: 30,
+ COLOR_NAME_MAX: 80,
+ COLOR_HEX_MAX: 10,
+ COLOR_ROLE_MAX: 120,
+ COLORS_PER_PALETTE_MAX: 12,
+ PROP_NAME_MAX: 120,
+ PROP_PURPOSE_MAX: 400,
+ PROP_MATERIALS_MAX: 200,
+ PROP_NOTES_MAX: 600,
+ PROPS_PER_CHARACTER_MAX: 12,
+ EXPRESSION_NAME_MAX: 80,
+ EXPRESSION_DESC_MAX: 400,
+ EXPRESSIONS_PER_CHARACTER_MAX: 16,
+ GESTURE_NAME_MAX: 80,
+ GESTURE_DESC_MAX: 300,
+ GESTURES_PER_CHARACTER_MAX: 12,
+ WARDROBE_NAME_MAX: 120,
+ WARDROBE_DESCRIPTION_MAX: 800,
+ WARDROBES_PER_CHARACTER_MAX: 10,
+ EVIDENCE_ITEM_MAX: 500,
+ EVIDENCE_PER_ENTRY_MAX: 20,
+ SLUGLINE_MAX: 200,
+ PALETTE_MAX: 200,
+ ERA_MAX: 200,
+ WEATHER_MAX: 200,
+ RECURRING_DETAILS_MAX: 1000,
+ PLACE_DESCRIPTION_MAX: 2000,
+ OBJECT_DESCRIPTION_MAX: 2000,
+ SIGNIFICANCE_MAX: 1000,
+ ENTRIES_PER_BIBLE_MAX: 200,
+ PROMPT_MAX: 2000,
+ TAG_MAX: 60,
+ TAGS_PER_ENTRY_MAX: 12,
+ SOURCE_SERIES_ID_MAX: 64,
+ VOICE_ID_MAX: 200,
+});
diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.js
index e2c4ce1e3b..7517efc3f6 100644
--- a/server/lib/canonPrompt.js
+++ b/server/lib/canonPrompt.js
@@ -212,3 +212,66 @@ export function hasCanonDescriptorContent(kind, entry) {
if (!sequence) return false;
return sequenceHasAnyField(sequence, entry);
}
+
+// Flatteners for character bible list fields — used by the reference-sheet
+// builder and future per-page render prompts so the join logic stays in one
+// place. Each returns `''` when the input is missing/empty.
+export function flattenStats(stats) {
+ if (!Array.isArray(stats) || stats.length === 0) return '';
+ return stats
+ .map((s) => (s?.label && s?.value ? `${s.label}: ${s.value}` : s?.label || ''))
+ .filter(Boolean)
+ .join(' | ');
+}
+
+export function flattenPalette(palette) {
+ if (!Array.isArray(palette) || palette.length === 0) return '';
+ return palette
+ .map((c, i) => {
+ const name = trim(c?.name);
+ const hex = trim(c?.hex);
+ const role = trim(c?.role);
+ if (!name) return '';
+ const hexBit = hex ? ` ${hex}` : '';
+ const roleBit = role ? ` — ${role}` : '';
+ return `Swatch ${i + 1}: ${name}${hexBit}${roleBit}`;
+ })
+ .filter(Boolean)
+ .join(', ');
+}
+
+export function flattenWardrobes(wardrobes) {
+ if (!Array.isArray(wardrobes) || wardrobes.length === 0) return '';
+ return wardrobes
+ .map((w) => (w?.name && w?.description ? `"${w.name}": ${w.description}` : w?.name || ''))
+ .filter(Boolean)
+ .join(' | ');
+}
+
+export function flattenProps(props) {
+ if (!Array.isArray(props) || props.length === 0) return '';
+ return props
+ .map((p) => {
+ const name = trim(p?.name);
+ const purpose = trim(p?.purpose);
+ const materials = trim(p?.materials);
+ if (!name) return '';
+ const bits = [purpose ? `(${purpose})` : '', materials ? `[${materials}]` : '']
+ .filter(Boolean)
+ .join(' ');
+ return bits ? `${name} ${bits}` : name;
+ })
+ .filter(Boolean)
+ .join(' | ');
+}
+
+// `defaults` is consulted when the entry has no items at all — keeps the
+// reference-sheet prompt's expression / hand-gesture panels populated even
+// when the bible omitted them. Caps at 7 entries so the rendered sheet
+// stays legible across providers (codex/local both honor the cap).
+export function flattenNamedList(items, defaults) {
+ const list = Array.isArray(items) && items.length > 0
+ ? items.map((e) => (e?.name && e?.description ? `${e.name} (${e.description})` : trim(e?.name))).filter(Boolean)
+ : [...defaults];
+ return list.slice(0, 7).join(', ');
+}
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 7da90c04e3..e4234a3cfa 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -450,6 +450,20 @@ export function getDateString(date = new Date()) {
*/
export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+/**
+ * Truncate an id to a fixed prefix for human-readable log lines. Null-safe
+ * so callers can pass a possibly-missing field directly (`shortId(run?.id)`)
+ * without an outer truthiness check.
+ *
+ * @param {*} id - id-like value; coerced to string
+ * @param {number} [n=8] - prefix length
+ * @returns {string} prefix of length `n`, or `''` when `id` is null/undefined
+ */
+export function shortId(id, n = 8) {
+ if (id == null) return '';
+ return String(id).slice(0, n);
+}
+
/**
* Safely parse a date value to epoch milliseconds.
* Returns 0 for invalid/missing dates instead of NaN.
@@ -606,78 +620,120 @@ export function assertSafeFilename(filename, { extensions, subject = 'filename',
}
/**
- * Resolve a user-supplied gallery image filename to an absolute path under
- * `PATHS.images`. Returns `null` on any failure so callers can decide whether
- * to throw, log-and-skip, or substitute a fallback.
+ * Build a single-root path resolver that returns a function with the same
+ * signature as `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset`.
*
- * Defense in depth:
+ * Defense in depth (applied on every call):
* 1. `basename()` strips dirs (so `../../etc/passwd` → `passwd`).
* 2. Reject `.`/`..`/empty basenames outright.
- * 3. `resolve` + `startsWith(imagesRoot)` so unicode tricks can't escape.
- * 4. When `mustExist`, `statSync({ throwIfNoEntry: false }).isFile()` rejects
- * directories (the images root itself would otherwise pass an existsSync
- * check and flow into ffmpeg as an "image path" where it'd fail in
- * confusing ways). Note: `statSync` follows symlinks, so a symlink inside
- * `data/images/` pointing to a regular file outside the gallery still
- * passes. PortOS is single-user (see CLAUDE.md "Security Model") so we
- * accept that — if you need to reject symlinks too, use `lstatSync`.
- *
- * Pass `{ mustExist: false }` for code paths that intentionally skip the
- * existence check (e.g. when the path is resolved at request time but read
- * later — TOCTOU between resolve and use isn't worth the extra syscall, and
- * the downstream renderer surfaces a clear error if the file vanished).
- *
- * @param {string} name - Filename to resolve (basenamed internally)
+ * 3. `resolve` + `startsWith(rootPrefix)` so unicode tricks can't escape.
+ * 4. Optional extension allow-list (case-insensitive) before any FS syscall.
+ * 5. When `mustExist`, `statSync({ throwIfNoEntry: false }).isFile()` rejects
+ * directories (the root itself would otherwise pass an existsSync check
+ * and flow into ffmpeg / image-gen as an "image path" where it'd fail in
+ * confusing ways). Note: `statSync` follows symlinks, so a symlink under
+ * the root pointing to a regular file outside still passes. PortOS is
+ * single-user (see CLAUDE.md "Security Model") so we accept that — for
+ * symlink rejection, swap to `lstatSync`.
+ *
+ * Pass `{ mustExist: false }` at call time for code paths that intentionally
+ * skip the existence check (e.g. when the path is resolved at request time
+ * but read later — TOCTOU between resolve and use isn't worth the extra
+ * syscall, and the downstream renderer surfaces a clear error if the file
+ * vanished).
+ *
+ * @param {() => string} getRoot - Thunk returning the absolute directory.
+ * A thunk (not a literal) so tests that mutate `PATHS.x` at mock-eval
+ * time still steer the resolver — the value is captured on first call
+ * and cached thereafter (recomputed only if the thunk later returns a
+ * different value, which production code never does).
* @param {object} [opts]
- * @param {boolean} [opts.mustExist=true] - Require the resolved path to be an existing regular file
- * @returns {string|null} Absolute path inside PATHS.images, or null
+ * @param {string[]} [opts.extensions] - allowed extensions WITHOUT the leading
+ * dot (`['png', 'jpg', 'jpeg', 'webp']`). When omitted, all extensions are
+ * accepted (matches the legacy gallery/refs behavior — extension checks
+ * happen elsewhere on those paths).
+ * @param {boolean} [opts.cache=false] - Memoize successful resolutions. Only
+ * safe for shipped/stable assets (templates) where the basename → path
+ * binding is stable for the process lifetime; never enable for user-mutable
+ * dirs (gallery, refs) since deletions would be masked.
+ * @returns {(name: string, opts?: { mustExist?: boolean }) => string|null}
*/
-export function resolveGalleryImage(name, { mustExist = true } = {}) {
- if (typeof name !== 'string' || !name) return null;
- const safe = basename(name);
- if (!safe || safe === '.' || safe === '..') return null;
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.images, safe));
- if (!localPath.startsWith(imagesRoot)) return null;
- if (!mustExist) return localPath;
- // throwIfNoEntry:false swallows ENOENT but not EACCES / transient I/O —
- // treat those as "not a valid gallery reference" too rather than bubbling
- // a 500 out of the route layer.
- try {
- const stat = statSync(localPath, { throwIfNoEntry: false });
- return stat?.isFile() ? localPath : null;
- } catch {
- return null;
+export function makePathResolver(getRoot, { extensions, cache = false } = {}) {
+ if (typeof getRoot !== 'function') {
+ throw new Error('makePathResolver: getRoot must be a function returning the root dir');
}
+ const extRegex = Array.isArray(extensions) && extensions.length > 0
+ ? new RegExp(`\\.(${extensions.map((e) => String(e).replace(/^\./, '')).join('|')})$`, 'i')
+ : null;
+ const memo = cache ? new Map() : null;
+ // Resolved-root cache so the hot path doesn't re-run `resolvePath(root) +
+ // PATH_SEP` per call. Recomputes only when `getRoot()` returns a different
+ // value — picks up test-time `PATHS.x = ...` mutation on first call, then
+ // stays warm for the rest of the process.
+ let _root = null;
+ let _rootAbsPrefix = null;
+
+ return (name, { mustExist = true } = {}) => {
+ if (typeof name !== 'string' || !name) return null;
+ const safe = basename(name);
+ if (!safe || safe === '.' || safe === '..') return null;
+ if (extRegex && !extRegex.test(safe)) return null;
+ const cacheKey = memo ? (mustExist ? `must:${safe}` : `nostat:${safe}`) : null;
+ if (memo && memo.has(cacheKey)) return memo.get(cacheKey);
+ const root = getRoot();
+ if (root !== _root) {
+ _root = root;
+ _rootAbsPrefix = resolvePath(root) + PATH_SEP;
+ }
+ const localPath = resolvePath(join(root, safe));
+ if (!localPath.startsWith(_rootAbsPrefix)) return null;
+ if (!mustExist) {
+ if (memo) memo.set(cacheKey, localPath);
+ return localPath;
+ }
+ // throwIfNoEntry:false swallows ENOENT but not EACCES / transient I/O —
+ // treat those as "not a valid reference" too rather than bubbling a 500
+ // out of the route layer.
+ let resolved = null;
+ try {
+ const stat = statSync(localPath, { throwIfNoEntry: false });
+ resolved = stat?.isFile() ? localPath : null;
+ } catch { /* falls through to null */ }
+ // Only cache successful resolutions — a missing-then-installed asset
+ // should pick up on the next call (e.g. setup-data.js racing a render).
+ if (memo && resolved) memo.set(cacheKey, resolved);
+ return resolved;
+ };
}
+/**
+ * Resolve a user-supplied gallery image filename to an absolute path under
+ * `PATHS.images`. Returns `null` on any failure so callers can decide whether
+ * to throw, log-and-skip, or substitute a fallback. See `makePathResolver`
+ * for the defense-in-depth checks. Late-binds via a thunk so tests that
+ * mutate `PATHS.images` at mock-eval time still steer the resolver.
+ */
+export const resolveGalleryImage = makePathResolver(() => PATHS.images);
+
/**
* Resolve a user-supplied reference-image filename to an absolute path under
* `PATHS.imageRefs`. Multi-reference uploads land in a sibling dir to keep
- * them out of the gallery enumeration; this helper enforces the same
- * defense-in-depth checks as `resolveGalleryImage` but anchored at the refs
- * root.
- *
- * @param {string} name - Filename to resolve (basenamed internally)
- * @param {object} [opts]
- * @param {boolean} [opts.mustExist=true] - Require the resolved path to be an existing regular file
- * @returns {string|null} Absolute path inside PATHS.imageRefs, or null
+ * them out of the gallery enumeration; same defense-in-depth as the gallery
+ * resolver but anchored at the refs root.
*/
-export function resolveImageRef(name, { mustExist = true } = {}) {
- if (typeof name !== 'string' || !name) return null;
- const safe = basename(name);
- if (!safe || safe === '.' || safe === '..') return null;
- const refsRoot = resolvePath(PATHS.imageRefs) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.imageRefs, safe));
- if (!localPath.startsWith(refsRoot)) return null;
- if (!mustExist) return localPath;
- try {
- const stat = statSync(localPath, { throwIfNoEntry: false });
- return stat?.isFile() ? localPath : null;
- } catch {
- return null;
- }
-}
+export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);
+
+/**
+ * Resolve a shipped visual template filename (e.g. character reference-sheet
+ * layout PNG) to an absolute path under `PATHS.visualTemplates`. Caches
+ * successful resolutions because the template assets are shipped and stable
+ * for the lifetime of the process — keeps reference-sheet rendering off the
+ * statSync hot path.
+ */
+export const resolveTemplateAsset = makePathResolver(() => PATHS.visualTemplates, {
+ extensions: ['png', 'jpg', 'jpeg', 'webp'],
+ cache: true,
+});
/**
* Resolve any user-supplied image input (init image OR multi-reference image)
@@ -686,13 +742,7 @@ export function resolveImageRef(name, { mustExist = true } = {}) {
* or the shipped visual-template dir (`PATHS.visualTemplates`). Used by the
* image-gen runner to re-validate paths that originated from internal
* features (gallery picks, reference-sheet renders) which may legitimately
- * cross dir boundaries — a portrait pinned from the gallery passed as a
- * multi-ref input, a template PNG used as an init-image anchor.
- *
- * The defense-in-depth checks (basename strip, traversal block, root prefix,
- * existence + isFile gate) apply at each candidate root just like the
- * single-root resolvers (`resolveGalleryImage`, `resolveImageRef`,
- * `resolveTemplateAsset`).
+ * cross dir boundaries.
*
* Accepts both basename input (`"foo.png"`) and already-resolved absolute
* paths (the local image-gen runner re-validates the same input on every
@@ -701,6 +751,15 @@ export function resolveImageRef(name, { mustExist = true } = {}) {
* @param {string} rawPath - basename or absolute path
* @returns {string|null} validated absolute path, or null
*/
+// Module-load prefixes — PATHS.* values don't change at runtime, so
+// `resolvePath() + PATH_SEP` is computed once instead of every call. Each
+// entry pairs the prefix to its matching resolver for the dispatch loop.
+const IMAGE_INPUT_ROOTS = [
+ [resolvePath(PATHS.images) + PATH_SEP, resolveGalleryImage],
+ [resolvePath(PATHS.imageRefs) + PATH_SEP, resolveImageRef],
+ [resolvePath(PATHS.visualTemplates) + PATH_SEP, resolveTemplateAsset],
+];
+
export function resolveImageInputPath(rawPath) {
if (typeof rawPath !== 'string' || !rawPath) return null;
// For ABSOLUTE inputs, dispatch by prefix. The single-root resolvers
@@ -708,69 +767,20 @@ export function resolveImageInputPath(rawPath) {
// absolute path can silently redirect a `/data/templates/foo.png` input
// to `/data/images/foo.png` whenever a same-named file lives in the gallery.
// Validate against the matching root only.
- const ROOTS = [
- [PATHS.images, resolveGalleryImage],
- [PATHS.imageRefs, resolveImageRef],
- [PATHS.visualTemplates, resolveTemplateAsset],
- ];
const resolvedInput = resolvePath(rawPath);
- for (const [rootDir, resolver] of ROOTS) {
- const rootPrefix = resolvePath(rootDir) + PATH_SEP;
+ for (const [rootPrefix, resolver] of IMAGE_INPUT_ROOTS) {
if (resolvedInput.startsWith(rootPrefix)) return resolver(rawPath);
}
// For basename / relative input (no matching prefix), fall through the
// resolvers in order. First match wins; basename collisions across roots
// are accepted as ambiguous and resolve to the first defined root.
- for (const [, resolver] of ROOTS) {
+ for (const [, resolver] of IMAGE_INPUT_ROOTS) {
const candidate = resolver(rawPath);
if (candidate) return candidate;
}
return null;
}
-/**
- * Resolve a shipped visual template filename (e.g. character reference-sheet
- * layout PNG) to an absolute path under `PATHS.visualTemplates`. Mirrors
- * `resolveImageRef` / `resolveGalleryImage`: basename + traversal + root-prefix
- * + existence checks. Allows PNG/JPG/JPEG/WEBP since the template assets are
- * shipped image files.
- *
- * @param {string} name - Filename (basenamed internally)
- * @param {object} [opts]
- * @param {boolean} [opts.mustExist=true] - Require an existing regular file
- * @returns {string|null} Absolute path inside PATHS.visualTemplates, or null
- */
-// Templates are shipped assets — once a basename resolves to a file the path
-// is stable for the lifetime of the process, so cache the result. This stays
-// off the hot path of every reference-sheet render without sacrificing the
-// defense-in-depth basename + traversal + extension checks.
-const _templateAssetCache = new Map();
-export function resolveTemplateAsset(name, { mustExist = true } = {}) {
- if (typeof name !== 'string' || !name) return null;
- const safe = basename(name);
- if (!safe || safe === '.' || safe === '..') return null;
- const lower = safe.toLowerCase();
- if (!/\.(png|jpg|jpeg|webp)$/.test(lower)) return null;
- const cacheKey = mustExist ? `must:${safe}` : `nostat:${safe}`;
- if (_templateAssetCache.has(cacheKey)) return _templateAssetCache.get(cacheKey);
- const root = resolvePath(PATHS.visualTemplates) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.visualTemplates, safe));
- if (!localPath.startsWith(root)) return null;
- if (!mustExist) {
- _templateAssetCache.set(cacheKey, localPath);
- return localPath;
- }
- let resolved = null;
- try {
- const stat = statSync(localPath, { throwIfNoEntry: false });
- resolved = stat?.isFile() ? localPath : null;
- } catch { /* falls through to null */ }
- // Only cache successful resolutions — a missing-then-installed template
- // should pick up on the next call (e.g. setup-data.js races a render).
- if (resolved) _templateAssetCache.set(cacheKey, resolved);
- return resolved;
-}
-
/**
* List a directory, keep entries whose extension matches `extensions`, stat
* each, and project the survivors through `mapEntry(name, fullPath, stat)`.
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index fb2395c9b9..b7ffde1a30 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -1001,3 +1001,13 @@ describe('storyBible — createBibleStore (multi-primary-field kind / settings)'
).rejects.toThrow(/already exists/i);
});
});
+
+describe('BIBLE_LIMITS client mirror', () => {
+ it('matches client/src/lib/bibleLimits.js verbatim', async () => {
+ // The client mirror at `client/src/lib/bibleLimits.js` exists so the
+ // CharacterDetailEditor's `max:` literals can't drift from the server
+ // sanitizer caps. If this fails, update the client file to match.
+ const clientMirror = await import('../../client/src/lib/bibleLimits.js');
+ expect(clientMirror.BIBLE_LIMITS).toEqual(BIBLE_LIMITS);
+ });
+});
diff --git a/server/routes/sdapi.js b/server/routes/sdapi.js
index 97f3a00064..bd2f84f7a2 100644
--- a/server/routes/sdapi.js
+++ b/server/routes/sdapi.js
@@ -24,35 +24,20 @@ import { PATHS } from '../lib/fileUtils.js';
import { getSettings } from '../services/settings.js';
import { generateImage, getMode, getActiveJob } from '../services/imageGen/index.js';
import { local as localImage } from '../services/imageGen/index.js';
-import { imageGenEvents } from '../services/imageGenEvents.js';
+import { createImageGenWaiter } from '../services/imageGenWaiter.js';
import { listVideoModels, defaultVideoModelId } from '../services/videoGen/local.js';
const router = Router();
-// Build a completion waiter for a future generationId. Listeners attach
-// immediately so a fast Python child can't emit 'completed' before we're
-// listening, but the id-match check uses a registered id (set by .register()
-// once generateImage returns). 5-minute timeout matches the external client.
-// The returned `cleanup()` is exposed so the caller can detach listeners
-// even if generateImage throws before we ever resolve/reject.
+// `onTimeout` + `onFailed` map the shared waiter's rejections onto the
+// ServerError shape sdapi routes need; centralized middleware surfaces the
+// status + code on the HTTP response.
function createCompletionWaiter() {
- let registeredId = null;
- let resolve, reject;
- // Swallow the unhandled-rejection if the caller never awaits .promise
- // (e.g. generateImage throws and the route exits via the error path).
- const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
- promise.catch(() => {});
- const onComplete = (ev) => { if (ev.generationId === registeredId) { cleanup(); resolve(ev); } };
- const onFailed = (ev) => { if (ev.generationId === registeredId) { cleanup(); reject(new ServerError(ev.error || 'Generation failed', { status: 500, code: 'GEN_FAILED' })); } };
- const timer = setTimeout(() => { cleanup(); reject(new ServerError('Generation timed out', { status: 504, code: 'GEN_TIMEOUT' })); }, 5 * 60 * 1000);
- const cleanup = () => {
- clearTimeout(timer);
- imageGenEvents.off('completed', onComplete);
- imageGenEvents.off('failed', onFailed);
- };
- imageGenEvents.on('completed', onComplete);
- imageGenEvents.on('failed', onFailed);
- return { register: (id) => { registeredId = id; }, promise, cleanup };
+ return createImageGenWaiter({
+ timeoutMs: 5 * 60 * 1000,
+ onTimeout: () => new ServerError('Generation timed out', { status: 504, code: 'GEN_TIMEOUT' }),
+ onFailed: (ev) => new ServerError(ev?.error || 'Generation failed', { status: 500, code: 'GEN_FAILED' }),
+ });
}
const ensureExposed = async () => {
diff --git a/server/services/imageGenWaiter.js b/server/services/imageGenWaiter.js
new file mode 100644
index 0000000000..a643f9e469
--- /dev/null
+++ b/server/services/imageGenWaiter.js
@@ -0,0 +1,52 @@
+/**
+ * Shared completion waiter for `imageGenEvents` — used wherever a route or
+ * voice tool awaits a single image-gen job by `generationId`. Two contracts
+ * the helper enforces: (1) listeners attach BEFORE `generateImage` returns
+ * so a fast job can't emit `completed` first, and (2) listeners detach on
+ * completion / failure / timeout so the global emitter doesn't accumulate
+ * leaks. Always call `cleanup()` on the synchronous error path — `register`
+ * may never run.
+ *
+ * Routes route both the timeout AND the failed-event payload through
+ * caller-supplied factories so the rejection lands as a `ServerError` with
+ * the right status/code; the voice tool keeps the raw `{ error }` envelope.
+ *
+ * Scoped to the `imageGenEvents` bus. The `mediaJobQueue` / `mediaJobEvents`
+ * pattern in `universeCharacterSheet.js` uses a custom dispatcher to bound
+ * listeners + a two-stage timeout — distinct enough that it stays separate.
+ */
+import { imageGenEvents } from './imageGenEvents.js';
+
+export function createImageGenWaiter({
+ timeoutMs = 5 * 60 * 1000,
+ onTimeout = () => ({ error: 'image generation timed out' }),
+ // Mapper applied to the raw `failed` event before the promise rejects.
+ // Defaults to the event verbatim (legacy voice-tool shape); routes pass
+ // a `(ev) => new ServerError(...)` for a typed rejection.
+ onFailed = (ev) => ev,
+} = {}) {
+ let registeredId = null;
+ let resolve, reject;
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
+ promise.catch(() => {});
+
+ const onCompletedEvent = (ev) => { if (ev?.generationId === registeredId) { cleanup(); resolve(ev); } };
+ const onFailedEvent = (ev) => { if (ev?.generationId === registeredId) { cleanup(); reject(onFailed(ev)); } };
+
+ const timer = setTimeout(() => { cleanup(); reject(onTimeout()); }, timeoutMs);
+
+ const cleanup = () => {
+ clearTimeout(timer);
+ imageGenEvents.off('completed', onCompletedEvent);
+ imageGenEvents.off('failed', onFailedEvent);
+ };
+
+ imageGenEvents.on('completed', onCompletedEvent);
+ imageGenEvents.on('failed', onFailedEvent);
+
+ return {
+ register: (id) => { registeredId = id; },
+ promise,
+ cleanup,
+ };
+}
diff --git a/server/services/pipeline/refineHelpers.js b/server/services/pipeline/refineHelpers.js
index 26c5c485ef..c5dd901092 100644
--- a/server/services/pipeline/refineHelpers.js
+++ b/server/services/pipeline/refineHelpers.js
@@ -1,20 +1,17 @@
import { runStagedLLM } from '../../lib/stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
-// Shared scaffolding for every pipeline LLM refine path (comic-panel,
-// storyboard-scene, character-physicalDescription). Owns the runStagedLLM call,
-// the empty-result guard, the changes-array shaping, and the runId log. Callers
-// pass `resultField` (e.g. 'prompt' or 'physicalDescription') so this helper
-// stays prompt-agnostic.
-export async function runPromptRefine({
+// Pass `logTag: null` to suppress the default runId log so a caller that
+// needs a context-rich line (e.g. universeCharacterExpand wants the
+// field-count) can emit its own after the post-merge state is known.
+export async function runPromptRefineRaw({
templateName,
variables,
options = {},
source,
logTag,
- resultField = 'prompt',
- emptyError = { code: 'PIPELINE_PROMPT_REFINE_EMPTY', message: 'LLM returned an empty refined prompt' },
- changesLimit = 8,
+ emptyError = { code: 'PIPELINE_PROMPT_REFINE_EMPTY', message: 'LLM returned an empty payload' },
+ validateContent,
}) {
const result = await runStagedLLM(templateName, variables, {
providerOverride: options.providerId,
@@ -22,16 +19,40 @@ export async function runPromptRefine({
returnsJson: true,
source,
});
- const refined = (result.content?.[resultField] || '').trim();
- if (!refined) {
+ const content = result.content;
+ // Reject array AND non-object — `typeof [] === 'object'` would otherwise
+ // let an LLM that returned `[{...}]` slip through downstream merges as a
+ // valid-but-empty payload (no string keys match) and silently no-op.
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });
}
- const changes = Array.isArray(result.content?.changes)
- ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, changesLimit)
+ if (validateContent) validateContent(content);
+ const rationale = typeof content.rationale === 'string' ? content.rationale.trim() : '';
+ if (logTag) {
+ console.log(`✨ ${logTag} runId=${(result.runId || '').slice(0, 8)}`);
+ }
+ return { content, rationale, runId: result.runId, providerId: result.providerId, model: result.model };
+}
+
+// Single-field refine wrapper for the comic-panel / storyboard-scene /
+// character-physicalDescription paths. `resultField` keeps the helper
+// prompt-agnostic; `changes` are trimmed + capped on the way out.
+export async function runPromptRefine({
+ resultField = 'prompt',
+ emptyError = { code: 'PIPELINE_PROMPT_REFINE_EMPTY', message: 'LLM returned an empty refined prompt' },
+ changesLimit = 8,
+ ...rest
+}) {
+ const validateContent = (c) => {
+ const refined = (c?.[resultField] || '').trim();
+ if (!refined) {
+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });
+ }
+ };
+ const { content, ...meta } = await runPromptRefineRaw({ ...rest, validateContent, emptyError });
+ const refined = String(content[resultField]).trim();
+ const changes = Array.isArray(content.changes)
+ ? content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, changesLimit)
: [];
- const rationale = typeof result.content?.rationale === 'string'
- ? result.content.rationale.trim()
- : '';
- console.log(`✨ ${logTag} runId=${(result.runId || '').slice(0, 8)}`);
- return { refined, changes, rationale, runId: result.runId, providerId: result.providerId, model: result.model };
+ return { refined, changes, ...meta };
}
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index c6a68a4c00..6315aa3671 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -12,6 +12,7 @@ import {
import { runStagedLLM } from '../lib/stageRunner.js';
import { runPromptRefine } from './pipeline/refineHelpers.js';
import { ServerError } from '../lib/errorHandler.js';
+import { shortId } from '../lib/fileUtils.js';
export const peerForPrompt = (entry) => ({
id: entry.id,
@@ -123,7 +124,7 @@ export async function refineUniverseCharacter(universeId, entryId, options = {})
},
options,
source: 'universe-character-refine',
- logTag: `Universe character refine — universe=${universeId.slice(0, 8)} entry=${entryId.slice(0, 8)}`,
+ logTag: `Universe character refine — universe=${shortId(universeId)} entry=${shortId(entryId)}`,
resultField: 'physicalDescription',
emptyError: { code: 'UNIVERSE_CANON_REFINE_EMPTY', message: 'LLM returned an empty physicalDescription' },
changesLimit: 12,
@@ -209,7 +210,7 @@ export async function differentiateUniverseCast(universeId, options = {}) {
const updated = await updateUniverse(universeId, { characters: nextList });
const rationale = typeof result.content?.rationale === 'string' ? result.content.rationale.trim() : '';
- console.log(`✨ Universe cast differentiate — universe=${universeId.slice(0, 8)} touched=${touched}/${list.length} skippedLocked=${skippedLocked} runId=${(result.runId || '').slice(0, 8)}`);
+ console.log(`✨ Universe cast differentiate — universe=${shortId(universeId)} touched=${touched}/${list.length} skippedLocked=${skippedLocked} runId=${shortId(result.runId)}`);
return {
universe: updated,
touched,
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index f35d509486..046133fd5c 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -9,6 +9,7 @@ vi.mock('../lib/fileUtils.js', () => ({
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+ shortId: (id, n = 8) => (id == null ? '' : String(id).slice(0, n)),
}));
let uuidCounter = 0;
diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.js
index 186ba2d098..3a29d6e905 100644
--- a/server/services/universeCharacterExpand.js
+++ b/server/services/universeCharacterExpand.js
@@ -13,9 +13,10 @@
import { getUniverse, updateUniverse } from './universeBuilder.js';
import { buildStyleClause } from './universeCanon.js';
-import { runStagedLLM } from '../lib/stageRunner.js';
+import { runPromptRefineRaw } from './pipeline/refineHelpers.js';
import { ServerError } from '../lib/errorHandler.js';
import { sanitizeCharacter } from '../lib/storyBible.js';
+import { shortId } from '../lib/fileUtils.js';
// Adding a new extended field on `sanitizeCharacter` requires adding it here
// too — otherwise the expand response key is silently dropped.
@@ -104,31 +105,23 @@ export async function expandUniverseCharacter(universeId, entryId, options = {})
}
const peers = list.filter((_, i) => i !== idx);
- const { content, runId, providerId, model } = await runStagedLLM(
- 'universe-character-expand',
- {
+ // logTag: null — emit a context-rich log AFTER the merge so universeId,
+ // entryId, and the field count are all available.
+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({
+ templateName: 'universe-character-expand',
+ variables: {
styleClause: buildStyleClause(universe),
characterJson: JSON.stringify(target),
peersJson: JSON.stringify(peers.map(peerForExpandPrompt)),
},
- {
- providerOverride: options.providerId,
- modelOverride: options.model,
- returnsJson: true,
- source: 'universe-character-expand',
+ options: { providerId: options.providerId, model: options.model },
+ source: 'universe-character-expand',
+ logTag: null,
+ emptyError: {
+ code: 'UNIVERSE_CHARACTER_EXPAND_EMPTY',
+ message: 'LLM returned an empty character expansion',
},
- );
-
- // Reject array AND non-object — `typeof [] === 'object'` would otherwise
- // let an LLM that returned `[{...}]` slip through `applyExpansion` as a
- // valid-but-empty payload (no string keys match) and silently no-op.
- if (!content || typeof content !== 'object' || Array.isArray(content)) {
- throw new ServerError('LLM returned an empty character expansion', {
- status: 502, code: 'UNIVERSE_CHARACTER_EXPAND_EMPTY',
- });
- }
-
- const rationale = typeof content.rationale === 'string' ? content.rationale.trim() : '';
+ });
// Re-derive the merge INSIDE the write queue against the freshest persisted
// universe so a user edit (or another LLM call) that landed during the
@@ -163,7 +156,7 @@ export async function expandUniverseCharacter(universeId, entryId, options = {})
if (updatedFields.length === 0) {
return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };
}
- console.log(`✨ Universe character expand — universe=${universeId.slice(0, 8)} entry=${entryId.slice(0, 8)} fields=${updatedFields.length} runId=${(runId || '').slice(0, 8)}`);
+ console.log(`✨ Universe character expand — universe=${shortId(universeId)} entry=${shortId(entryId)} fields=${updatedFields.length} runId=${shortId(runId)}`);
return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };
}
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index 50caee5b35..0b28fb21b0 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -16,7 +16,7 @@
import { copyFile } from 'fs/promises';
import { join, basename } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, shortId } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import { getSettings } from './settings.js';
import { getUniverse, updateUniverse } from './universeBuilder.js';
@@ -24,6 +24,9 @@ import { buildStyleClause } from './universeCanon.js';
import { getImageModels } from '../lib/mediaModels.js';
import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';
import { findOrCreateUniverseCollection } from './mediaCollections.js';
+import {
+ flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,
+} from '../lib/canonPrompt.js';
// 2048×1536 keeps panel labels legible while still rendering in a single
// pass on Apple Silicon local backends. Codex / nano-banana ignore the
@@ -56,62 +59,6 @@ const DEFAULT_HAND_GESTURES = Object.freeze([
const trim = (s) => (typeof s === 'string' ? s.trim() : '');
-const flattenStats = (stats) => {
- if (!Array.isArray(stats) || stats.length === 0) return '';
- return stats
- .map((s) => (s?.label && s?.value ? `${s.label}: ${s.value}` : s?.label || ''))
- .filter(Boolean)
- .join(' | ');
-};
-
-const flattenPalette = (palette) => {
- if (!Array.isArray(palette) || palette.length === 0) return '';
- return palette
- .map((c, i) => {
- const name = trim(c?.name);
- const hex = trim(c?.hex);
- const role = trim(c?.role);
- if (!name) return '';
- const hexBit = hex ? ` ${hex}` : '';
- const roleBit = role ? ` — ${role}` : '';
- return `Swatch ${i + 1}: ${name}${hexBit}${roleBit}`;
- })
- .filter(Boolean)
- .join(', ');
-};
-
-const flattenWardrobes = (wardrobes) => {
- if (!Array.isArray(wardrobes) || wardrobes.length === 0) return '';
- return wardrobes
- .map((w) => (w?.name && w?.description ? `"${w.name}": ${w.description}` : w?.name || ''))
- .filter(Boolean)
- .join(' | ');
-};
-
-const flattenProps = (props) => {
- if (!Array.isArray(props) || props.length === 0) return '';
- return props
- .map((p) => {
- const name = trim(p?.name);
- const purpose = trim(p?.purpose);
- const materials = trim(p?.materials);
- if (!name) return '';
- const bits = [purpose ? `(${purpose})` : '', materials ? `[${materials}]` : '']
- .filter(Boolean)
- .join(' ');
- return bits ? `${name} ${bits}` : name;
- })
- .filter(Boolean)
- .join(' | ');
-};
-
-const flattenNamedList = (items, defaults) => {
- const list = Array.isArray(items) && items.length > 0
- ? items.map((e) => (e?.name && e?.description ? `${e.name} (${e.description})` : trim(e?.name))).filter(Boolean)
- : [...defaults];
- return list.slice(0, 7).join(', ');
-};
-
/**
* Build the prompt + render options for one character's reference sheet.
* Pure function — does no I/O, doesn't enqueue anything. The route handler
@@ -210,7 +157,7 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
// "live" sheet pointer on the character (`referenceSheetImageRef`) always
// names the newest, but older files stay on disk for rollback.
const sheetFilename = (universeId, characterId, generationId) =>
- `universe-${String(universeId).slice(0, 8)}-${String(characterId).slice(0, 8)}-sheet-${String(generationId).slice(0, 8)}.png`;
+ `universe-${shortId(universeId)}-${shortId(characterId)}-sheet-${shortId(generationId)}.png`;
// `(universeId, characterId) → latest generationId requested`. When a new
// render starts for a character it claims the slot; when a render completes,
@@ -381,7 +328,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
const armTimeout = (ms, reason) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(() => {
- console.log(`⏱️ Character sheet render ${reason} [${jobId.slice(0, 8)}] — detaching`);
+ console.log(`⏱️ Character sheet render ${reason} [${shortId(jobId)}] — detaching`);
detach();
}, ms);
timeoutHandle.unref?.();
@@ -396,7 +343,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
detach();
const sourceFilename = job.result?.filename;
await onSheetComplete({ universeId, entryId, jobId, sourceFilename }).catch((err) => {
- console.error(`❌ Character sheet post-completion failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ console.error(`❌ Character sheet post-completion failed [${shortId(jobId)}]: ${err?.message}`);
});
},
onFailed: (job) => {
@@ -405,7 +352,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
if (_latestPendingByCharacter.get(pendingKey(universeId, entryId)) === jobId) {
_latestPendingByCharacter.delete(pendingKey(universeId, entryId));
}
- console.log(`⚠️ Character sheet render ${job.status} [${jobId.slice(0, 8)}]: ${job.error || 'unknown'}`);
+ console.log(`⚠️ Character sheet render ${job.status} [${shortId(jobId)}]: ${job.error || 'unknown'}`);
},
});
armTimeout(QUEUE_WAIT_MS, 'queue-wait timeout');
@@ -414,7 +361,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// can patch optimistically on SSE completion without a universe refetch.
// onSheetComplete derives the same filename from the same inputs.
const destFilename = sheetFilename(universeId, entryId, jobId);
- console.log(`🎨 Universe character sheet render — universe=${universeId.slice(0, 8)} entry=${entryId.slice(0, 8)} job=${jobId.slice(0, 8)} mode=${activeMode} model=${modelId} position=${queued.position}`);
+ console.log(`🎨 Universe character sheet render — universe=${shortId(universeId)} entry=${shortId(entryId)} job=${shortId(jobId)} mode=${activeMode} model=${modelId} position=${queued.position}`);
return {
jobId,
// `generationId` retained for client back-compat (older clients keyed
@@ -445,7 +392,7 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilena
// an older-but-slower render could overwrite a newer-but-finished pointer.
const key = pendingKey(universeId, entryId);
if (_latestPendingByCharacter.get(key) !== jobId) {
- console.log(`⏭️ Character sheet [${jobId.slice(0, 8)}] superseded by newer render — file saved, pointer not stamped`);
+ console.log(`⏭️ Character sheet [${shortId(jobId)}] superseded by newer render — file saved, pointer not stamped`);
return { filename: destFilename, path: destPath, superseded: true };
}
// Stamp ONLY `referenceSheetImageRef` inside the write queue against the
@@ -480,7 +427,7 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilena
console.log(`⚠️ Character ${entryId} not found post-render — sheet saved but not linked`);
return null;
}
- console.log(`📌 Character ${entryId.slice(0, 8)}.referenceSheetImageRef = ${destFilename}`);
+ console.log(`📌 Character ${shortId(entryId)}.referenceSheetImageRef = ${destFilename}`);
return { filename: destFilename, path: destPath };
}
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 4030c96a9a..5f7a4c03a1 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -15,7 +15,7 @@ import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';
import * as imageGen from '../imageGen/index.js';
-import { imageGenEvents } from '../imageGenEvents.js';
+import { createImageGenWaiter } from '../imageGenWaiter.js';
import { getSettings } from '../settings.js';
import { isDestructiveLabel, buildPending } from './confirmGate.js';
@@ -1317,25 +1317,9 @@ const TOOLS = [
// emit 'completed' before we attach. External backends await the
// upstream HTTP call internally and the file is on disk by the time
// generateImage resolves — wait() is a no-op there.
- let resolveDone, rejectDone;
- const completionPromise = new Promise((res, rej) => { resolveDone = res; rejectDone = rej; });
- let registeredId = null;
- const onCompleted = (ev) => { if (ev.generationId === registeredId) cleanup(resolveDone, ev); };
- const onFailed = (ev) => { if (ev.generationId === registeredId) cleanup(rejectDone, ev); };
- const cleanup = (fn, ev) => {
- clearTimeout(timeout);
- imageGenEvents.off('completed', onCompleted);
- imageGenEvents.off('failed', onFailed);
- fn(ev);
- };
// 5-min cap mirrors the codex provider's own timeout — a stuck job
// shouldn't leak listeners into the voice/palette dispatcher forever.
- const timeout = setTimeout(() => cleanup(rejectDone, { error: 'image generation timed out' }), 5 * 60 * 1000);
- imageGenEvents.on('completed', onCompleted);
- imageGenEvents.on('failed', onFailed);
- // Swallow unhandled rejection if generateImage throws before we
- // register; the catch block below handles it.
- completionPromise.catch(() => {});
+ const waiter = createImageGenWaiter({ timeoutMs: 5 * 60 * 1000 });
let result;
try {
@@ -1347,7 +1331,7 @@ const TOOLS = [
mode: requestedMode,
});
} catch (err) {
- cleanup(() => {}, null);
+ waiter.cleanup();
return { ok: false, summary: `Image generation failed: ${err?.message || err}` };
}
@@ -1355,7 +1339,7 @@ const TOOLS = [
const isAsync = usedMode === 'local' || usedMode === 'codex';
// External resolves with the file already on disk — short-circuit.
if (!isAsync) {
- cleanup(() => {}, null);
+ waiter.cleanup();
return {
ok: true,
path: result?.path,
@@ -1365,8 +1349,8 @@ const TOOLS = [
};
}
- registeredId = result.generationId;
- const ev = await completionPromise.catch((errEv) => ({ __failed: true, ...errEv }));
+ waiter.register(result.generationId);
+ const ev = await waiter.promise.catch((errEv) => ({ __failed: true, ...errEv }));
if (ev?.__failed) {
return { ok: false, summary: `Image generation failed: ${ev.error || 'unknown'}` };
}