Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([purge-reference-sheet-image-ref-on-sheet-delete]): active-purge character.referenceSheetImageRef on sheet delete
[._.]/ Adam Eivy074a80de3917
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5cd350456a..e4a415aa1a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Delete affordance for character reference sheets.** New trash button on `CharacterReferenceSheetPanel` (inline `[Cancel] [Delete sheet]` confirm row) backed by `DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet`. Server unlinks the PNG from `data/image-refs/` and eagerly purges every matching `referenceSheetImageRef` pointer across all universes via a new `purgeReferenceSheetFromAllUniverses(filename)` helper. Locked characters' sheets stay delete-protected (`UNIVERSE_CANON_LOCKED` 409, mirrors the renderer's lock guard).- **Per-stage editorial locks on Pipeline issues.** Each `issue.stages.{id}` now carries a `locked` flag; locked stages refuse regeneration (text generate, image / video enqueue, refine, extract-scenes / extract-pages, audio extract / render, episode-video fresh start, cover-concepts commit). UI exposes a lock toggle on every Pipeline Issue tab and renders a per-stage Lock indicator on the TabPills strip, so users can freeze a finalized comic script while still iterating storyboards.- **Per-field arc locks on series.** `series.locked.arcFields` is an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); locked fields are preserved verbatim through `commitSeasonsWithRemap` so arc regenerate + auto-resolve only rewrite the unlocked fields. Inline lock icons on the Arc Canvas read view toggle each field.- **Pagination on `GET /api/pipeline/series/:id/issues`.** Accepts optional `?offset=N&limit=N`; when present, returns `{ items, total, offset, limit }`. Without the params, the endpoint still returns the legacy raw array. Eliminates the silent 1000-issue cap for long-running series.diff --git a/DONE.md b/DONE.mdindex a5ade3c3ee..06f882f66c 100644--- a/DONE.md+++ b/DONE.md@@ -11,6 +11,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-19- **[clear-pending-sheet-slot-on-entry-delete] Prune `_latestPendingByCharacter` on character / universe delete.** The in-process slot map that supersede-checks character reference-sheet renders previously persisted entries for the full Node process lifetime — even after the character or its universe was deleted. Extracted the Map + its `claim`/`get`/`release` helpers into `server/services/universeCharacterSheetSlot.js` (standalone module so `universeBuilder.js` can clear slots without a `universeCharacterSheet.js → universeBuilder.js` import cycle) and added two delete-path helpers: `clearPendingSheetSlot(universeId, entryId)` (unconditional single-character drop) and `clearPendingSheetSlotsForUniverse(universeId)` (walks the map once, drops every `${universeId}:` prefix). `universeCharacterSheet.js` now consumes `claimPendingSheetSlot` / `getPendingSheetSlot` / `releasePendingSheetSlot` instead of inline `_latestPendingByCharacter.set/.get/.delete` — behavior is unchanged, the supersede-aware contract still holds. Wired into two paths: (a) `deleteUniverse` calls `clearPendingSheetSlotsForUniverse(id)` after the file-write queue releases, alongside the existing `unlinkCollectionsForUniverse` cascade; (b) `updateUniverse` computes a `prevIds`/`nextIds` diff against `cur.characters` vs `mergedRecord.characters` INSIDE the write queue (so the diff sees the freshest persisted state) and calls `clearPendingSheetSlot(id, removedId)` for each dropped id after the queue returns. The in-flight render path is unaffected — if a render's character is deleted mid-flight the slot becomes empty, `onSheetComplete` treats itself as superseded, saves the file on disk, and skips stamping a now-orphaned `referenceSheetImageRef` pointer (the `updateUniverse` mutator inside `onSheetComplete` is also a no-op since the character record is gone). Coverage: 11 new tests in `universeCharacterSheetSlot.test.js` covering claim/get/release contracts, unconditional vs conditional drop, prefix-anchored universe sweep (with explicit anti-collision case proving `u-a` doesn't match `u-ab`), falsy-id no-ops; 3 new integration tests in `universeBuilder.test.js#"pending sheet slot cleanup"` covering character-drop via PATCH, character-preserve when the patch keeps them, and universe-delete clearing only that universe's slots. All 5703 server tests + 14 reused `universeCharacterSheet.test.js` cases pass.+- **[purge-reference-sheet-image-ref-on-sheet-delete] Active-purge `character.referenceSheetImageRef` on sheet delete.** Shipped both the sheet-delete route the original PLAN entry was gated on AND the eager purge it needed. New `purgeReferenceSheetFromAllUniverses(filename)` helper in `server/services/universeCanon.js` mirrors `purgeImageRefFromAllUniverses` but targets the single-string sheet pointer; uses `updateUniverse`'s mutator form because `referenceSheetImageRef` is in `SERVER_OWNED_CHARACTER_FIELDS` and a literal-object PATCH would be guarded against clobbering the pointer. New `deleteCharacterReferenceSheet(universeId, entryId)` in `server/services/universeCharacterSheet.js` reads the character's current pointer, re-validates via `assertSafeFilename` as defense-in-depth, unlinks the PNG from `PATHS.imageRefs` (ENOENT is benign — surfaced via `fileDeleted: false`), then calls the purge to clear every matching pointer across all universes. Mirrors the renderer's lock guard (`UNIVERSE_CANON_LOCKED` 409) so locked characters' sheets stay delete-protected. New `DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet` route. Client: `deleteCharacterReferenceSheet` helper in `apiUniverseBuilder.js` (silent option), trash button in `CharacterReferenceSheetPanel.jsx` (only rendered when a sheet exists + not in-flight) with inline `[Cancel] [Delete sheet]` confirm row per the user's confirmation-UX preference, `onSheetDeleted` callback wired through `characterExtensions` in `CanonCard.jsx` → `UniverseCanonSection.jsx` (`handleSheetDeleted` mirrors `handleSheetCompleted`'s `latestUniverseRef` read so a parallel edit during the DELETE isn't clobbered). Coverage: 3 new tests in `universeCanon.test.js` for `purgeReferenceSheetFromAllUniverses` + 2 backfill tests for the previously-untested `purgeImageRefFromAllUniverses`; new `universeCharacterSheetDelete.test.js` with 8 tests covering happy path, ENOENT benign, non-ENOENT propagation, no-pointer no-op, 404 character, 409 locked, traversal-rejection, and cross-universe purge. All 5710 server tests + 103 client tests pass; client build clean.- **[per-field-locks-arc-and-stage-granularity] Per-field arc locks + per-stage issue locks.** Follow-on to per-season locks (`[per-season-and-per-field-locks-extend-arc-lock]`). Two layered ratchets, both enforced server-side and surfaced in the UI. (1) **Per-field arc locks** — `series.locked.arcFields` carries an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); new `mergeArcWithLocks(currentArc, nextArc, lockedFields)` helper in `arcPlanner.js` rewrites the incoming arc to preserve locked field values verbatim from the existing arc, called from `commitSeasonsWithRemap` so both auto-resolve (via `resolveVerifyIssues`) and the `/series/:id/arc/generate?commit=true` path honor the lock; new `ARC_LOCKABLE_FIELDS = ['logline','summary','protagonistArc','themes','shape']` export in `pipeline/series.js` is mirrored as the Zod schema in `seriesLockedSchema`. Arc Canvas read view now renders a small `FieldLockToggle` icon (subtle 4×4 inline button, Lock/Unlock-with-spinner) next to each field that's currently displayed — logline paragraph, story-shape badge, themes chip row, summary `<summary>`, protagonistArc `<summary>` — toggling PATCHes through `updatePipelineSeries({ locked: { ...series.locked, arcFields: nextFields } })` with optimistic update + toast. (2) **Per-stage issue locks** — every `issue.stages.{id}` (text + visual + audio) carries `locked: boolean` (default `false`, strict-true coercion so `locked: 'yes'` typos can't accidentally freeze the stage). New `assertStageUnlocked(issue, stageId)` helper in `pipeline/issues.js` throws `ServerError({ status: 400, code: 'PIPELINE_STAGE_LOCKED' })` and is called from every regeneration entry point: `textStages.generateStage`, `visualStages.enqueueComicCoverLike` / `enqueueVisualComicPage` / `enqueueVisualImage` / `enqueueStoryboardSceneVideo` / `enqueueStoryboardShotStartFrame` / `refineComicPanelPrompt` / `refineStoryboardScenePrompt`, `episodeVideo.startEpisodeVideoForIssue` (fresh-start branch only; reuse of existing `cdProjectId` is still permitted), `arcPlanner.generateComicCoverConcepts` (`commit: true` path), and the four route-level audio/extract paths (`/audio/extract-lines`, `/audio/lines/:n/render`, `/storyboards/extract-scenes`, `/comicPages/extract-pages`). The text-stage gate runs *before* `updateStage({ status: 'generating' })` so a locked stage doesn't get stuck at "generating" only to be reset. `PipelineIssue.jsx` (a) gates the per-tab `<Lock>` indicator on per-stage `locked` first (then falls back to the ambient arc/season-wide lock); (b) adds a Lock/Unlock toggle button to the action bar that targets the currently-active stage and PATCHes `{ stages: { [stageId]: { locked: next } } }` via `updatePipelineIssue`; (c) the lock-banner under the TabPills strip prefers the per-stage message when the active tab is locked. Coverage: 11 new tests — 4 in `issues.test.js` (default `locked: false` on every stage, PATCH round-trip, non-boolean coerce-to-false, `assertStageUnlocked` throw/no-op), 1 in `textStages.test.js` (refuse + leave status untouched on locked stage), 6 in `arcPlanner.test.js` (`mergeArcWithLocks` per-field preservation, empty/null/undefined locks pass through, no-current-arc passthrough, null/undefined next no-op, unknown lock keys ignored, full `commitSeasonsWithRemap` round-trip with locked logline + themes). All 5689 server tests + 103 client tests pass.- **[pipeline-visual-stages-setting-field-injection] Inject setting `palette`/`era`/`weather`/`recurringDetails` into visual stages.** Visual prompts now pull the full RICH place descriptor set (description + Palette + Era + Weather + recurringDetails) instead of the SHORT subset (description + Palette + recurringDetails) — era + weather are continuity-critical visual cues that diffusion models weight strongly for lighting, atmosphere, and period dress, and they were already wired through the bible schema + LLM extraction but silently dropped at the visual-prompt boundary. Two surfaces touched: (1) `buildScenePrompt` in `server/lib/scenePrompt.js` + the client mirror at `client/src/lib/scenePrompt.js` swap `shortCanonDescriptorFragments('place', …)` for `richCanonDescriptorFragments('place', …)`, so storyboard scene renders (via `composeVisualPrompt` in `visualStages.js`) AND Writers Room's `SceneCard.jsx` pick up era/weather; (2) `composeComicPagePrompt`'s hand-rolled multi-place clause is replaced with the same `richCanonDescriptorFragments` helper, so the per-page `Setting — Place: description. Palette: X. Era: Y. Weather: Z. recurringDetails` shape is consistent with the scene-prompt path. The capital-cased `Palette:` prefix replaces the previous lowercase `palette:` in comic-page output as a side-effect of the shared helper (RICH_SPEC's uniform capitalization convention). UI card summaries (`KINDS[].descFor` in `UniverseCanonSection`) still use the narrower SHORT spec — those don't drive renders, so widening would just clutter the bible. Truncation order under tight budget pressure: description survives longest; recurringDetails drops first, then weather, era, palette — the priority order documented in `buildScenePrompt`'s header comment. Coverage: 2 new tests in `scenePrompt.test.js` (RICH frags pinned in display order; era/weather omitted when blank) + 3 new tests in `visualStages.test.js` for `composeComicPagePrompt` (full RICH injection + order; blank-field skip without bare prefixes; multi-place ` | `-join). All 5661 server tests + 103 client tests pass; client build clean. Two `/simplify` follow-ups deferred to PLAN.md: `[extract-flatten-canon-descriptor-fragments-helper]` (collapse the 4-site `.map(f => prefix ? ...).join(...)` pattern) and `[cleanplateprompt-migrate-to-rich-canon-fragments]` (sibling visual-prompt surface still on SHORT spec).diff --git a/PLAN.md b/PLAN.mdindex b9eb1731d6..4e3a34db3d 100644--- a/PLAN.md+++ b/PLAN.md@@ -12,7 +12,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Universe-as-Canon — Phase 2 + extensions-- [ ] [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.- [ ] [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[]`.diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 06f0bc1251..ed7feeef86 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -276,7 +276,7 @@ export default function CanonCard({// CanonCard reveals an Expand → CharacterDetailEditor section and a// Reference Sheet panel. NounsStage (series view) omits this so the// per-series cast list stays focused on naming + visual refs.- // Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted }+ // Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted, onSheetDeleted }characterExtensions = null,}) {const description = kind.descFor(entry);@@ -404,6 +404,7 @@ export default function CanonCard({entry={entry}locked={locked}onSheetCompleted={characterExtensions.onSheetCompleted}+ onSheetDeleted={characterExtensions.onSheetDeleted}onOpenLightbox={(filename) => onPreview?.(filename, { isSheet: true })}/></CharacterDetailsToggle>diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsxindex 81ed8d0e91..168d6ed3e5 100644--- a/client/src/components/universe/CharacterReferenceSheetPanel.jsx+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx@@ -11,8 +11,11 @@*/import { useEffect, useRef, useState } from 'react';-import { Camera, Loader2, RefreshCcw, ExternalLink } from 'lucide-react';-import { renderCharacterReferenceSheet } from '../../services/apiUniverseBuilder';+import { Camera, Loader2, RefreshCcw, ExternalLink, Trash2 } from 'lucide-react';+import {+ renderCharacterReferenceSheet,+ deleteCharacterReferenceSheet,+} from '../../services/apiUniverseBuilder';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import useMounted from '../../hooks/useMounted';import toast from '../ui/Toast';@@ -48,10 +51,12 @@ async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150, signa}export default function CharacterReferenceSheetPanel({- universeId, entry, locked, onSheetCompleted, onOpenLightbox,+ universeId, entry, locked, onSheetCompleted, onSheetDeleted, onOpenLightbox,}) {const existing = entry?.referenceSheetImageRef || null;const [jobId, setJobId] = useState(null);+ const [confirmingDelete, setConfirmingDelete] = useState(false);+ const [deleting, setDeleting] = useState(false);// destFilename for the in-flight render — captured from the route response// so the SSE-completion handler can pass the real refs-dir filename up to// the parent without a universe refetch.@@ -108,6 +113,18 @@ export default function CharacterReferenceSheetPanel({// Abort any in-flight HEAD poll when the panel unmounts.useEffect(() => () => { pollAbortRef.current?.abort(); }, []);+ const handleDelete = async () => {+ if (deleting || !universeId || !entry?.id || !existing) return;+ setDeleting(true);+ const result = await deleteCharacterReferenceSheet(universeId, entry.id, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to delete reference sheet'); return null; })+ .finally(() => { setDeleting(false); });+ if (!result) return;+ setConfirmingDelete(false);+ onSheetDeleted?.(entry.id);+ toast.success(`Deleted reference sheet for ${entry.name}`);+ };+const handleGenerate = async () => {if (jobId || !universeId || !entry?.id) return;const queued = await renderCharacterReferenceSheet(universeId, entry.id)@@ -140,22 +157,60 @@ export default function CharacterReferenceSheetPanel({Reference sheet</div><div className="flex items-center gap-1">- <button- type="button"- onClick={handleGenerate}- disabled={inFlight || locked}- title={locked- ? `Unlock ${entry.name} to render a reference sheet`- : (existing ? 'Regenerate the character reference sheet' : 'Generate a character reference sheet')}- className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"- >- {inFlight- ? <Loader2 size={10} className="animate-spin" />- : (existing ? <RefreshCcw size={10} /> : <Camera size={10} />)}- {inFlight- ? `Rendering${pctLabel}`- : (existing ? 'Regenerate sheet' : 'Generate sheet')}- </button>+ {confirmingDelete ? (+ <>+ <button+ type="button"+ onClick={() => setConfirmingDelete(false)}+ disabled={deleting}+ className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleDelete}+ disabled={deleting}+ className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-error/60 text-port-error hover:bg-port-error/15 disabled:opacity-40"+ >+ {deleting ? <Loader2 size={10} className="animate-spin" /> : <Trash2 size={10} />}+ {deleting ? 'Deleting' : 'Delete sheet'}+ </button>+ </>+ ) : (+ <>+ {existing && !inFlight ? (+ <button+ type="button"+ onClick={() => setConfirmingDelete(true)}+ disabled={locked}+ title={locked+ ? `Unlock ${entry.name} to delete the reference sheet`+ : 'Delete the current reference sheet'}+ className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-400 hover:border-port-error/60 hover:text-port-error disabled:opacity-40"+ aria-label={`Delete reference sheet for ${entry.name}`}+ >+ <Trash2 size={10} />+ </button>+ ) : null}+ <button+ type="button"+ onClick={handleGenerate}+ disabled={inFlight || locked}+ title={locked+ ? `Unlock ${entry.name} to render a reference sheet`+ : (existing ? 'Regenerate the character reference sheet' : 'Generate a character reference sheet')}+ className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"+ >+ {inFlight+ ? <Loader2 size={10} className="animate-spin" />+ : (existing ? <RefreshCcw size={10} /> : <Camera size={10} />)}+ {inFlight+ ? `Rendering${pctLabel}`+ : (existing ? 'Regenerate sheet' : 'Generate sheet')}+ </button>+ </>+ )}</div></div>{existing ? (diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex c1ccc5dd5f..8fd78539e3 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -361,6 +361,19 @@ export default function UniverseCanonSection({toast.success(`${entryName} reference sheet ready`);}, [onUniverseChange]);+ // Server already deleted the file + purged the pointer via the DELETE+ // route. Mirror the change into the local draft so the thumbnail clears+ // without a refetch. Reads from `latestUniverseRef` for the same staleness+ // reason as `handleSheetCompleted`.+ const handleSheetDeleted = useCallback((entryId) => {+ const latest = latestUniverseRef.current;+ if (!latest) return;+ const nextCharacters = (latest.characters || []).map((c) =>+ c.id === entryId ? { ...c, referenceSheetImageRef: null } : c,+ );+ onUniverseChange({ ...latest, characters: nextCharacters });+ }, [onUniverseChange]);+const handleRenderRef = async (kind, entry) => {const description = kind.descFor(entry);if (!description.trim()) {@@ -648,6 +661,7 @@ export default function UniverseCanonSection({onExpandCharacter={handleExpandCharacter}expandingId={expandingId}onSheetCompleted={handleSheetCompleted}+ onSheetDeleted={handleSheetDeleted}onToggleLock={(entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked)}togglingLockId={togglingLockId}onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}@@ -665,7 +679,7 @@ export default function UniverseCanonSection({);}-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null }) {// Universe-only character wiring — `null` for non-character kinds so// CanonCard's gate stays `kind === 'characters' && characterExtensions`.// Memoized so the BASE object is stable across re-renders that aren't@@ -675,8 +689,8 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende// per-card memoization and isn't worth the complexity at typical cast// sizes.const characterExtensions = useMemo(- () => (kind.key === 'characters' ? { universeId, onExpandCharacter, onSheetCompleted } : null),- [kind.key, universeId, onExpandCharacter, onSheetCompleted],+ () => (kind.key === 'characters' ? { universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted } : null),+ [kind.key, universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted],);const Icon = kind.icon;// Bulk lock-state summary computed off the FULL list (not the series-filtereddiff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 0360d19aec..778dc8d16b 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -193,6 +193,16 @@ export const renderCharacterReferenceSheet = (universeId, entryId, {body: JSON.stringify({ overridePrompt, overrideNegativePrompt, modelId }),});+// Delete the character's current reference sheet (file + pointer). Server+// unlinks the PNG from /data/image-refs/ and clears every matching+// `referenceSheetImageRef` across all universes. Returns+// `{ filename, fileDeleted, cleared }`.+export const deleteCharacterReferenceSheet = (universeId, entryId, options = {}) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet`, {+ method: 'DELETE',+ ...options,+ });+// Cast-wide differentiate — single LLM call rewrites every character so the// whole cast has no visually-colliding pairs.export const differentiateUniverseCast = (universeId, { providerId, model } = {}) =>diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 23daa5ccd4..f0a3bac60e 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -19,7 +19,7 @@ import { validateRequest } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';-import { renderCharacterReferenceSheet } from '../services/universeCharacterSheet.js';+import { renderCharacterReferenceSheet, deleteCharacterReferenceSheet } from '../services/universeCharacterSheet.js';import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/storyBible.js';import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';@@ -677,6 +677,16 @@ router.post('/:id/characters/:entryId/render-reference-sheet', asyncHandler(asynres.json(result);}));+// Delete the character's current reference sheet — unlinks the PNG from+// `data/image-refs/` and nulls `referenceSheetImageRef` on every matching+// character (via `purgeReferenceSheetFromAllUniverses`) so the UI clears+// reactively without a refetch.+router.delete('/:id/characters/:entryId/reference-sheet', asyncHandler(async (req, res) => {+ const result = await deleteCharacterReferenceSheet(req.params.id, req.params.entryId)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+// Cast-wide differentiate — one LLM call rewrites every character so the// cast as a whole has no visually-colliding pairs. Returns counts + the// updated universe.diff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex 26469f77a1..f1d1ee73b8 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -360,3 +360,42 @@ export async function purgeImageRefFromAllUniverses(filename) {}return { removed };}++/**+ * Null out `character.referenceSheetImageRef` on every character (across every+ * universe) whose pointer matches `filename`. Mirrors `purgeImageRefFromAllUniverses`+ * but targets the single-string sheet pointer rather than the `imageRefs[]` array.+ *+ * Wired into the sheet-delete route so the eager pointer-clear lands the same+ * moment the file is unlinked. The GET-time lazy `pruneStaleReferenceSheets`+ * is still the safety net for files deleted out-of-band (filesystem cleanup,+ * sample-data resets) — this helper is the eager path.+ *+ * Uses `updateUniverse`'s mutator form because `referenceSheetImageRef` is in+ * `SERVER_OWNED_CHARACTER_FIELDS` — a literal-object PATCH would be guarded+ * against clobbering the server-stamped pointer (the guard preserves cur's+ * value when its file still resolves on disk). The purge IS the server-side+ * writer, so it has to bypass that guard via the mutator form.+ */+export async function purgeReferenceSheetFromAllUniverses(filename) {+ if (!filename || typeof filename !== 'string') return { cleared: 0 };+ const universes = await listUniverses();+ let cleared = 0;+ for (const universe of universes) {+ const characters = Array.isArray(universe.characters) ? universe.characters : null;+ if (!characters) continue;+ if (!characters.some((entry) => entry?.referenceSheetImageRef === filename)) continue;+ await updateUniverse(universe.id, (cur) => {+ const list = Array.isArray(cur.characters) ? cur.characters : [];+ let touched = false;+ const nextList = list.map((entry) => {+ if (entry?.referenceSheetImageRef !== filename) return entry;+ cleared += 1;+ touched = true;+ return { ...entry, referenceSheetImageRef: null };+ });+ return touched ? { characters: nextList } : null;+ });+ }+ return { cleared };+}diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.jsindex 4bb524d8cc..5ae0151a90 100644--- a/server/services/universeCanon.test.js+++ b/server/services/universeCanon.test.js@@ -5,11 +5,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const fileStore = new Map();vi.mock('../lib/fileUtils.js', () => ({- PATHS: { data: '/mock/data' },+ PATHS: { data: '/mock/data', imageRefs: '/mock/data/image-refs' },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)),+ // Stub: pretend every referenced sheet file exists, so the GET-time lazy+ // `pruneStaleReferenceSheets` doesn't null out pointers between seed and+ // assertion. The purge tests below don't depend on stale-collapse behavior.+ resolveImageRef: vi.fn((filename) => (filename ? `/mock/data/image-refs/${filename}` : null)),}));let uuidCounter = 0;@@ -273,3 +277,67 @@ describe('universeCanon — extractCanonFromProse passes autoLock + sourceSeriesexpect(inserted.locked).not.toBe(true);});});++describe('universeCanon — purgeReferenceSheetFromAllUniverses', () => {+ it('nulls referenceSheetImageRef on every matching character across every universe', async () => {+ const w1 = await seedUniverseWithCharacters([+ { name: 'Alex', physicalDescription: 'a', referenceSheetImageRef: 'sheet-A.png' },+ { name: 'Beth', physicalDescription: 'b', referenceSheetImageRef: 'sheet-B.png' },+ ]);+ const w2Initial = await svc.createUniverse({ name: 'Universe Two', starterPrompt: 'x', stylePrompt: 'y' });+ const w2 = await svc.updateUniverse(w2Initial.id, {+ characters: [{ name: 'Cara', physicalDescription: 'c', referenceSheetImageRef: 'sheet-A.png' }],+ });++ const result = await canonSvc.purgeReferenceSheetFromAllUniverses('sheet-A.png');+ expect(result.cleared).toBe(2);++ const reread = await svc.listUniverses();+ const reread1 = reread.find((u) => u.id === w1.id);+ const reread2 = reread.find((u) => u.id === w2.id);+ expect(reread1.characters.find((c) => c.name === 'Alex').referenceSheetImageRef).toBeNull();+ // Untouched: Beth's sheet name doesn't match the purge target.+ expect(reread1.characters.find((c) => c.name === 'Beth').referenceSheetImageRef).toBe('sheet-B.png');+ expect(reread2.characters.find((c) => c.name === 'Cara').referenceSheetImageRef).toBeNull();+ });++ it('returns cleared:0 and skips writes when no character matches', async () => {+ await seedUniverseWithCharacters([+ { name: 'Alex', physicalDescription: 'a', referenceSheetImageRef: 'sheet-A.png' },+ ]);+ const result = await canonSvc.purgeReferenceSheetFromAllUniverses('sheet-missing.png');+ expect(result.cleared).toBe(0);+ });++ it('returns cleared:0 when filename is empty / non-string (defensive guard)', async () => {+ await seedUniverseWithCharacters([+ { name: 'Alex', physicalDescription: 'a', referenceSheetImageRef: 'sheet-A.png' },+ ]);+ expect(await canonSvc.purgeReferenceSheetFromAllUniverses('')).toEqual({ cleared: 0 });+ expect(await canonSvc.purgeReferenceSheetFromAllUniverses(null)).toEqual({ cleared: 0 });+ expect(await canonSvc.purgeReferenceSheetFromAllUniverses(undefined)).toEqual({ cleared: 0 });+ });+});++describe('universeCanon — purgeImageRefFromAllUniverses', () => {+ it('strips a filename from every imageRefs[] across canon kinds', async () => {+ const w = await seedUniverseWithCharacters([+ { name: 'Alex', physicalDescription: 'a', imageRefs: ['shared.png', 'other.png'] },+ { name: 'Beth', physicalDescription: 'b', imageRefs: ['shared.png'] },+ ]);+ const result = await canonSvc.purgeImageRefFromAllUniverses('shared.png');+ expect(result.removed).toBe(2);+ const reread = (await svc.listUniverses()).find((u) => u.id === w.id);+ expect(reread.characters.find((c) => c.name === 'Alex').imageRefs).toEqual(['other.png']);+ expect(reread.characters.find((c) => c.name === 'Beth').imageRefs).toEqual([]);+ });++ it('returns removed:0 when nothing matches or input is invalid', async () => {+ await seedUniverseWithCharacters([+ { name: 'Alex', physicalDescription: 'a', imageRefs: ['only.png'] },+ ]);+ expect(await canonSvc.purgeImageRefFromAllUniverses('nope.png')).toEqual({ removed: 0 });+ expect(await canonSvc.purgeImageRefFromAllUniverses('')).toEqual({ removed: 0 });+ expect(await canonSvc.purgeImageRefFromAllUniverses(null)).toEqual({ removed: 0 });+ });+});diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex 4d6ec32056..d7de728b7e 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -13,14 +13,14 @@* `character.referenceSheetImageRef` once the render completes.*/-import { copyFile } from 'fs/promises';+import { copyFile, unlink } from 'fs/promises';import { join, basename } from 'path';import { randomUUID } from 'crypto';-import { PATHS, ensureDir, shortId } from '../lib/fileUtils.js';+import { PATHS, ensureDir, shortId, assertSafeFilename } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { getSettings } from './settings.js';import { getUniverse, updateUniverse } from './universeBuilder.js';-import { buildStyleClause } from './universeCanon.js';+import { buildStyleClause, purgeReferenceSheetFromAllUniverses } from './universeCanon.js';import { getImageModels } from '../lib/mediaModels.js';import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';import { findOrCreateUniverseCollection } from './mediaCollections.js';@@ -430,6 +430,55 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilenareturn { filename: destFilename, path: destPath };}+/**+ * Delete the character's current reference sheet — unlinks the file from+ * `PATHS.imageRefs` and clears `referenceSheetImageRef` on every matching+ * character via `purgeReferenceSheetFromAllUniverses`. Returns+ * `{ filename, fileDeleted, cleared }`; a missing file is not an error+ * (the lazy `pruneStaleReferenceSheets` may have already nulled the pointer+ * out-of-band) — `fileDeleted: false` distinguishes that case.+ *+ * Mirrors the renderer's lock check so a locked character's sheet stays+ * delete-protected alongside its other AI-managed fields.+ */+export async function deleteCharacterReferenceSheet(universeId, entryId) {+ const universe = await getUniverse(universeId);+ const list = Array.isArray(universe.characters) ? universe.characters : [];+ const character = list.find((c) => c.id === entryId);+ if (!character) {+ throw new ServerError(`Character ${entryId} not found in universe`, {+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',+ });+ }+ if (character.locked === true) {+ throw new ServerError(+ `Character "${character.name}" is locked — unlock it before deleting the reference sheet`,+ { status: 409, code: 'UNIVERSE_CANON_LOCKED' },+ );+ }+ const filename = character.referenceSheetImageRef;+ if (!filename) {+ return { filename: null, fileDeleted: false, cleared: 0 };+ }+ // Defense-in-depth: the filename was server-stamped via `sheetFilename()`,+ // but re-validate before passing to `unlink` so a hand-edited universes+ // JSON can't smuggle a traversal segment into the filesystem call.+ assertSafeFilename(filename, { extensions: ['.png'], subject: 'reference sheet filename' });++ const target = join(PATHS.imageRefs, filename);+ // ENOENT is benign — the on-disk file may already be gone (out-of-band+ // cleanup, sample-data reset). The pointer-purge below is the canonical+ // clean and runs regardless.+ let fileDeleted = true;+ await unlink(target).catch((err) => {+ if (err?.code === 'ENOENT') { fileDeleted = false; return; }+ throw err;+ });+ const { cleared } = await purgeReferenceSheetFromAllUniverses(filename);+ console.log(`🗑️ Deleted character sheet ${filename} (file=${fileDeleted}, pointers cleared=${cleared})`);+ return { filename, fileDeleted, cleared };+}+export const REFERENCE_SHEET_CONSTANTS = Object.freeze({DEFAULT_WIDTH, DEFAULT_HEIGHT,DEFAULT_EXPRESSIONS, DEFAULT_HAND_GESTURES,diff --git a/server/services/universeCharacterSheetDelete.test.js b/server/services/universeCharacterSheetDelete.test.jsnew file mode 100644index 0000000000..fda699873a--- /dev/null+++ b/server/services/universeCharacterSheetDelete.test.js@@ -0,0 +1,171 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// `deleteCharacterReferenceSheet` orchestrates: getUniverse → fs.unlink → purge.+// Stub each collaborator so the orchestration is testable without spinning+// up the universe store or touching disk. Heavy deps the renderer pulls in+// (mediaJobQueue, mediaCollections) are stubbed to noops since the delete+// path doesn't exercise them.++const unlinkMock = vi.fn();+vi.mock('fs/promises', async () => {+ const actual = await vi.importActual('fs/promises');+ return { ...actual, unlink: (...args) => unlinkMock(...args) };+});++const fakeUniverseStore = new Map();+vi.mock('./universeBuilder.js', () => ({+ getUniverse: vi.fn(async (id) => {+ const u = fakeUniverseStore.get(id);+ if (!u) throw Object.assign(new Error(`Not found`), { status: 404, code: 'UNIVERSE_NOT_FOUND' });+ return u;+ }),+ updateUniverse: vi.fn(async (id, mutatorOrPatch) => {+ const cur = fakeUniverseStore.get(id);+ const patch = typeof mutatorOrPatch === 'function' ? mutatorOrPatch(cur) : mutatorOrPatch;+ if (!patch) return cur;+ const next = { ...cur, ...patch };+ fakeUniverseStore.set(id, next);+ return next;+ }),+ listUniverses: vi.fn(async () => Array.from(fakeUniverseStore.values())),+ joinInfluenceList: vi.fn(() => ''),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { imageRefs: '/mock/data/image-refs', images: '/mock/data/images', data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ shortId: (id, n = 8) => (id == null ? '' : String(id).slice(0, n)),+ // Real basename-only validator behavior the helper relies on as defense-in-depth.+ assertSafeFilename: vi.fn((filename) => {+ if (!filename || typeof filename !== 'string') {+ throw Object.assign(new Error('Filename required'), { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (filename.includes('/') || filename.includes('\\') || filename === '.' || filename === '..') {+ throw Object.assign(new Error('Invalid filename'), { status: 400, code: 'VALIDATION_ERROR' });+ }+ }),+}));++// Stubs for the heavy deps the renderer pulls in. The delete helper doesn't+// touch any of these, but the module loader will pull them in unless we stub.+vi.mock('./mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(),+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },+}));+vi.mock('./mediaCollections.js', () => ({ findOrCreateUniverseCollection: vi.fn() }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn().mockResolvedValue({}) }));+vi.mock('../lib/mediaModels.js', () => ({ getImageModels: vi.fn(() => []) }));+vi.mock('../lib/canonPrompt.js', () => ({+ flattenStats: vi.fn(() => ''),+ flattenPalette: vi.fn(() => ''),+ flattenWardrobes: vi.fn(() => ''),+ flattenProps: vi.fn(() => ''),+ flattenNamedList: vi.fn(() => ''),+}));++const { deleteCharacterReferenceSheet } = await import('./universeCharacterSheet.js');++const seedUniverse = (id, characters) => {+ fakeUniverseStore.set(id, { id, name: 'Test', characters });+};++beforeEach(() => {+ fakeUniverseStore.clear();+ unlinkMock.mockReset();+ unlinkMock.mockResolvedValue(undefined);+});++describe('universeCharacterSheet — deleteCharacterReferenceSheet', () => {+ it('unlinks the file and nulls the pointer on success', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-X.png' },+ ]);++ const result = await deleteCharacterReferenceSheet('uni-1', 'char-1');+ expect(result).toEqual({ filename: 'sheet-X.png', fileDeleted: true, cleared: 1 });+ expect(unlinkMock).toHaveBeenCalledWith('/mock/data/image-refs/sheet-X.png');+ expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBeNull();+ });++ it('treats ENOENT (file already gone) as benign — pointer still clears', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-X.png' },+ ]);+ unlinkMock.mockRejectedValueOnce(Object.assign(new Error('not found'), { code: 'ENOENT' }));++ const result = await deleteCharacterReferenceSheet('uni-1', 'char-1');+ expect(result).toEqual({ filename: 'sheet-X.png', fileDeleted: false, cleared: 1 });+ expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBeNull();+ });++ it('propagates non-ENOENT unlink errors instead of swallowing', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-X.png' },+ ]);+ unlinkMock.mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }));++ await expect(deleteCharacterReferenceSheet('uni-1', 'char-1'))+ .rejects.toMatchObject({ code: 'EACCES' });+ // Pointer is NOT cleared when the unlink fails for a non-ENOENT reason —+ // a half-cleared state where the file is still on disk would leave the+ // gallery showing a sheet that no character knows about.+ expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBe('sheet-X.png');+ });++ it('no-ops when character has no sheet pointer', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: null },+ ]);++ const result = await deleteCharacterReferenceSheet('uni-1', 'char-1');+ expect(result).toEqual({ filename: null, fileDeleted: false, cleared: 0 });+ expect(unlinkMock).not.toHaveBeenCalled();+ });++ it('throws 404 when character is missing from the universe', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-X.png' },+ ]);++ await expect(deleteCharacterReferenceSheet('uni-1', 'char-missing'))+ .rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });+ expect(unlinkMock).not.toHaveBeenCalled();+ });++ it('throws 409 when the character is locked (mirrors the render path)', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-X.png', locked: true },+ ]);++ await expect(deleteCharacterReferenceSheet('uni-1', 'char-1'))+ .rejects.toMatchObject({ status: 409, code: 'UNIVERSE_CANON_LOCKED' });+ expect(unlinkMock).not.toHaveBeenCalled();+ expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBe('sheet-X.png');+ });++ it('rejects a sheet pointer that smuggles a path separator (defense in depth)', async () => {+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: '../escape.png' },+ ]);++ await expect(deleteCharacterReferenceSheet('uni-1', 'char-1'))+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR' });+ expect(unlinkMock).not.toHaveBeenCalled();+ });++ it('clears the pointer on every other character whose sheet matches the same filename', async () => {+ // Renames can leave two universes pointing at the same on-disk PNG. Purge+ // must hit them all so the gallery delete is the single source of truth.+ seedUniverse('uni-1', [+ { id: 'char-1', name: 'Alex', referenceSheetImageRef: 'sheet-Z.png' },+ ]);+ seedUniverse('uni-2', [+ { id: 'char-99', name: 'Cara', referenceSheetImageRef: 'sheet-Z.png' },+ ]);++ const result = await deleteCharacterReferenceSheet('uni-1', 'char-1');+ expect(result.cleared).toBe(2);+ expect(fakeUniverseStore.get('uni-1').characters[0].referenceSheetImageRef).toBeNull();+ expect(fakeUniverseStore.get('uni-2').characters[0].referenceSheetImageRef).toBeNull();+ });+});