Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-3103]): add corrective reference images for universe canon entries

[._.]/ Adam Eivye404104e90d4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 356aac39a4..5883df328f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,3 +9,7 @@
- Failed agent runs are classified far more accurately. A terminal-UI agent's transcript is a repainted *screen*, not a log — it can run to hundreds of kilobytes while containing barely any line breaks — so the analyzer's "look at the recent output" window was quietly reading the entire session. Any keyword anywhere in it, including commands the agent itself typed, decided the verdict: one run reaped for going idle was reported as "Context length exceeded", which blocked its task and auto-filed an investigation for a problem that never happened.
- When the system already knows why a run ended — the idle watchdog fired, the runtime budget ran out, the provider CLI wasn't installed — that is now what gets reported. Only a genuine provider or system error in the transcript can override it.
- Failure snippets shown on an agent's record are now short, readable excerpts centered on the actual error instead of raw terminal escape codes. One failed run had been writing an 816KB blob of control characters into its own record.
+
+## Universe canon corrective reference images
+
+- [issue-3103] Any Cast, Place, or Object entry in a Universe's bible can now take a corrective reference image: upload or pick a photo/render that shows what it should actually look like, and a vision model compares it against the entry's current description and proposes a correction. Reviewing and applying it both fixes the description and pins the image as that entry's reference image, so future renders for it are visually anchored to the correction instead of starting from scratch each time.
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index a327c2fc8d..d70f792b3a 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -11,7 +11,7 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen, ScanText } from 'lucide-react';
+import { Loader2, ImagePlus, ImageUp, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen, ScanText } from 'lucide-react';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import useRowDraft from '../../hooks/useRowDraft';
import useFieldDraft from '../../hooks/useFieldDraft';
@@ -377,6 +377,7 @@ export default function CanonCard({
// 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.
@@ -606,6 +607,20 @@ export default function CanonCard({
<ScanText size={14} />
</button>
) : null}
+ {onCorrectFromImage ? (
+ <button
+ type="button"
+ onClick={() => onCorrectFromImage(entry)}
+ disabled={blockedByLock}
+ className="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"
diff --git a/client/src/components/universe/CorrectiveReferenceModal.jsx b/client/src/components/universe/CorrectiveReferenceModal.jsx
new file mode 100644
index 0000000000..ac01c52033
--- /dev/null
+++ b/client/src/components/universe/CorrectiveReferenceModal.jsx
@@ -0,0 +1,200 @@
+/**
+ * Corrective reference-image modal for ONE canon entry (character/place/object).
+ *
+ * Pick or upload a single gallery image, run vision analysis against the
+ * entry's CURRENT descriptor text (unlike VisionDescribeModal's "Describe",
+ * this corrects rather than describing blind), review the proposed
+ * replacement, then Apply: the reviewed text overwrites the entry's
+ * descriptor field AND the image is pinned as the entry's `primaryImageRef`
+ * — assigning it as that noun's style/reference image so subsequent renders
+ * seed from it.
+ */
+import { useState } from 'react';
+import { ImagePlus, Loader2, Sparkles, X } from 'lucide-react';
+import Modal from '../ui/Modal';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import VisionProviderPicker from './VisionProviderPicker';
+import { KIND_NOUN } from './VisionDescribeModal';
+import toast from '../ui/Toast';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { correctEntityFromImage, applyCanonImageCorrection } from '../../services/apiUniverseBuilder';
+
+export default function CorrectiveReferenceModal({
+ open, kind, entryName, universeId, entryId, onApplied, onClose,
+}) {
+ const [image, setImage] = useState(null);
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [context, setContext] = useState('');
+ const [vision, setVision] = useState({ providerId: '', model: '', hasProviders: false });
+ const [analysis, setAnalysis] = useState(null);
+ const [proposedText, setProposedText] = useState('');
+
+ const noun = KIND_NOUN[kind] || 'subject';
+ const subject = entryName ? `"${entryName}"` : `this ${noun}`;
+
+ const reset = () => {
+ setImage(null);
+ setContext('');
+ setAnalysis(null);
+ setProposedText('');
+ setVision({ providerId: '', model: '', hasProviders: false });
+ };
+ const close = () => {
+ if (analyzing || applying) return;
+ reset();
+ onClose?.();
+ };
+
+ const [analyze, analyzing] = useAsyncAction(async () => {
+ if (!image?.filename || !vision.model) return null;
+ const result = await correctEntityFromImage(universeId, kind, entryId, {
+ image: image.filename,
+ name: entryName || undefined,
+ context: context.trim() || undefined,
+ providerId: vision.providerId || undefined,
+ model: vision.model,
+ }, { silent: true });
+ if (result.locked) {
+ toast.error(`${subject} is locked — unlock it before applying a corrective reference`);
+ return null;
+ }
+ setAnalysis(result);
+ setProposedText(result.proposedDescription || '');
+ return result;
+ }, { errorMessage: 'Correction analysis failed' });
+
+ const [apply, applying] = useAsyncAction(async () => {
+ if (!analysis || !proposedText.trim() || !image?.filename) return null;
+ const result = await applyCanonImageCorrection(universeId, kind, entryId, {
+ description: proposedText.trim(),
+ imageFilename: image.filename,
+ }, { silent: true });
+ toast.success(`Corrected ${subject} and pinned the reference image`);
+ onApplied?.(result);
+ close();
+ return result;
+ }, { errorMessage: 'Applying correction failed' });
+
+ return (
+ <Modal open={open} onClose={close} size="lg" closeOnBackdrop={!analyzing && !applying} usePortal ariaLabel={`Corrective reference for ${subject}`}>
+ <div className="bg-port-card border border-port-border rounded-lg shadow-xl flex flex-col max-h-[85vh]">
+ <div className="flex items-center justify-between px-4 py-3 border-b border-port-border">
+ <h3 className="text-sm font-semibold text-white flex items-center gap-2">
+ <Sparkles size={14} className="text-port-accent" />
+ Corrective reference for {subject}
+ </h3>
+ <button type="button" onClick={close} disabled={analyzing || applying} className="text-gray-500 hover:text-white disabled:opacity-50" aria-label="Close">
+ <X size={16} />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-4 overflow-y-auto">
+ <p className="text-xs text-gray-500">
+ Upload or pick one image that shows what this {noun} actually looks like. A vision model compares it
+ against the current description and proposes a correction; applying it also pins the image as this{' '}
+ {noun}&apos;s reference image for future renders.
+ </p>
+
+ <div>
+ {image ? (
+ <button type="button" onClick={() => { setImage(null); setAnalysis(null); }} className="block" title="Choose another image">
+ <img
+ src={image.preview || `/data/images/${encodeURIComponent(image.filename)}`}
+ alt="Selected corrective reference"
+ className="h-32 w-32 rounded-lg border border-port-border object-cover"
+ />
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setGalleryOpen(true)}
+ className="flex h-32 w-32 flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-port-border text-xs text-gray-400 hover:border-port-accent hover:text-white"
+ >
+ <ImagePlus size={24} />
+ Upload or choose image
+ </button>
+ )}
+ </div>
+
+ <VisionProviderPicker label="Vision model for correction" onChange={setVision} />
+
+ <div>
+ <label htmlFor="corrective-reference-context" className="block text-xs text-gray-500 mb-1">
+ Known context (optional)
+ </label>
+ <input
+ id="corrective-reference-context"
+ type="text"
+ value={context}
+ onChange={(e) => setContext(e.target.value)}
+ placeholder={`Anything the image doesn't make obvious about this ${noun}`}
+ maxLength={2000}
+ className="w-full px-2 py-1.5 text-xs bg-port-bg border border-port-border rounded text-gray-200"
+ />
+ </div>
+
+ {!analysis ? (
+ <button
+ type="button"
+ onClick={analyze}
+ disabled={analyzing || !image?.filename || !vision.model}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent text-white text-sm disabled:opacity-40 disabled:cursor-not-allowed hover:bg-port-accent/90"
+ >
+ {analyzing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {analyzing ? 'Analyzing…' : 'Analyze image'}
+ </button>
+ ) : (
+ <div className="space-y-2">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1">Current description</div>
+ <p className="rounded border border-port-border p-2 text-xs text-gray-400 whitespace-pre-wrap min-h-[4rem]">
+ {analysis.currentDescription || 'None yet'}
+ </p>
+ </div>
+ <div>
+ <label htmlFor="corrective-reference-proposed" className="text-[11px] uppercase tracking-wide text-port-accent mb-1 block">
+ Proposed correction (edit before applying if you like)
+ </label>
+ <textarea
+ id="corrective-reference-proposed"
+ value={proposedText}
+ onChange={(e) => setProposedText(e.target.value)}
+ rows={6}
+ className="w-full rounded border border-port-accent/30 p-2 text-xs text-gray-200 whitespace-pre-wrap bg-port-bg"
+ />
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={apply}
+ disabled={applying || !proposedText.trim()}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent text-white text-sm disabled:opacity-40 disabled:cursor-not-allowed hover:bg-port-accent/90"
+ >
+ {applying ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {applying ? 'Applying…' : 'Apply correction + set as reference'}
+ </button>
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">
+ <button type="button" onClick={close} disabled={analyzing || applying} className="px-3 py-1.5 rounded border border-port-border text-gray-300 text-sm hover:text-white disabled:opacity-50">
+ Close
+ </button>
+ </div>
+ </div>
+
+ <GalleryImagePicker
+ open={galleryOpen}
+ onClose={() => setGalleryOpen(false)}
+ allowUpload
+ onSelect={(item) => {
+ if (!item?.filename) return;
+ setImage({ filename: item.filename, preview: item.previewUrl });
+ setAnalysis(null);
+ }}
+ />
+ </Modal>
+ );
+}
diff --git a/client/src/components/universe/CorrectiveReferenceModal.test.jsx b/client/src/components/universe/CorrectiveReferenceModal.test.jsx
new file mode 100644
index 0000000000..795c2e89fa
--- /dev/null
+++ b/client/src/components/universe/CorrectiveReferenceModal.test.jsx
@@ -0,0 +1,105 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import CorrectiveReferenceModal from './CorrectiveReferenceModal';
+
+const apiMocks = vi.hoisted(() => ({
+ correctEntityFromImage: vi.fn(),
+ applyCanonImageCorrection: vi.fn(),
+}));
+vi.mock('../../services/apiUniverseBuilder', () => apiMocks);
+vi.mock('../imageGen/GalleryImagePicker', () => ({
+ default: ({ open, onSelect }) => (open
+ ? <button onClick={() => onSelect({ filename: 'reference.png', previewUrl: 'data:image/png;base64,x' })}>Select gallery image</button>
+ : null),
+}));
+vi.mock('./VisionProviderPicker', () => ({
+ default: ({ onChange }) => (
+ <button onClick={() => onChange({ providerId: 'ollama', model: 'qwen-vl', hasProviders: true })}>Select vision model</button>
+ ),
+}));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+const baseProps = {
+ open: true, kind: 'character', entryName: 'Vex', universeId: 'uni-1', entryId: 'chr-1',
+ onApplied: () => {}, onClose: () => {},
+};
+
+const pickImageAndModel = () => {
+ fireEvent.click(screen.getByRole('button', { name: /Upload or choose image/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select gallery image' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select vision model' }));
+};
+
+describe('CorrectiveReferenceModal', () => {
+ beforeEach(() => {
+ apiMocks.correctEntityFromImage.mockReset();
+ apiMocks.applyCanonImageCorrection.mockReset();
+ });
+
+ it('analyzes the picked image, shows the diff, and applies the reviewed correction + pins the image', async () => {
+ apiMocks.correctEntityFromImage.mockResolvedValue({
+ descField: 'physicalDescription',
+ currentDescription: 'a short, stocky trader',
+ proposedDescription: 'a tall scavenger in patched leathers',
+ llm: { provider: 'ollama', model: 'qwen-vl' },
+ });
+ apiMocks.applyCanonImageCorrection.mockResolvedValue({
+ universe: { id: 'uni-1' },
+ entry: { id: 'chr-1', physicalDescription: 'a tall scavenger in patched leathers', primaryImageRef: 'reference.png' },
+ });
+ const onApplied = vi.fn();
+ const onClose = vi.fn();
+ render(<CorrectiveReferenceModal {...baseProps} onApplied={onApplied} onClose={onClose} />);
+
+ pickImageAndModel();
+ fireEvent.click(screen.getByRole('button', { name: /Analyze image/i }));
+
+ expect(await screen.findByText('a short, stocky trader')).toBeInTheDocument();
+ const proposed = screen.getByRole('textbox', { name: /Proposed correction/i });
+ expect(proposed.value).toBe('a tall scavenger in patched leathers');
+
+ fireEvent.click(screen.getByRole('button', { name: /Apply correction \+ set as reference/i }));
+
+ await waitFor(() => expect(apiMocks.applyCanonImageCorrection).toHaveBeenCalledWith(
+ 'uni-1', 'character', 'chr-1',
+ expect.objectContaining({ description: 'a tall scavenger in patched leathers', imageFilename: 'reference.png' }),
+ expect.anything(),
+ ));
+ await waitFor(() => expect(onApplied).toHaveBeenCalledWith(
+ expect.objectContaining({ entry: expect.objectContaining({ primaryImageRef: 'reference.png' }) }),
+ ));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('lets the user edit the proposed text before applying', async () => {
+ apiMocks.correctEntityFromImage.mockResolvedValue({
+ descField: 'description', currentDescription: '', proposedDescription: 'a rusted blade', llm: {},
+ });
+ apiMocks.applyCanonImageCorrection.mockResolvedValue({ universe: {}, entry: {} });
+ render(<CorrectiveReferenceModal {...baseProps} kind="object" />);
+
+ pickImageAndModel();
+ fireEvent.click(screen.getByRole('button', { name: /Analyze image/i }));
+ const proposed = await screen.findByRole('textbox', { name: /Proposed correction/i });
+ fireEvent.change(proposed, { target: { value: 'a rusted ceremonial blade' } });
+
+ fireEvent.click(screen.getByRole('button', { name: /Apply correction \+ set as reference/i }));
+ await waitFor(() => expect(apiMocks.applyCanonImageCorrection).toHaveBeenCalledWith(
+ 'uni-1', 'object', 'chr-1',
+ expect.objectContaining({ description: 'a rusted ceremonial blade' }),
+ expect.anything(),
+ ));
+ });
+
+ it('surfaces the locked state and never calls apply', async () => {
+ apiMocks.correctEntityFromImage.mockResolvedValue({ locked: true, entryName: 'Vex' });
+ render(<CorrectiveReferenceModal {...baseProps} />);
+
+ pickImageAndModel();
+ fireEvent.click(screen.getByRole('button', { name: /Analyze image/i }));
+
+ await waitFor(() => expect(apiMocks.correctEntityFromImage).toHaveBeenCalled());
+ expect(screen.queryByRole('textbox', { name: /Proposed correction/i })).not.toBeInTheDocument();
+ expect(apiMocks.applyCanonImageCorrection).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index d813413da5..512d96e362 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -19,6 +19,7 @@ import {
import toast from '../ui/Toast';
import IngredientPicker from '../IngredientPicker';
import VisionDescribeModal from './VisionDescribeModal';
+import CorrectiveReferenceModal from './CorrectiveReferenceModal';
import { linkCatalogIngredient } from '../../services/apiCatalog';
import {
extractUniverseCanon,
@@ -134,6 +135,8 @@ export default function UniverseCanonSection({
const [catalogPickerKind, setCatalogPickerKind] = useState(null);
// `{ kind, entry }` when the vision "Describe from image(s)" modal is open.
const [describeTarget, setDescribeTarget] = useState(null);
+ // `{ kind, entry }` when the corrective-reference modal is open.
+ const [correctTarget, setCorrectTarget] = useState(null);
const [catalogLinking, setCatalogLinking] = useState(false);
// Ingredient ids already embedded in the open kind's canon list — passed to
// the picker so it hides already-linked rows. Only recomputed when the open
@@ -402,11 +405,18 @@ export default function UniverseCanonSection({
baseNegative: baseOpts.negativePrompt,
});
const universeRun = buildUniverseSectionRenderTag(universe, kind.key, entry);
+ // A pinned primaryImageRef (set manually, or via the corrective-reference
+ // flow) seeds the render as an i2i init image so the result stays
+ // anchored to that reference instead of a fresh text-to-image roll every
+ // time. 0.4 mirrors ImageGen's own init-image-strength default — enough
+ // influence to anchor likeness while leaving room for prompt-driven pose/
+ // expression variety.
const queued = await generateImage({
...baseOpts,
prompt: styled.prompt,
negativePrompt: styled.negativePrompt || undefined,
...(universeRun ? { universeRun } : {}),
+ ...(entry.primaryImageRef ? { initImageFile: entry.primaryImageRef, initImageStrength: 0.4 } : {}),
}, { silent: true }).catch((err) => { toast.error(err.message || 'Render failed'); return null; });
if (!queued?.jobId || !mountedRef.current) return;
setRenderingJobs((prev) => ({ ...prev, [entry.id]: queued.jobId }));
@@ -806,6 +816,7 @@ export default function UniverseCanonSection({
onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
onRenderCleanPlate={(entry) => handleRenderCleanPlate(kind, entry)}
onDescribeImages={(entry) => setDescribeTarget({ kind, entry })}
+ onCorrectFromImage={(entry) => setCorrectTarget({ kind, entry })}
seriesNameMap={usage?.seriesNameMap || null}
onBulkLock={(nextLocked) => handleBulkLockKind(kind, nextLocked)}
bulkLocking={bulkLockingKindKey === kind.key}
@@ -867,11 +878,27 @@ export default function UniverseCanonSection({
onClose={() => setDescribeTarget(null)}
/>
) : null}
+
+ {/* Corrective reference image — analyzes an uploaded image against the
+ entry's current description, then on Apply overwrites the
+ description AND pins the image as the entry's primaryImageRef so
+ future renders (handleRenderRef) i2i-seed from it. */}
+ {correctTarget ? (
+ <CorrectiveReferenceModal
+ open
+ kind={correctTarget.kind.apiKind}
+ entryName={correctTarget.entry.name}
+ universeId={universeId}
+ entryId={correctTarget.entry.id}
+ onApplied={(result) => { if (result?.universe) onUniverseChange(result.universe); }}
+ onClose={() => setCorrectTarget(null)}
+ />
+ ) : null}
</section>
);
}
-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, onDescribeImages = null, seriesNameMap, onBulkLock, bulkLocking, fullList, castList = [], externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false, onAddEntry = null, creating = false }) {
+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, onDescribeImages = null, onCorrectFromImage = null, seriesNameMap, onBulkLock, bulkLocking, fullList, castList = [], externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false, onAddEntry = null, creating = false }) {
// 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
@@ -1083,6 +1110,7 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
onDescribeImages={onDescribeImages}
+ onCorrectFromImage={onCorrectFromImage}
seriesNameMap={seriesNameMap}
characterExtensions={characterExtensions
? { ...characterExtensions, expanding: expandingId === entry.id }
diff --git a/client/src/components/universe/VisionDescribeModal.jsx b/client/src/components/universe/VisionDescribeModal.jsx
index f19d9344e5..fa15bf2071 100644
--- a/client/src/components/universe/VisionDescribeModal.jsx
+++ b/client/src/components/universe/VisionDescribeModal.jsx
@@ -32,7 +32,9 @@ import { describeEntityFromImages, expandEntityFromImages } from '../../services
// 400s.
const MAX_IMAGES = 8;
-const KIND_NOUN = { character: 'character', place: 'place', object: 'object' };
+// Shared with CorrectiveReferenceModal, which offers the same vision actions
+// against a different (corrective, not blank-fill) analysis.
+export const KIND_NOUN = { character: 'character', place: 'place', object: 'object' };
// camelCase field name → human label for the attribute review list.
const humanizeField = (f) => f
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 43c2e3abf5..afd41e3166 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -107,6 +107,37 @@ export const expandEntityFromImages = (universeId, entryId, {
},
);
+// Corrective vision analysis for ONE canon entry: given the entry's current
+// descriptor text as context, a vision model proposes a CORRECTED
+// replacement (unlike expandEntityFromImages, which only fills still-blank
+// fields). Review-only — resolves to `{ descField, currentDescription,
+// proposedDescription, llm, imageFilename }` (or `{ locked: true, entryName }`);
+// `applyCanonImageCorrection` persists the reviewed text and pins the image.
+export const correctEntityFromImage = (universeId, kind, entryId, {
+ image, name, context, providerId, model,
+} = {}, options = {}) => request(
+ `/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/correct-from-image`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ image, name, context, providerId, model }),
+ ...options,
+ },
+);
+
+// Persist a reviewed corrective-image analysis: overwrites the entry's
+// descriptor field with `description` AND pins `imageFilename` as the
+// entry's `primaryImageRef` in one atomic write.
+export const applyCanonImageCorrection = (universeId, kind, entryId, {
+ description, imageFilename,
+} = {}, options = {}) => request(
+ `/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/apply-image-correction`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ description, imageFilename }),
+ ...options,
+ },
+);
+
// Caller should dedupe the returned variations against its local list before
// appending — the local list may have changed during the request.
export const generateCategoryVariations = ({
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 88aed358a6..dff80e67dc 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -10,6 +10,8 @@
* POST /api/universe-builder/describe-from-images → { description, llm }
* POST /api/universe-builder/analyze-style-reference → { reference, proposed, diff, rationale, llm }
* POST /api/universe-builder/:id/characters/:entryId/expand-from-images → { fields, updatedFields, llm }
+ * POST /api/universe-builder/:id/canon/:kind/:entryId/correct-from-image → { descField, currentDescription, proposedDescription, llm } | { locked, entryName }
+ * POST /api/universe-builder/:id/canon/:kind/:entryId/apply-image-correction → { universe, entry }
* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }
* GET /api/universe-builder/:id/runs → Run[]
*/
@@ -29,7 +31,7 @@ import {
import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/storyBible.js';
import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';
import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
-import { describeEntityFromImages, VISION_KINDS, VISION_MAX_IMAGES } from '../services/universeVisionDescribe.js';
+import { describeEntityFromImages, correctEntityFromImage, VISION_KINDS, VISION_MAX_IMAGES } from '../services/universeVisionDescribe.js';
import { expandEntityFromImages, VISION_EXPAND_MAX_IMAGES } from '../services/universeVisionExpand.js';
import { analyzeUniverseStyleReference } from '../services/universeStyleReference.js';
import { sanitizeFilename, PATHS, resolveGalleryImage } from '../lib/fileUtils.js';
@@ -460,6 +462,29 @@ function resolveImageSources(images) {
});
}
+// Resolve a SINGLE gallery filename to an absolute path, rejecting a
+// traversal attempt or an unknown file up front. Shared by the two
+// single-gallery-image vision routes (`analyze-style-reference`,
+// `correct-from-image`) that resolve one reference image rather than the
+// mixed upload/gallery list `resolveImageSources` handles.
+function resolveGalleryImageOrThrow(filename) {
+ const imageFilename = sanitizeFilename(filename);
+ if (imageFilename !== filename) {
+ throw new ServerError(`Invalid gallery image filename: ${filename}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+ const imagePath = resolveGalleryImage(imageFilename);
+ if (!imagePath) {
+ throw new ServerError(`Gallery image not found: ${imageFilename} — upload it again and retry.`, {
+ status: 400,
+ code: 'GALLERY_IMAGE_NOT_FOUND',
+ });
+ }
+ return { imageFilename, imagePath };
+}
+
// Vision-to-prose: turn one or more reference images of a character/place/
// object into an image-gen-ready prose description (multiple images → the
// shared/common description). Stateless — the client decides which entry
@@ -497,20 +522,7 @@ const analyzeStyleReferenceSchema = z.object({
// reference-and-adopt in the client.
router.post('/analyze-style-reference', asyncHandler(async (req, res) => {
const body = validateRequest(analyzeStyleReferenceSchema, req.body ?? {});
- const imageFilename = sanitizeFilename(body.image);
- if (imageFilename !== body.image) {
- throw new ServerError(`Invalid gallery image filename: ${body.image}`, {
- status: 400,
- code: 'VALIDATION_ERROR',
- });
- }
- const imagePath = resolveGalleryImage(imageFilename);
- if (!imagePath) {
- throw new ServerError(`Gallery image not found: ${imageFilename} — upload it again and retry.`, {
- status: 400,
- code: 'GALLERY_IMAGE_NOT_FOUND',
- });
- }
+ const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);
res.json(await analyzeUniverseStyleReference({
...body,
imagePath,
@@ -763,6 +775,53 @@ router.post('/:id/characters/:entryId/expand-from-images', asyncHandler(async (r
res.json(result);
}));
+// Corrective vision analysis for ONE canon entry (character/place/object):
+// given the entry's CURRENT descriptor text as context, a vision model
+// proposes a CORRECTED replacement — unlike expand-from-images (fills only
+// still-blank fields) or describe-from-images (describes blind), this
+// overwrites existing text where the image contradicts it. Review-only:
+// returns the proposed text for the client to show alongside the current
+// value; `apply-image-correction` (below) persists it.
+const correctFromImageSchema = z.object({
+ image: z.string().trim().min(1).max(300),
+ name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),
+ context: z.string().trim().max(2000).optional(),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+router.post('/:id/canon/:kind/:entryId/correct-from-image', asyncHandler(async (req, res) => {
+ const { kind } = validateRequest(lockParamsSchema, req.params);
+ const body = validateRequest(correctFromImageSchema, req.body ?? {});
+ const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);
+ const result = await correctEntityFromImage({
+ universeId: req.params.id,
+ entryId: req.params.entryId,
+ kind,
+ name: body.name,
+ context: body.context,
+ screenshot: imagePath,
+ providerId: body.providerId,
+ model: body.model,
+ }).catch((err) => { throw mapServiceError(err); });
+ res.json({ ...result, imageFilename });
+}));
+
+// Persist a reviewed corrective-image analysis: overwrites the entry's
+// descriptor field with the reviewed text AND pins the analyzed image as the
+// entry's `primaryImageRef` — assigning it as that noun's style/reference
+// image so subsequent renders (client-side i2i seeding) use it.
+const applyImageCorrectionSchema = z.object({
+ description: z.string().trim().min(1).max(BIBLE_LIMITS.NOTES_MAX),
+ imageFilename: z.string().trim().min(1).max(300),
+});
+router.post('/:id/canon/:kind/:entryId/apply-image-correction', asyncHandler(async (req, res) => {
+ const { kind } = validateRequest(lockParamsSchema, req.params);
+ const body = validateRequest(applyImageCorrectionSchema, req.body ?? {});
+ const result = await canonSvc.applyCanonImageCorrection(req.params.id, kind, req.params.entryId, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Generate one of the character reference-sheet variants from a structured
// TEXT prompt — no init image required, so it works across codex / local
// backends. The `variant` field selects which prompt-builder + storage slot
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index 6a9d068df0..aa4ab3e448 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -34,9 +34,24 @@ vi.mock('fs', async (importActual) => {
// Stub the vision/refine services so the route tests exercise the image-source
// resolution + schema glue, not a real LLM. Real constants pass through.
const describeEntityFromImagesMock = vi.fn(async () => ({ description: 'mock prose', llm: { provider: 'mock', model: null } }));
+const correctEntityFromImageMock = vi.fn(async () => ({
+ descField: 'physicalDescription', currentDescription: 'old', proposedDescription: 'corrected', llm: { provider: 'mock', model: null },
+}));
vi.mock('../services/universeVisionDescribe.js', async () => {
const actual = await vi.importActual('../services/universeVisionDescribe.js');
- return { ...actual, describeEntityFromImages: (...args) => describeEntityFromImagesMock(...args) };
+ return {
+ ...actual,
+ describeEntityFromImages: (...args) => describeEntityFromImagesMock(...args),
+ correctEntityFromImage: (...args) => correctEntityFromImageMock(...args),
+ };
+});
+const applyCanonImageCorrectionMock = vi.fn(async (_universeId, kind, entryId, body) => ({
+ universe: { id: _universeId },
+ entry: { id: entryId, [kind === 'character' ? 'physicalDescription' : 'description']: body.description, primaryImageRef: body.imageFilename },
+}));
+vi.mock('../services/universeCanon.js', async () => {
+ const actual = await vi.importActual('../services/universeCanon.js');
+ return { ...actual, applyCanonImageCorrection: (...args) => applyCanonImageCorrectionMock(...args) };
});
const expandEntityFromImagesMock = vi.fn(async () => ({ fields: { pronouns: 'she/her' }, updatedFields: ['pronouns'], llm: { provider: 'mock', model: null } }));
vi.mock('../services/universeVisionExpand.js', async () => {
@@ -1227,6 +1242,67 @@ describe('universe-builder routes', () => {
});
});
+ describe('POST /:id/canon/:kind/:entryId/correct-from-image', () => {
+ it('resolves the gallery image and forwards universeId/entryId/kind, echoing the filename', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/canon/character/chr-1/correct-from-image')
+ .send({ image: 'g.png', name: 'Vex' });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(expect.objectContaining({
+ proposedDescription: 'corrected', imageFilename: 'g.png',
+ }));
+ expect(correctEntityFromImageMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ universeId: 'uni-1', entryId: 'chr-1', kind: 'character', name: 'Vex', screenshot: '/mock/data/images/g.png',
+ }),
+ );
+ });
+
+ it('400 GALLERY_IMAGE_NOT_FOUND for a missing gallery image, without invoking the service', async () => {
+ correctEntityFromImageMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/canon/place/plc-1/correct-from-image')
+ .send({ image: 'missing.png' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('GALLERY_IMAGE_NOT_FOUND');
+ expect(correctEntityFromImageMock).not.toHaveBeenCalled();
+ });
+
+ it('400s an invalid kind before invoking the service', async () => {
+ correctEntityFromImageMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/canon/monster/chr-1/correct-from-image')
+ .send({ image: 'g.png' });
+ expect(res.status).toBe(400);
+ expect(correctEntityFromImageMock).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('POST /:id/canon/:kind/:entryId/apply-image-correction', () => {
+ it('persists the reviewed description + image filename via canonSvc', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/canon/character/chr-1/apply-image-correction')
+ .send({ description: 'a corrected description', imageFilename: 'g.png' });
+ expect(res.status).toBe(200);
+ expect(res.body.entry).toEqual(expect.objectContaining({
+ id: 'chr-1', physicalDescription: 'a corrected description', primaryImageRef: 'g.png',
+ }));
+ expect(applyCanonImageCorrectionMock).toHaveBeenCalledWith(
+ 'uni-1', 'character', 'chr-1',
+ expect.objectContaining({ description: 'a corrected description', imageFilename: 'g.png' }),
+ );
+ });
+
+ it('rejects a blank description before invoking the service', async () => {
+ applyCanonImageCorrectionMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/canon/character/chr-1/apply-image-correction')
+ .send({ description: ' ', imageFilename: 'g.png' });
+ expect(res.status).toBe(400);
+ expect(applyCanonImageCorrectionMock).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /refine-prompts (style-reference image)', () => {
it('resolves the image filename to an absolute path before the service', async () => {
const res = await request(buildApp())
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index a4b74e2b60..0fad965f80 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -205,12 +205,12 @@ export function summarizeCanonExtraction({ results, failures, provider, model, e
// Which field holds a kind's renderable description. Characters carry
// `physicalDescription` (legacy `description` is the read-fallback);
// places/objects use `description`. Mirrors NounsStage's `descFor` source.
-const DESC_FIELD = Object.freeze({
+export const DESC_FIELD = Object.freeze({
[BIBLE_KIND.CHARACTER]: 'physicalDescription',
[BIBLE_KIND.PLACE]: 'description',
[BIBLE_KIND.OBJECT]: 'description',
});
-const DESC_LIMIT = Object.freeze({
+export const DESC_LIMIT = Object.freeze({
[BIBLE_KIND.CHARACTER]: BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,
[BIBLE_KIND.PLACE]: BIBLE_LIMITS.PLACE_DESCRIPTION_MAX,
[BIBLE_KIND.OBJECT]: BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX,
@@ -551,6 +551,62 @@ export async function setCanonEntryLock(universeId, kind, entryId, locked) {
return { universe: updated, entry };
}
+/**
+ * Apply a reviewed corrective-image analysis (`universeVisionDescribe.correctEntityFromImage`)
+ * to one canon entry: overwrite its descriptor field with the reviewed
+ * correction AND pin the analyzed image as the entry's `primaryImageRef` —
+ * assigning it as that noun's style/reference image so subsequent renders
+ * seed from it. Both writes land atomically via the mutator form, so a
+ * concurrent render-completion `imageRefs[]` append (landing between analyze
+ * and apply) can't be clobbered by a stale read.
+ */
+export async function applyCanonImageCorrection(universeId, kind, entryId, { description, imageFilename } = {}) {
+ if (!BIBLE_KINDS.includes(kind)) {
+ throw new ServerError(
+ `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
+ { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
+ );
+ }
+ const trimmedDescription = typeof description === 'string' ? description.trim().slice(0, DESC_LIMIT[kind]) : '';
+ if (!trimmedDescription) {
+ throw new ServerError('A corrected description is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (typeof imageFilename !== 'string' || !imageFilename.trim()) {
+ throw new ServerError('An image filename is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const field = BIBLE_FIELD[kind];
+ const descField = DESC_FIELD[kind];
+ let found = false;
+ let wasLocked = false;
+ const updated = await updateUniverse(universeId, (cur) => {
+ const list = Array.isArray(cur[field]) ? cur[field] : [];
+ const idx = list.findIndex((e) => e.id === entryId);
+ if (idx < 0) return null;
+ found = true;
+ const target = list[idx];
+ if (target.locked === true) { wasLocked = true; return null; }
+ const imageRefs = Array.isArray(target.imageRefs) ? target.imageRefs : [];
+ const nextImageRefs = imageRefs.includes(imageFilename) ? imageRefs : [...imageRefs, imageFilename];
+ const nextList = list.map((e, i) => (i === idx
+ ? { ...e, [descField]: trimmedDescription, imageRefs: nextImageRefs, primaryImageRef: imageFilename }
+ : e));
+ return { [field]: nextList };
+ });
+ if (!found) {
+ throw new ServerError(`Canon ${kind} ${entryId} not found in universe`, {
+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',
+ });
+ }
+ if (wasLocked) {
+ throw new ServerError(`This ${kind} is locked — unlock it before applying a correction`, {
+ status: 409, code: 'UNIVERSE_CANON_LOCKED',
+ });
+ }
+ const entry = (updated[field] || []).find((e) => e.id === entryId) || null;
+ return { universe: updated, entry };
+}
+
/**
* Bulk-set the `locked` flag on every canon entry of a single kind. Returns
* the updated universe plus the count of entries whose lock state actually
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index c4c5521886..8b3a352b98 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -123,6 +123,76 @@ describe('universeCanon — setCanonEntryLock', () => {
});
});
+describe('universeCanon — applyCanonImageCorrection', () => {
+ it('overwrites the descriptor field and pins the image as primaryImageRef', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'stale description', imageRefs: ['old.png'], locked: false },
+ ]);
+ const entryId = w.characters[0].id;
+ const { entry } = await canonSvc.applyCanonImageCorrection(w.id, 'character', entryId, {
+ description: 'a corrected description', imageFilename: 'new.png',
+ });
+ expect(entry.physicalDescription).toBe('a corrected description');
+ expect(entry.imageRefs).toEqual(['old.png', 'new.png']);
+ expect(entry.primaryImageRef).toBe('new.png');
+ // Persisted: a fresh read reflects the same correction.
+ const reread = (await svc.listUniverses())[0];
+ const rereadEntry = reread.characters.find((c) => c.id === entryId);
+ expect(rereadEntry.physicalDescription).toBe('a corrected description');
+ expect(rereadEntry.primaryImageRef).toBe('new.png');
+ });
+
+ it('does not duplicate the image if it is already in imageRefs', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'stale', imageRefs: ['already-there.png'], locked: false },
+ ]);
+ const entryId = w.characters[0].id;
+ const { entry } = await canonSvc.applyCanonImageCorrection(w.id, 'character', entryId, {
+ description: 'corrected', imageFilename: 'already-there.png',
+ });
+ expect(entry.imageRefs).toEqual(['already-there.png']);
+ expect(entry.primaryImageRef).toBe('already-there.png');
+ });
+
+ it('rejects a locked entry with a 409-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'stale', locked: true },
+ ]);
+ await expect(
+ canonSvc.applyCanonImageCorrection(w.id, 'character', w.characters[0].id, {
+ description: 'corrected', imageFilename: 'new.png',
+ }),
+ ).rejects.toMatchObject({ status: 409, code: 'UNIVERSE_CANON_LOCKED' });
+ });
+
+ it('rejects unknown kind with a 400-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'stale' }]);
+ await expect(
+ canonSvc.applyCanonImageCorrection(w.id, 'monster', w.characters[0].id, {
+ description: 'corrected', imageFilename: 'new.png',
+ }),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' });
+ });
+
+ it('rejects unknown entry with a 404-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'stale' }]);
+ await expect(
+ canonSvc.applyCanonImageCorrection(w.id, 'character', 'chr-not-real', {
+ description: 'corrected', imageFilename: 'new.png',
+ }),
+ ).rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });
+ });
+
+ it('rejects a blank description', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'stale' }]);
+ await expect(
+ canonSvc.applyCanonImageCorrection(w.id, 'character', w.characters[0].id, {
+ description: ' ', imageFilename: 'new.png',
+ }),
+ ).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ });
+});
+
describe('universeCanon — setCanonKindLockAll', () => {
it('locks every entry of the kind, counts only entries whose state changed', async () => {
// Two already-locked + one explicitly-unlocked: only the unlocked entry
diff --git a/server/services/universeVisionDescribe.js b/server/services/universeVisionDescribe.js
index cdcd67f9cc..f2141ee279 100644
--- a/server/services/universeVisionDescribe.js
+++ b/server/services/universeVisionDescribe.js
@@ -21,6 +21,9 @@
import { resolveAPIProvider, stripCodeFences } from '../lib/aiProvider.js';
import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';
import { ServerError } from '../lib/errorHandler.js';
+import { getUniverse } from './universeBuilder.js';
+import { BIBLE_FIELD } from '../lib/storyBible.js';
+import { DESC_FIELD, DESC_LIMIT } from './universeCanon.js';
// Singular kind → render-prompt focus. Mirrors the descriptor emphasis the
// canon render path already uses (CanonCard's descField placeholders).
@@ -47,6 +50,12 @@ const KIND_FOCUS = {
'Focus on the object: overall form and silhouette, size, materials, color, texture, wear/condition, moving parts or mechanisms, and distinctive markings. Ignore the background and surroundings.',
};
+// Shared closing clause every vision prompt in this file appends when the
+// caller supplies known context to disambiguate the subject.
+const buildKnownContextSuffix = (context) => (context && context.trim()
+ ? `\n\nKnown context (use it to disambiguate, do not contradict the images): ${context.trim()}`
+ : '');
+
/**
* Build the vision prompt. The model is told to return ONE prose paragraph
* suitable for a Stable-Diffusion-style image generator — no markdown, no
@@ -61,15 +70,60 @@ function buildVisionPrompt({ kind, name, context, imageCount }) {
? `You are looking at ${imageCount} reference images of the same ${noun}${name ? ` (${subject})` : ''}. They show the same subject under different conditions (angle, lighting, framing, background). Identify the visual traits that stay CONSISTENT across all of them and describe that single shared subject. Ignore differences that are incidental to a particular shot (pose, camera angle, background, lighting).`
: `You are looking at a reference image of ${subject}. Describe what you see.`;
- const ctx = context && context.trim()
- ? `\n\nKnown context (use it to disambiguate, do not contradict the images): ${context.trim()}`
- : '';
-
return `${intro}
${focus}
-Write a SINGLE paragraph of image-generation-ready prose (roughly 40–120 words) describing ${subject}. Pack it with concrete, renderable visual detail — comma-separated descriptive phrases work well. Do NOT include markdown, headings, bullet points, a "Description:" label, camera/photography jargon, or any commentary about the images themselves. Output only the description.${ctx}`;
+Write a SINGLE paragraph of image-generation-ready prose (roughly 40–120 words) describing ${subject}. Pack it with concrete, renderable visual detail — comma-separated descriptive phrases work well. Do NOT include markdown, headings, bullet points, a "Description:" label, camera/photography jargon, or any commentary about the images themselves. Output only the description.${buildKnownContextSuffix(context)}`;
+}
+
+/**
+ * Run a vision-analysis prompt against a single-image or multi-image
+ * screenshot set and return the cleaned prose + the provider/model that
+ * actually ran. Shared by `describeEntityFromImages` and
+ * `correctEntityFromImage` — both resolve an API-vision provider, run the
+ * prompt, reject a silent CLI/TUI fallback that dropped the images, and
+ * reject an empty result the same way; only the prompt text and the
+ * unavailable/empty error copy differ per caller.
+ */
+async function runVisionTextPrompt({
+ prompt, source, providerId, model, screenshots, unavailableMessage, emptyMessage,
+}) {
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, { message: unavailableMessage, code: 'NO_API_PROVIDER', status: 503 });
+
+ const result = await runPromptThroughProvider({
+ provider,
+ prompt,
+ source,
+ // `model || undefined` so an empty-string UI sentinel falls through to
+ // the provider's default rather than resolving to a bogus model id.
+ model: model || undefined,
+ screenshots,
+ });
+
+ // The runner can swap providers two ways: a proactive swap inside createRun
+ // (when the chosen API provider was already benched — leaves
+ // usedFallback/fallbackProvider UNSET) and a retry fallback after a failure
+ // (sets them). Both surface the provider that actually ran as `result.provider`.
+ // A CLI/TUI provider has no vision path and silently drops the images, so the
+ // completion would be prose hallucinated from the text prompt alone — reject
+ // it outright (resolving an API provider up front was meant to guarantee the
+ // model actually sees the references).
+ const ranProvider = assertVisionRunUsedImages(result, provider);
+
+ const text = stripCodeFences(result.text || '').trim();
+ if (!text) {
+ throw new ServerError(emptyMessage, { status: 502, code: 'VISION_EMPTY' });
+ }
+
+ return {
+ text,
+ // Report the provider/model that ACTUALLY ran (a proactive or retry swap
+ // may have changed it), so the UI's picker can reflect reality instead of
+ // the request.
+ llm: { provider: ranProvider.id || provider.id, model: result.model || null },
+ };
}
/**
@@ -103,54 +157,112 @@ export async function describeEntityFromImages({ kind, name, context, screenshot
});
}
- const provider = await resolveAPIProvider(providerId);
- assertProvider(provider, {
- message:
+ const { text: description, llm } = await runVisionTextPrompt({
+ prompt: buildVisionPrompt({ kind, name, context, imageCount: images.length }),
+ source: 'universe-vision-describe',
+ providerId,
+ model,
+ screenshots: images,
+ unavailableMessage:
'Describing an image needs an API-based AI provider with a vision-capable model (e.g. Ollama with a llava/qwen-vl model, LM Studio, or an OpenAI-compatible endpoint). Configure one under Settings → Providers.',
- code: 'NO_API_PROVIDER',
- status: 503,
+ emptyMessage: 'The vision model returned an empty description — try a different model or clearer images.',
});
- const prompt = buildVisionPrompt({ kind, name, context, imageCount: images.length });
+ return { description, llm };
+}
- const result = await runPromptThroughProvider({
- provider,
- prompt,
- source: 'universe-vision-describe',
- // `model || undefined` so an empty-string UI sentinel falls through to the
- // provider's default rather than resolving to a bogus model id.
- model: model || undefined,
- screenshots: images,
- });
+/**
+ * Build the corrective vision prompt. Unlike `buildVisionPrompt` (describe
+ * blind), this hands the model the entry's CURRENT descriptor text as context
+ * and asks it to correct only what the image contradicts — preserving
+ * detail the image can't see or doesn't dispute.
+ */
+function buildVisionCorrectPrompt({ kind, name, context, currentDescription }) {
+ const noun = KIND_NOUN[kind];
+ const focus = KIND_FOCUS[kind];
+ const subject = name ? `the ${noun} "${name}"` : `this ${noun}`;
- // The runner can swap providers two ways: a proactive swap inside createRun
- // (when the chosen API provider was already benched — leaves
- // usedFallback/fallbackProvider UNSET) and a retry fallback after a failure
- // (sets them). Both surface the provider that actually ran as `result.provider`.
- // A CLI/TUI provider has no vision path and silently drops the images, so the
- // completion would be prose hallucinated from the text prompt alone — reject
- // it outright (resolving an API provider up front was meant to guarantee the
- // model actually sees the references).
- const ranProvider = assertVisionRunUsedImages(result, provider);
+ const currentBlock = currentDescription
+ ? `The current description on file for ${subject} is:\n"${currentDescription}"\n\nCompare it against the attached image. Where the image CONTRADICTS the current description, correct it. Preserve any part of the current description the image does not contradict — it may capture detail (personality-adjacent phrasing, texture/material notes not fully visible, etc.) worth keeping.`
+ : `${subject} has no description on file yet — write one from the image.`;
+
+ return `You are looking at a corrective reference image for ${subject}. ${focus}
+
+${currentBlock}
+
+Write a SINGLE paragraph of image-generation-ready prose (roughly 40–120 words) describing ${subject} as it should read AFTER your correction. Pack it with concrete, renderable visual detail — comma-separated descriptive phrases work well. Do NOT include markdown, headings, bullet points, a "Description:" label, camera/photography jargon, or any commentary about the images themselves. Output only the corrected description.${buildKnownContextSuffix(context)}`;
+}
- const description = stripCodeFences(result.text || '').trim();
- if (!description) {
- throw new ServerError('The vision model returned an empty description — try a different model or clearer images.', {
- status: 502,
- code: 'VISION_EMPTY',
+/**
+ * Corrective vision analysis for ONE canon entry (character/place/object).
+ * Like `describeEntityFromImages`, but grounded in the entry's CURRENT
+ * descriptor text: the model corrects what the image contradicts instead of
+ * describing blind, and preserves detail the image doesn't dispute. Unlike
+ * `expandEntityFromImages` (fills only still-blank fields), this OVERWRITES
+ * the primary descriptor field — the point is to fix a wrong/outdated render
+ * anchor, not just fill gaps.
+ *
+ * Stateless / review-only: returns the proposed replacement text for the
+ * caller to show alongside the current value. Persisting the reviewed text
+ * — together with pinning the analyzed image as the entry's
+ * `primaryImageRef` so it seeds future i2i renders — happens via
+ * `universeCanon.applyCanonImageCorrection`.
+ *
+ * @param {object} args
+ * @param {string} args.universeId
+ * @param {string} args.entryId
+ * @param {'character'|'place'|'object'} args.kind
+ * @param {string} [args.name] — entity name, for prompt context (falls back
+ * to the entry's own name)
+ * @param {string} [args.context] — extra known context to disambiguate
+ * @param {string} args.screenshot — a single image path the runner can load
+ * (an absolute gallery path, or a bare filename under data/screenshots)
+ * @param {string} [args.providerId] — preferred API provider id
+ * @param {string} [args.model] — preferred model id
+ * @returns {Promise<object>} `{ descField, currentDescription, proposedDescription, llm }`,
+ * or `{ locked: true, entryName }` when the entry is locked.
+ */
+export async function correctEntityFromImage({
+ universeId, entryId, kind, name, context, screenshot, providerId, model,
+} = {}) {
+ if (!VISION_KINDS.includes(kind)) {
+ throw new ServerError(`Unsupported kind "${kind}" — expected one of ${VISION_KINDS.join(', ')}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
});
}
+ if (typeof screenshot !== 'string' || !screenshot.trim()) {
+ throw new ServerError('An image is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
- return {
- description,
- // Report the provider/model that ACTUALLY ran (a proactive or retry swap
- // may have changed it), so the UI's picker can reflect reality instead of
- // the request.
- llm: {
- provider: ranProvider.id || provider.id,
- model: result.model || null,
- },
- };
+ const universe = await getUniverse(universeId);
+ const list = Array.isArray(universe[BIBLE_FIELD[kind]]) ? universe[BIBLE_FIELD[kind]] : [];
+ const target = list.find((e) => e.id === entryId);
+ if (!target) {
+ throw new ServerError(`${kind} ${entryId} not found in universe`, {
+ status: 404,
+ code: 'UNIVERSE_CANON_NOT_FOUND',
+ });
+ }
+ if (target.locked === true) {
+ return { locked: true, entryName: target.name };
+ }
+
+ const descField = DESC_FIELD[kind];
+ const currentDescription = (target[descField] || '').trim().slice(0, DESC_LIMIT[kind]);
+
+ const { text: proposedDescription, llm } = await runVisionTextPrompt({
+ prompt: buildVisionCorrectPrompt({ kind, name: name || target.name, context, currentDescription }),
+ source: 'universe-vision-correct',
+ providerId,
+ model,
+ screenshots: [screenshot],
+ unavailableMessage:
+ 'Correcting from an image needs an API-based AI provider with a vision-capable model (e.g. Ollama with a llava/qwen-vl model, LM Studio, or an OpenAI-compatible endpoint). Configure one under Settings → Providers.',
+ emptyMessage: 'The vision model returned an empty correction — try a different model or clearer image.',
+ });
+
+ return { descField, currentDescription, proposedDescription, llm };
}
-export const __testing = { buildVisionPrompt };
+export const __testing = { buildVisionPrompt, buildVisionCorrectPrompt };
diff --git a/server/services/universeVisionDescribe.test.js b/server/services/universeVisionDescribe.test.js
index 980d4e3cd7..a3e7019f6b 100644
--- a/server/services/universeVisionDescribe.test.js
+++ b/server/services/universeVisionDescribe.test.js
@@ -14,15 +14,31 @@ vi.mock('../lib/promptRunner.js', async (importActual) => {
return { ...actual, runPromptThroughProvider: vi.fn() };
});
+// getUniverse is the only universeBuilder surface correctEntityFromImage
+// touches (review-only — it never writes).
+vi.mock('./universeBuilder.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, getUniverse: vi.fn() };
+});
+
const aiProvider = await import('../lib/aiProvider.js');
const promptRunner = await import('../lib/promptRunner.js');
-const { describeEntityFromImages, VISION_KINDS, VISION_MAX_IMAGES, __testing } = await import('./universeVisionDescribe.js');
+const universeBuilder = await import('./universeBuilder.js');
+const {
+ describeEntityFromImages, correctEntityFromImage, VISION_KINDS, VISION_MAX_IMAGES, __testing,
+} = await import('./universeVisionDescribe.js');
const apiProvider = { id: 'ollama', type: 'api', defaultModel: 'llava' };
+const makeUniverse = (overrides = {}) => ({
+ id: 'uni-1',
+ characters: [{ id: 'chr-1', name: 'Vex', physicalDescription: 'a tall scavenger in patched leathers', ...overrides }],
+});
+
beforeEach(() => {
vi.clearAllMocks();
aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ universeBuilder.getUniverse.mockResolvedValue(makeUniverse());
promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'a weathered scavenger', runId: 'r1', model: 'llava' });
});
@@ -134,3 +150,73 @@ describe('describeEntityFromImages', () => {
expect(VISION_KINDS).toEqual(['character', 'place', 'object']);
});
});
+
+describe('buildVisionCorrectPrompt', () => {
+ it('hands the model the current description and asks it to correct contradictions', () => {
+ const p = __testing.buildVisionCorrectPrompt({
+ kind: 'character', name: 'Vex', currentDescription: 'a short, stocky trader',
+ });
+ expect(p).toMatch(/corrective reference image/);
+ expect(p).toMatch(/current description on file for the character "Vex" is:\n"a short, stocky trader"/);
+ expect(p).toMatch(/CONTRADICTS the current description, correct it/);
+ });
+
+ it('writes from the image alone when there is no current description', () => {
+ const p = __testing.buildVisionCorrectPrompt({ kind: 'place', name: 'The Foundry', currentDescription: '' });
+ expect(p).toMatch(/has no description on file yet — write one from the image/);
+ });
+
+ it('folds known context into the prompt', () => {
+ const p = __testing.buildVisionCorrectPrompt({
+ kind: 'object', currentDescription: 'a rusted blade', context: 'family heirloom',
+ });
+ expect(p).toMatch(/Known context.*family heirloom/s);
+ });
+});
+
+describe('correctEntityFromImage', () => {
+ it('returns the current + proposed description and the provider/model that ran', async () => {
+ const out = await correctEntityFromImage({
+ universeId: 'uni-1', entryId: 'chr-1', kind: 'character', screenshot: 'a.png', providerId: 'ollama', model: 'llava',
+ });
+ expect(out).toEqual({
+ descField: 'physicalDescription',
+ currentDescription: 'a tall scavenger in patched leathers',
+ proposedDescription: 'a weathered scavenger',
+ llm: { provider: 'ollama', model: 'llava' },
+ });
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['a.png'], source: 'universe-vision-correct' }),
+ );
+ });
+
+ it('returns { locked: true } without calling the vision model when the entry is locked', async () => {
+ universeBuilder.getUniverse.mockResolvedValue(makeUniverse({ locked: true }));
+ const out = await correctEntityFromImage({
+ universeId: 'uni-1', entryId: 'chr-1', kind: 'character', screenshot: 'a.png',
+ });
+ expect(out).toEqual({ locked: true, entryName: 'Vex' });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unsupported kind', async () => {
+ await expect(correctEntityFromImage({ universeId: 'uni-1', entryId: 'chr-1', kind: 'vehicle', screenshot: 'a.png' }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it('rejects when no image is supplied', async () => {
+ await expect(correctEntityFromImage({ universeId: 'uni-1', entryId: 'chr-1', kind: 'character' }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it('404s when the entry is not found in the universe', async () => {
+ await expect(correctEntityFromImage({ universeId: 'uni-1', entryId: 'missing', kind: 'character', screenshot: 'a.png' }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_CANON_NOT_FOUND', status: 404 });
+ });
+
+ it('throws VISION_EMPTY (502) when the model returns a blank correction', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: ' ', model: 'llava' });
+ await expect(correctEntityFromImage({ universeId: 'uni-1', entryId: 'chr-1', kind: 'character', screenshot: 'a.png' }))
+ .rejects.toMatchObject({ code: 'VISION_EMPTY', status: 502 });
+ });
+});