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
/**
* Shared canon-entity card — one bible entry (character / place / object)
* with description, render-reference button, optional AI-differentiate button
* (characters only), and click-to-preview image thumbnails.
*
* Used by NounsStage (per-series, pre-Phase B) and UniverseCanonSection
* (per-universe, embedded in UniverseBuilder).
*
* Renders through `EntryCard` so the locked accent, title row, action column,
* and thumbnail stay in lock-step with the variation card.
*/
import { useEffect, useRef, useState } from 'react';
import { Loader2, ImagePlus, ImageUp, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, X, Star, Square, ScanText } from 'lucide-react';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import useRowDraft from '../../hooks/useRowDraft';
import useFieldDraft from '../../hooks/useFieldDraft';
import usePendingListRows from '../../hooks/usePendingListRows';
import MediaJobThumb from './MediaJobThumb';
import EntryCard from '../universe/EntryCard';
import EntryThumbSlot from '../universe/EntryThumbSlot';
import CharacterDetailEditor from '../universe/CharacterDetailEditor';
import ObjectAttachmentsEditor from '../universe/ObjectAttachmentsEditor';
import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';
import CharacterLoraChip from '../loraTraining/CharacterLoraChip';
import Pill from '../ui/Pill';
import CollapsibleSection from '../ui/CollapsibleSection';
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
// drift would surface immediately as a Zod 400 on the next save.
const INT_EXT_OPTIONS = ['INT', 'EXT'];
const TIME_OF_DAY_OPTIONS = ['dawn', 'day', 'dusk', 'night'];
function ChipPicker({ label, value, options, onChange }) {
return (
<div className="flex items-center gap-1">
<span className="text-[10px] uppercase tracking-wider text-gray-500">{label}:</span>
{options.map((opt) => {
const active = value === opt;
return (
<button
key={opt}
type="button"
onClick={() => onChange(active ? null : opt)}
className={`px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider border ${
active
? 'bg-port-accent/20 border-port-accent text-port-accent'
: 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'
}`}
title={active ? `Clear ${label}` : `Set ${label} to ${opt}`}
>
{opt}
</button>
);
})}
</div>
);
}
// Inline editable description for the canon card's primary descriptor field.
// Read-only `<p>` when locked or no PATCH channel; buffered textarea otherwise
// (commits on blur via `useFieldDraft`, mirroring the WardrobeRow pattern).
// The bound value falls back to the legacy field (`description` on characters,
// `significance` on objects) so pre-migration entries pre-fill on first edit
// and migrate to the canonical field on save.
function DescriptionField({ entry, descField, fallbackField, max, editable, onCommit, placeholder }) {
const stored = entry[descField];
const fallback = fallbackField ? entry[fallbackField] : null;
const seed = (typeof stored === 'string' && stored)
|| (typeof fallback === 'string' ? fallback : '')
|| '';
const draft = useFieldDraft(seed, onCommit);
if (!editable) {
return (
<p className="text-xs text-gray-400 mt-1 line-clamp-3 whitespace-pre-wrap">
{seed || <em className="text-gray-600">No description yet.</em>}
</p>
);
}
return (
<textarea
aria-label="Description"
value={draft.value}
onChange={draft.onChange}
onBlur={draft.onBlur}
placeholder={placeholder}
rows={3}
maxLength={max}
className="w-full mt-1 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 whitespace-pre-wrap"
/>
);
}
function ReadonlyChip({ children }) {
return (
<span className="px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider bg-port-card border border-port-border text-gray-400">
{children}
</span>
);
}
// A canon entry is reveal-gated (#2178) when it carries a hard `spoiler` flag
// or a numeric `revealIssue`. Mirrors the server's `isEntryRevealGated`.
const isEntryGated = (entry) => entry?.spoiler === true || Number.isInteger(entry?.revealIssue);
// Spoiler badge shown in the card title when an entry is reveal-gated (#2178).
// Purely informational; the gating itself happens server-side in
// `buildStageContext`. Uses the shared `Pill` primitive (warning tone).
function SpoilerBadge({ entry }) {
if (!isEntryGated(entry)) return null;
const label = entry.spoiler === true ? 'spoiler' : `reveal #${entry.revealIssue}`;
const title = entry.spoiler === true
? 'Hard spoiler — hidden from every issue’s drafting prompt'
: `Hidden from drafting context until Issue ${entry.revealIssue}`;
return (
<Pill tone="warning" size="xs" title={title} className="rounded-full uppercase tracking-wider">
{label}
</Pill>
);
}
// Reveal-timing editor (#2178) — sets when a canon fact may enter a drafting
// prompt. Applies to every kind. `revealIssue` (int) hides the entry from
// issues before that number; `spoiler` hard-hides it from all drafting;
// `surfaceDescriptor` is the pre-reveal stand-in substituted into context.
// Absent = always visible (backward-compatible default). Labels are
// `htmlFor`/`id` paired per the accessibility convention.
function RevealTimingField({ entry, editable, onPatch }) {
const idBase = `reveal-${entry.id}`;
const surfaceDraft = useFieldDraft(
typeof entry.surfaceDescriptor === 'string' ? entry.surfaceDescriptor : '',
(v) => onPatch({ surfaceDescriptor: v || null }),
);
const gated = isEntryGated(entry);
if (!editable) {
if (!gated) return null;
return (
<div className="mt-2 flex flex-wrap items-center gap-2 text-[10px] text-gray-500">
<span className="uppercase tracking-wider">Reveal:</span>
{entry.spoiler === true
? <ReadonlyChip>hard spoiler</ReadonlyChip>
: <ReadonlyChip>Issue {entry.revealIssue}</ReadonlyChip>}
{entry.surfaceDescriptor
? <span className="italic text-gray-500">surface: {entry.surfaceDescriptor}</span>
: null}
</div>
);
}
return (
<CollapsibleSection
className="mt-2"
label={
<>
Reveal timing (spoiler scoping)
{gated ? <span className="ml-1 text-port-warning normal-case tracking-normal">· gated</span> : null}
</>
}
bodyClassName="mt-1.5 space-y-2 pl-3 border-l border-port-border"
>
<div className="flex flex-wrap items-center gap-3">
<div className="flex flex-col gap-0.5">
<label htmlFor={`${idBase}-issue`} className="text-[10px] uppercase tracking-wider text-gray-500">
Reveal in issue #
</label>
<input
id={`${idBase}-issue`}
type="number"
min={1}
max={BIBLE_LIMITS.REVEAL_ISSUE_MAX}
value={Number.isInteger(entry.revealIssue) ? entry.revealIssue : ''}
onChange={(e) => {
const v = e.target.value.trim();
const n = v === '' ? null : Math.trunc(Number(v));
onPatch({ revealIssue: Number.isInteger(n) && n >= 1 ? n : null });
}}
placeholder="—"
className="w-20 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200"
/>
</div>
<label htmlFor={`${idBase}-spoiler`} className="flex items-center gap-1.5 text-[11px] text-gray-400 mt-3">
<input
id={`${idBase}-spoiler`}
type="checkbox"
checked={entry.spoiler === true}
onChange={(e) => onPatch({ spoiler: e.target.checked })}
className="accent-port-warning"
/>
Hard spoiler (never in drafting)
</label>
</div>
<div className="flex flex-col gap-0.5">
<label htmlFor={`${idBase}-surface`} className="text-[10px] uppercase tracking-wider text-gray-500">
Surface descriptor (pre-reveal stand-in)
</label>
<textarea
id={`${idBase}-surface`}
value={surfaceDraft.value}
onChange={surfaceDraft.onChange}
onBlur={surfaceDraft.onBlur}
rows={2}
maxLength={BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX}
placeholder="What the world looks like BEFORE the reveal (e.g. "the locked east wing"). Substituted into drafting context until the reveal issue."
className="w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 whitespace-pre-wrap"
/>
</div>
</CollapsibleSection>
);
}
function SourceSeriesChip({ sourceSeriesId, seriesName }) {
return (
<span
className="inline-flex items-center px-1.5 py-0.5 rounded bg-port-card border border-port-border text-[9px] uppercase tracking-wider text-gray-400"
title={seriesName
? `Introduced by series "${seriesName}" (${sourceSeriesId})`
: `Introduced by series ${sourceSeriesId}`}
>
{seriesName ? `from ${seriesName}` : 'from series'}
</span>
);
}
// Parent decides patch-vs-promote on `nextRow.name` non-empty; see `useRowDraft`.
function WardrobeRow({ wardrobe, editable, onCommit, onRemove }) {
const { draftFor, setDraft, commit } = useRowDraft(wardrobe, onCommit);
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={draftFor('name')}
onChange={(e) => setDraft('name', e.target.value)}
onBlur={() => commit('name')}
placeholder="Outfit name (e.g. Wedding)"
aria-label="Outfit name"
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'}`} aria-label={`Remove ${wardrobe.name || 'this outfit'}`}
className="shrink-0 text-gray-500 hover:text-port-error"
>
<Trash2 size={12} />
</button>
</div>
<textarea
aria-label="Outfit description"
value={draftFor('description')}
onChange={(e) => setDraft('description', e.target.value)}
onBlur={() => commit('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={BIBLE_LIMITS.WARDROBE_DESCRIPTION_MAX}
/>
</div>
);
}
// Wardrobes (A2) — collapsed summary by default; click to expand into an
// inline editor when `editable`. Per-row edits are buffered inside each
// `WardrobeRow` via `useRowDraft`, so a keystroke doesn't fire a
// universe-wide round-trip per character. The ride-along merge means a
// fast desc-blur after a name keystroke ships both columns together, so the
// row promotes correctly even if the user never explicitly blurs name first.
//
// Pending rows use `wd-<uuid>` ids (server `ensureId` preserves them, so
// they round-trip verbatim across the pending → persisted promotion) —
// `stripIdOnPromote` stays false to keep WardrobeRow mounted across the
// swap and preserve sibling draft buffers.
function WardrobeSection({ wardrobes, editable, onChange }) {
// Kept local (rather than folded into CollapsibleSection's internal state)
// because "Add outfit" has to force the section open from outside the header.
const [open, setOpen] = useState(false);
const { merged, addRow, updateRow, removeRow } = usePendingListRows({
persisted: wardrobes,
requiredColumn: 'name',
idPrefix: 'wd-',
blankRow: () => ({ name: '', description: '' }),
onChange,
});
if (!editable && merged.length === 0) return null;
const names = merged.map((w) => w.name).filter(Boolean).join(', ');
const addOne = () => {
setOpen(true);
addRow();
};
return (
<CollapsibleSection
className="mt-2"
icon={Shirt}
label={`Outfits (${merged.length})`}
summary={names ? `: ${names}` : ''}
open={open}
onOpenChange={setOpen}
bodyClassName="mt-1.5 pl-3 border-l border-port-border space-y-1.5"
>
{merged.map((w, i) => (
<WardrobeRow
key={w.id || i}
wardrobe={w}
editable={editable}
onCommit={(nextRow) => updateRow(i, nextRow)}
onRemove={() => removeRow(i)}
/>
))}
{editable ? (
<button
type="button"
onClick={addOne}
className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500"
>
<Plus size={10} /> Add outfit
</button>
) : null}
</CollapsibleSection>
);
}
export default function CanonCard({
kind, entry,
inFlightJobId,
onRender, onJobCompleted, onJobFailed, onPreview, onRefine,
refining = false, refineDisabled = false,
// Cross-reference usage: `[{ seriesId, seriesName, issueCount, issueIds }, ...]`
// populated lazily by the Universe Canon page. Null while still loading.
usage = null,
// Optional — NounsStage omits this so per-series canon stays
// unlockable-only at the universe level. Called with `(entryId, nextLocked)`.
onToggleLock = null,
togglingLock = false,
// Optional — when provided + kind is settings, surfaces inline chip pickers
// for `intExt` / `timeOfDay`. Called with `(entryId, { intExt?, timeOfDay? })`.
onPatchEntry = null,
// Optional — settings-only "Render clean plate" affordance. Called with
// `(entry)` so the parent can build the no-people prompt variant.
onRenderCleanPlate = null,
// Optional — "Describe from image(s)" affordance. Called with `(entry)` so
// the parent can open the vision-describe modal seeded with this entry. When
// omitted (e.g. the pipeline series view) the button is hidden.
onDescribeImages = null,
onCorrectFromImage = null,
// Optional `{ [seriesId]: name }` lookup so the "from series" chip can
// render the actual series name. Null/empty falls back to the id-tooltip
// form for callers that don't have the map handy.
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 this so the
// per-series cast list stays focused on naming + visual refs.
// Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted, onSheetDeleted, castList }
// `castList` (the universe-wide character list) feeds the relationship-link
// target picker in CharacterDetailEditor (#1287).
characterExtensions = null,
// Universe-only object extensions. When provided + kind is 'objects',
// CanonCard reveals an Attachments editor (object↔character emotional
// attachment links, #1288). NounsStage (series view) omits this.
// Shape: { castList } — the universe-wide character list feeds the
// attachment target picker in ObjectAttachmentsEditor.
objectExtensions = null,
// `(entryId) => void` — drop this entry from its canon bucket. Same contract
// (and same X-button affordance) as removing a category variation or a
// composite sheet: the entry leaves the universe bucket, while its rendered
// images and any linked Catalog ingredient are left alone. Null in the
// pipeline/series view (NounsStage), which has no removal channel.
onRemove = null,
}) {
const description = kind.descFor(entry);
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
const locked = entry.locked === true;
const tags = Array.isArray(entry.tags) ? entry.tags.filter(Boolean) : [];
// Lock guards prompt-data rewrites only — `refineUniverseCharacter`
// returns 409 `UNIVERSE_CANON_LOCKED` on a locked target, and the cast-wide
// differentiate skips locked entries at apply time. Render paths do NOT
// consult the lock: rendering a new reference image (or a clean plate for
// places) doesn't mutate the entry's prompt/description, just appends to
// `imageRefs[]`. The pipeline view (NounsStage) inherits the same UX —
// locked entries are still renderable, just not LLM-rewritable.
const blockedByLock = locked;
// Visual at-a-glance without scrolling to the footer ref grid. Falls back
// to the MOST RECENT ref when nothing is pinned so a freshly-rendered entry
// isn't thumbnail-less just because the user hasn't picked a primary yet,
// and a re-render lands as the avatar instead of being buried behind older
// takes. `imageRefs` is chronological (renders append to the end).
const thumbnailRef = (entry.primaryImageRef && refs.includes(entry.primaryImageRef))
? entry.primaryImageRef
: (refs[refs.length - 1] || null);
// settledRef prevents duplicate completion callbacks under React 18
// StrictMode's mount→cleanup→mount double-fire in dev. MediaJobThumb
// opens its own subscription for visuals; ours coexists, filtered by
// jobId.
const { status, filename, error } = useMediaJobProgress(inFlightJobId);
const settledRef = useRef(null);
useEffect(() => {
if (!inFlightJobId) { settledRef.current = null; return; }
if (settledRef.current === inFlightJobId) return;
if (status === 'completed' && filename) {
settledRef.current = inFlightJobId;
// Pass `inFlightJobId` back so the universe-page pending queue can
// shift exactly this jobId out (vs. dropping every queued job for
// the row, which would mis-handle batch renders that queue multiple
// jobs against a single canon entry).
onJobCompleted?.(entry.id, filename, inFlightJobId);
} else if (status === 'failed' || status === 'canceled') {
settledRef.current = inFlightJobId;
onJobFailed?.(entry.id, error || status, inFlightJobId);
}
}, [inFlightJobId, status, filename, error, entry.id, onJobCompleted, onJobFailed]);
const title = (
<div className="flex items-center gap-2 flex-wrap">
{/* Preserve the full name, including unbroken names, within the title slot. */}
<span className="min-w-0 text-sm text-white font-medium break-words">{entry.name}</span>
{entry.aliases?.length ? (
<span className="min-w-0 text-[10px] text-gray-500 break-words">
aka {entry.aliases.join(', ')}
</span>
) : null}
{entry.sourceSeriesId ? (
<SourceSeriesChip
sourceSeriesId={entry.sourceSeriesId}
seriesName={seriesNameMap?.[entry.sourceSeriesId]}
/>
) : null}
<SpoilerBadge entry={entry} />
</div>
);
// Three-state thumbnail slot (pending / empty / completed). Empty state
// shows a placeholder box with a Render button that fires the same handler
// as the actions-column Image button — surfaces a one-click affordance for
// canon entries that haven't been visualized yet. Pending shows the live
// diffusion spinner from MediaJobThumb (also mirrored in the footer's
// ref-grid for live-progress detail).
// Lock no longer gates rendering — see the `blockedByLock` comment above.
// Render still requires a description (the prompt source) + an actual
// handler from the parent. Pending state is checked inside EntryThumbSlot.
const showCharacterSheet = kind.key === 'characters' && !!characterExtensions && !!onPatchEntry;
const canRender = !!onRender && !!description.trim();
const thumbnail = (
<EntryThumbSlot
size={showCharacterSheet ? 'sheet' : 'sm'}
inFlightJobId={inFlightJobId || null}
imageRefs={refs}
primaryImageRef={entry.primaryImageRef || null}
alt={`${entry.name} reference`}
onPreview={onPreview ? (visibleFilename) => onPreview(visibleFilename || thumbnailRef) : null}
onRender={onRender}
canRender={canRender}
disabledHint="Give this entry a description to enable rendering"
/>
);
const body = (
<>
{tags.length > 0 ? (
<div className="flex items-center gap-1 mt-1 flex-wrap">
{tags.map((tag) => (
<span key={tag} className="px-1.5 py-0.5 rounded-full bg-port-card border border-port-border text-[9px] text-gray-400">
{tag}
</span>
))}
</div>
) : null}
<DescriptionField
entry={entry}
descField={kind.descField || 'description'}
fallbackField={kind.descFieldFallback || null}
max={kind.descFieldMax}
editable={!!onPatchEntry && !locked && !!kind.descField}
onCommit={(v) => onPatchEntry?.(entry.id, { [kind.descField]: v })}
placeholder={`Describe ${entry.name} (image-gen-ready prose)`}
/>
{kind.key === 'places' && onPatchEntry && !locked ? (
<div className="flex flex-wrap items-center gap-2 mt-2">
<ChipPicker
label="INT/EXT"
value={entry.intExt}
options={INT_EXT_OPTIONS}
onChange={(v) => onPatchEntry(entry.id, { intExt: v })}
/>
<ChipPicker
label="Time"
value={entry.timeOfDay}
options={TIME_OF_DAY_OPTIONS}
onChange={(v) => onPatchEntry(entry.id, { timeOfDay: v })}
/>
</div>
) : kind.key === 'places' && (entry.intExt || entry.timeOfDay) ? (
<div className="flex flex-wrap items-center gap-1 mt-2">
{entry.intExt ? <ReadonlyChip>{entry.intExt}</ReadonlyChip> : null}
{entry.timeOfDay ? <ReadonlyChip>{entry.timeOfDay}</ReadonlyChip> : null}
</div>
) : null}
{/* Reveal-gated canon / spoiler scoping (#2178) — every kind. Editable
when a PATCH channel exists and the entry isn't locked. */}
<RevealTimingField
entry={entry}
editable={!!onPatchEntry && !locked}
onPatch={(patch) => onPatchEntry?.(entry.id, patch)}
/>
{kind.key === 'characters' && !showCharacterSheet ? (
<WardrobeSection
wardrobes={Array.isArray(entry.wardrobes) ? entry.wardrobes : []}
editable={!!onPatchEntry && !locked}
onChange={(next) => onPatchEntry?.(entry.id, { wardrobes: next })}
/>
) : null}
{/* Universe-only: extended character detail editor + AI expand action.
Hidden when the caller didn't pass `characterExtensions` (pipeline
series view). Locked characters render read-only inputs. */}
{showCharacterSheet ? (
<CharacterDetailEditor
key={entry.id}
portrait={thumbnail}
entry={entry}
universeId={characterExtensions.universeId}
characters={characterExtensions.castList || []}
onPatch={(patch) => onPatchEntry(entry.id, patch)}
onExpand={characterExtensions.onExpandCharacter ? () => characterExtensions.onExpandCharacter(entry.id) : null}
expanding={!!characterExtensions.expanding}
disabled={locked}
>
<WardrobeSection
wardrobes={Array.isArray(entry.wardrobes) ? entry.wardrobes : []}
editable={!locked}
onChange={(next) => onPatchEntry(entry.id, { wardrobes: next })}
/>
<CharacterReferenceSheetPanel
universeId={characterExtensions.universeId}
entry={entry}
locked={locked}
onSheetCompleted={characterExtensions.onSheetCompleted}
onSheetDeleted={characterExtensions.onSheetDeleted}
onOpenLightbox={(filename) => onPreview?.(filename, { isSheet: true })}
/>
{/* Trained-LoRA link + dataset entry point (machine-local — the
chip resolves from this machine's lora sidecars). */}
<div className="mt-2">
<CharacterLoraChip
entryId={entry.id}
ingredientId={entry.ingredientId || null}
universeId={characterExtensions.universeId}
/>
</div>
</CharacterDetailEditor>
) : null}
{/* Universe-only: object↔character attachment editor (#1288). Hidden when
the caller didn't pass `objectExtensions` (pipeline series view).
Locked objects render read-only inputs. */}
{kind.key === 'objects' && objectExtensions && onPatchEntry ? (
<ObjectAttachmentsEditor
entry={entry}
characters={objectExtensions.castList || []}
onPatch={(patch) => onPatchEntry(entry.id, patch)}
disabled={locked}
/>
) : null}
</>
);
// Icon-only action strip — same visual contract as the variation cards
// (`VariationCard` in `pages/UniverseBuilder.jsx`): `p-1` icon button per
// action, horizontal row, 14px icons, accent hover for primary actions,
// accent-on-locked styling for the lock toggle. Keeps the canon section
// visually consistent with the bucket cards above it.
const actions = (
<div className="flex flex-wrap items-center gap-1 sm:gap-2">
<button
type="button"
onClick={onRender}
disabled={!description.trim() || !!inFlightJobId}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
title={description.trim()
? `Render a canonical reference image for ${entry.name}`
: 'Add a description first'}
aria-label={`Render reference for ${entry.name}`}
>
{inFlightJobId ? <Loader2 size={14} className="animate-spin" /> : <ImagePlus size={14} />}
</button>
{kind.key === 'places' && onRenderCleanPlate ? (
<button
type="button"
onClick={() => onRenderCleanPlate(entry)}
disabled={!description.trim() || !!inFlightJobId}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
title={description.trim()
? `Render an empty-location plate for ${entry.name} — no people, edge-to-edge`
: 'Add a description first'}
aria-label={`Render clean plate for ${entry.name}`}
>
{inFlightJobId ? <Loader2 size={14} className="animate-spin" /> : <Square size={14} />}
</button>
) : null}
{onDescribeImages ? (
<button
type="button"
onClick={() => onDescribeImages(entry)}
disabled={blockedByLock}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
title={blockedByLock
? `Unlock ${entry.name} to apply a generated description`
: `Describe ${entry.name} from a reference image (or several) using a vision model`}
aria-label={`Describe ${entry.name} from images`}
>
<ScanText size={14} />
</button>
) : null}
{onCorrectFromImage ? (
<button
type="button"
onClick={() => onCorrectFromImage(entry)}
disabled={blockedByLock}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
title={blockedByLock
? `Unlock ${entry.name} to apply a corrective reference`
: `Correct ${entry.name}'s description from a reference image and pin it for future renders`}
aria-label={`Correct ${entry.name} from a reference image`}
>
<ImageUp size={14} />
</button>
) : null}
{kind.key === 'characters' && onRefine ? (
<button
type="button"
onClick={() => onRefine(entry.id)}
disabled={refining || refineDisabled || blockedByLock}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
title={blockedByLock
? `Unlock ${entry.name} to refine`
: `AI: rewrite ${entry.name}'s description so they render distinct from every other character`}
aria-label={`AI differentiate ${entry.name}`}
>
{refining ? <Loader2 size={14} className="animate-spin" /> : <WandSparkles size={14} />}
</button>
) : null}
{onToggleLock ? (
<button
type="button"
onClick={() => onToggleLock(entry.id, !locked)}
disabled={togglingLock}
className={`min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 rounded ${locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
title={locked
? `Unlock ${entry.name} so refine / differentiate / re-extract can modify it`
: `Lock ${entry.name} so AI passes don't rewrite it`}
aria-pressed={locked}
>
{togglingLock ? <Loader2 size={14} className="animate-spin" /> : (locked ? <Lock size={14} /> : <Unlock size={14} />)}
</button>
) : null}
{onRemove ? (
// Trailing X, matching the variation + composite-sheet cards so every
// universe bucket removes the same way. Deliberately NOT lock-gated:
// the lock protects the entry from AI rewrites, not from the user
// deciding it doesn't belong in this universe.
<button
type="button"
onClick={() => onRemove(entry.id)}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-error rounded"
title={`Remove ${entry.name} from this universe's canon — rendered images and any Catalog entry are kept`}
aria-label={`Remove ${entry.name}`}
>
<X size={14} />
</button>
) : null}
</div>
);
const footer = (
<>
{(refs.length > 0 || inFlightJobId) ? (
<div className="flex items-center gap-2 mt-2 flex-wrap">
{inFlightJobId ? (
<MediaJobThumb jobId={inFlightJobId} label={`${entry.name} reference`} size="sm" />
) : null}
{refs.map((ref) => {
const isPrimary = entry.primaryImageRef === ref;
const canPin = !!onPatchEntry && !locked;
return (
<div key={ref} className="relative w-16 h-16">
<button
type="button"
onClick={() => onPreview?.(ref)}
title={ref}
className={`w-full h-full bg-port-bg rounded overflow-hidden border ${
isPrimary ? 'border-port-accent' : 'border-port-border hover:border-port-accent/50'
} cursor-zoom-in p-0`}
>
<img
src={`/data/images/${ref}`}
alt={`${entry.name} reference`}
className="w-full h-full object-cover"
loading="lazy"
/>
</button>
{canPin ? (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onPatchEntry(entry.id, { primaryImageRef: isPrimary ? null : ref });
}}
title={isPrimary
? `Unpin ${ref} as primary reference`
: `Pin ${ref} as ${entry.name}'s primary reference`} aria-label={isPrimary
? `Unpin ${ref} as primary reference`
: `Pin ${ref} as ${entry.name}'s primary reference`}
className={`absolute top-0.5 right-0.5 p-0.5 rounded ${
isPrimary
? 'bg-port-accent text-white'
: 'bg-port-bg/80 text-gray-400 hover:text-port-accent'
}`}
>
<Star size={10} fill={isPrimary ? 'currentColor' : 'none'} />
</button>
) : isPrimary ? (
<span
title="Primary reference image"
className="absolute top-0.5 right-0.5 p-0.5 rounded bg-port-accent text-white"
>
<Star size={10} fill="currentColor" />
</span>
) : null}
</div>
);
})}
</div>
) : null}
{usage && usage.length > 0 ? (
<div className="mt-2 text-[10px] text-gray-500">
Appears in:{' '}
{usage.map((u, i) => (
<span key={u.seriesId}>
{i > 0 ? ', ' : ''}
<span className="text-gray-400">{u.seriesName}</span>
<span className="text-gray-600"> ({u.issueCount} {u.issueCount === 1 ? 'issue' : 'issues'})</span>
</span>
))}
</div>
) : null}
</>
);
return (
<EntryCard
locked={locked}
thumbnail={showCharacterSheet ? null : thumbnail}
title={title}
body={body}
actions={actions}
footer={footer}
/>
);
}