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

Enrich Universe characters and refine style from reference images

[._.]/ Adam Eivyc0b2d1eeb70a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 664b2acc62..70cfc368fa 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone. (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)
+
- **[issue-1300] Editorial checks flag five prose anti-patterns (weak openings, mirror self-description, empty pleasantries, italic thoughts, darlings).** A bundle of line/scene-level checks (Create → Editorial Checks) for the well-known tells that pull readers out. Four are LLM checks over the drafted manuscript: **Weak opening** flags clichéd or mis-placed openers — "he wakes up" / alarm-clock / dream starts, weather-and-scenery preambles, and scenes that begin before the interesting moment; **Mirror self-description** catches the tired trick of a character studying their reflection so the prose can catalog their looks, while leaving reflections that do real story work alone; **Empty greeting / small-talk openings** flags scenes that open on greeting rituals or logistical filler that carry no tension or information, while sparing pleasantries laced with subtext; **Kill your darlings** surfaces precious, self-indulgent passages — showpiece descriptions, digressions, over-explaining, favorite lines that stop the scene — as cut candidates, judged by story need rather than quality (complementing the dead-metaphor check, which targets stock rather than precious prose). The fifth, **Italicized internal thoughts**, is a deterministic, high-precision scan that flags multi-word `*…*` / `_…_` italic thought runs (the prose is already in the character's perspective, so italicizing a thought is a tell) while leaving single-word emphasis, bold, and `snake_case` alone, with a configurable word threshold. All findings anchor a verbatim quote + issue number; the LLM checks ship four new stage prompts (`pipeline-editorial-{opening-start,mirror-description,dialogue-pleasantries,kill-your-darlings}`) that migrate for existing installs (103–106), the deterministic check needs no model. (`server/lib/editorial/{italicThoughts,checkRegistry}.js`) (#1300)
- **[issue-1309] Editorial checks flag thin sensory writing and ungrounded "white-room" scenes.** Two new prose checks (Create → Editorial Checks) target two of the most common reader gripes about flat scene writing. **Sensory balance** reads your drafted manuscript and flags scenes that lean almost entirely on sight while sound, smell, touch, and taste go neglected, plus sensory-bare scenes with almost no concrete grounding at all — naming exactly which sense is missing and suggesting a grounding detail to add. **White-room / ungrounded scene** flags "talking heads in a void": dialogue and action playing out with no setting, no physical blocking, and no spatial grounding the reader can stand in — distinct from sensory balance (which is about *senses*) and scene-component balance (narrative/action/dialogue mix) in that the gap here is specifically *place*. Both read your reverse-outline scene segmentation as context (using each scene's recorded setting as a white-room signal) and **degrade gracefully** to a whole-issue manuscript scan when no outline has been generated yet. Each finding anchors a verbatim quote + issue number so you can jump straight to the spot. Two new stage prompts (`pipeline-editorial-sensory-balance`, `pipeline-editorial-white-room`) ship + migrate for existing installs. (#1309)
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index e0291636b2..6419972a69 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -850,6 +850,8 @@ export default function UniverseCanonSection({
open
kind={describeTarget.kind.apiKind}
entryName={describeTarget.entry.name}
+ universeId={universeId}
+ entryId={describeTarget.entry.id}
onApply={(description) => {
if (describeTarget.kind.descField) {
handlePatchEntry(describeTarget.kind, describeTarget.entry.id, {
@@ -857,6 +859,11 @@ export default function UniverseCanonSection({
});
}
}}
+ // Structured attributes from a reference image (characters): apply the
+ // reviewed `{ field: value }` patch through the same entry-patch path.
+ onApplyFields={(patch) => {
+ handlePatchEntry(describeTarget.kind, describeTarget.entry.id, patch);
+ }}
onClose={() => setDescribeTarget(null)}
/>
) : null}
diff --git a/client/src/components/universe/VisionDescribeModal.jsx b/client/src/components/universe/VisionDescribeModal.jsx
index 84939ca797..f01e1006ac 100644
--- a/client/src/components/universe/VisionDescribeModal.jsx
+++ b/client/src/components/universe/VisionDescribeModal.jsx
@@ -1,26 +1,32 @@
/**
- * Vision-to-prose modal for a canon entry (character / place / object).
+ * Vision-to-prose / vision-to-attributes modal for a canon entry.
*
- * Upload one or more reference images, pick an (API/vision-capable) provider +
- * model on demand, and have the vision model turn the image(s) into an
- * image-gen-ready prose description. A single image describes that subject;
- * multiple images return the description COMMON to all of them (the same
- * character from several angles, a location across lighting conditions, …).
+ * Add reference images — uploaded from disk OR picked from the image gallery —
+ * pick an (API/vision-capable) provider + model on demand, and either:
+ * - "Describe" (all kinds): turn the image(s) into an image-gen-ready prose
+ * description that seeds the entry's descriptor field. A single image
+ * describes that subject; multiple images return the description COMMON to
+ * all of them (the same subject from several angles, …).
+ * - "Build character details" (characters only): have a vision model PROPOSE
+ * values for the character's still-blank structured fields (palette, visual
+ * notes, expressions, …). The proposals are shown for review (string fields
+ * editable) and applied via the entry-patch path.
*
* The modal is stateless w.r.t. the universe — it returns the generated prose
- * via `onApply(description)` and lets the parent write it into the right entry
- * field.
+ * via `onApply(description)` and the reviewed attribute patch via
+ * `onApplyFields(patch)`, and lets the parent write them into the entry.
*/
import { useState, useCallback, useRef } from 'react';
-import { Loader2, ImagePlus, Sparkles, X } from 'lucide-react';
+import { Loader2, ImagePlus, Images, Sparkles, X } from 'lucide-react';
import Modal from '../ui/Modal';
import toast from '../ui/Toast';
import ProviderModelSelector from '../ProviderModelSelector';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import useProviderModels from '../../hooks/useProviderModels';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { processScreenshotUploads } from '../../utils/fileUpload';
-import { describeEntityFromImages } from '../../services/apiUniverseBuilder';
+import { describeEntityFromImages, expandEntityFromImages } from '../../services/apiUniverseBuilder';
// Vision is an API-provider-only capability (the runner only base64-inlines
// images on the API path) — so the picker only offers enabled API providers.
@@ -32,16 +38,31 @@ const MAX_IMAGES = 8;
const KIND_NOUN = { character: 'character', place: 'place', object: 'object' };
-export default function VisionDescribeModal({ open, kind, entryName, onApply, onClose }) {
- // Each: { filename, preview }. `filename` is the server-stored screenshot
- // name we send to the describe endpoint; `preview` is the data URL for the
- // thumbnail.
+// camelCase field name → human label for the attribute review list.
+const humanizeField = (f) => f
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/^./, (c) => c.toUpperCase());
+
+// Unique key per reference image so a gallery image and an upload sharing a
+// name don't collide in the thumbnail list or the remove handler.
+const imageKey = (img) => `${img.source}:${img.filename}`;
+
+export default function VisionDescribeModal({
+ open, kind, entryName, universeId, entryId, onApply, onApplyFields, onClose,
+}) {
+ // Each: { source: 'upload'|'gallery', filename, preview }. `filename` is what
+ // we send to the server (an uploaded screenshot name or a gallery name);
+ // `preview` is the URL for the thumbnail.
const [images, setImages] = useState([]);
const [uploading, setUploading] = useState(false);
+ const [galleryOpen, setGalleryOpen] = useState(false);
const [result, setResult] = useState('');
- // Optional "known context" the user can type to disambiguate the subject
- // (e.g. a name the images don't make obvious) — passed straight to the
- // vision prompt.
+ // Structured attribute proposals (characters): { fields, updatedFields }.
+ const [proposed, setProposed] = useState(null);
+ // Per-field include set + edited string values for the review list.
+ const [selectedFields, setSelectedFields] = useState(() => new Set());
+ const [fieldEdits, setFieldEdits] = useState({});
+ // Optional "known context" the user can type to disambiguate the subject.
const [context, setContext] = useState('');
const fileInputRef = useRef(null);
@@ -51,6 +72,21 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
} = useProviderModels({ filter: apiProviderFilter, silent: true });
const noun = KIND_NOUN[kind] || 'subject';
+ const isCharacter = kind === 'character';
+
+ const addImages = useCallback((next) => {
+ setImages((prev) => {
+ const seen = new Set(prev.map(imageKey));
+ const merged = [...prev];
+ for (const img of next) {
+ if (merged.length >= MAX_IMAGES) break;
+ if (seen.has(imageKey(img))) continue;
+ seen.add(imageKey(img));
+ merged.push(img);
+ }
+ return merged;
+ });
+ }, []);
const handleFiles = useCallback(async (fileList) => {
// Respect the cap across the already-selected set. Slice BEFORE uploading
@@ -64,41 +100,100 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
if (files.length === 0) return;
if (files.length > room) toast.error(`Only adding ${room} — max ${MAX_IMAGES} images`);
setUploading(true);
- // processScreenshotUploads handles the image-type filter, size check, and
- // sequential upload; onSuccess appends each result (guarded by the cap).
await processScreenshotUploads(files.slice(0, room), {
- onSuccess: (info) => setImages((prev) => (prev.length >= MAX_IMAGES
- ? prev
- : [...prev, { filename: info.filename, preview: info.preview }])),
+ onSuccess: (info) => addImages([{ source: 'upload', filename: info.filename, preview: info.preview }]),
onError: (msg) => toast.error(msg),
});
setUploading(false);
- }, [images.length]);
+ }, [images.length, addImages]);
- const removeImage = useCallback((filename) => {
- setImages((prev) => prev.filter((img) => img.filename !== filename));
+ const handleGalleryPick = useCallback((item) => {
+ if (!item?.filename) return;
+ if (images.length >= MAX_IMAGES) {
+ toast.error(`Up to ${MAX_IMAGES} images at a time`);
+ return;
+ }
+ addImages([{ source: 'gallery', filename: item.filename, preview: item.previewUrl }]);
+ }, [images.length, addImages]);
+
+ const removeImage = useCallback((key) => {
+ setImages((prev) => prev.filter((img) => imageKey(img) !== key));
}, []);
+ // Payload shared by both vision calls.
+ const imagePayload = () => ({
+ images: images.map((img) => ({ source: img.source, filename: img.filename })),
+ providerId: selectedProviderId || undefined,
+ model: selectedModel || undefined,
+ });
+
const [runDescribe, describing] = useAsyncAction(async () => {
const res = await describeEntityFromImages({
kind,
name: entryName || undefined,
context: context.trim() || undefined,
- screenshots: images.map((img) => img.filename),
- providerId: selectedProviderId || undefined,
- model: selectedModel || undefined,
+ ...imagePayload(),
}, { silent: true });
if (res?.description) setResult(res.description);
return res;
}, { errorMessage: 'Failed to describe image(s)' });
- const apply = () => {
+ const [runBuildAttributes, building] = useAsyncAction(async () => {
+ const res = await expandEntityFromImages(universeId, entryId, {
+ name: entryName || undefined,
+ context: context.trim() || undefined,
+ ...imagePayload(),
+ }, { silent: true });
+ if (res?.locked) {
+ toast.error(`${entryName || 'This character'} is locked — unlock it to fill from an image`);
+ return res;
+ }
+ const fields = res?.fields && typeof res.fields === 'object' ? res.fields : {};
+ const updated = Array.isArray(res?.updatedFields) ? res.updatedFields : [];
+ setProposed({ fields, updatedFields: updated });
+ setSelectedFields(new Set(updated));
+ // Seed editable string values; list fields apply their proposed value as-is.
+ const edits = {};
+ for (const f of updated) if (typeof fields[f] === 'string') edits[f] = fields[f];
+ setFieldEdits(edits);
+ if (updated.length === 0) toast(`No new details to fill for ${entryName || `this ${noun}`}`);
+ return res;
+ }, { errorMessage: 'Failed to build details from image(s)' });
+
+ const applyDescription = () => {
onApply(result.trim());
toast.success(`Applied description to ${entryName || `this ${noun}`}`);
onClose();
};
- const canDescribe = images.length > 0 && !describing && !uploading;
+ const toggleField = (f) => {
+ setSelectedFields((prev) => {
+ const next = new Set(prev);
+ if (next.has(f)) next.delete(f); else next.add(f);
+ return next;
+ });
+ };
+
+ const applyAttributes = () => {
+ if (!proposed) return;
+ const patch = {};
+ for (const f of proposed.updatedFields) {
+ if (!selectedFields.has(f)) continue;
+ const value = typeof proposed.fields[f] === 'string'
+ ? (fieldEdits[f] ?? proposed.fields[f])
+ : proposed.fields[f];
+ patch[f] = value;
+ }
+ if (Object.keys(patch).length === 0) {
+ toast.error('Select at least one detail to apply');
+ return;
+ }
+ onApplyFields(patch);
+ toast.success(`Applied ${Object.keys(patch).length} detail${Object.keys(patch).length > 1 ? 's' : ''} to ${entryName || `this ${noun}`}`);
+ onClose();
+ };
+
+ const canRun = images.length > 0 && !describing && !building && !uploading && providers.length > 0;
const multi = images.length > 1;
return (
@@ -107,7 +202,7 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
<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" />
- Describe {entryName ? `"${entryName}"` : `this ${noun}`} from image{multi ? 's' : ''}
+ {entryName ? `"${entryName}"` : `This ${noun}`} from image{multi ? 's' : ''}
</h3>
<button type="button" onClick={onClose} className="text-gray-500 hover:text-white" aria-label="Close">
<X size={16} />
@@ -116,8 +211,10 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
<div className="p-4 space-y-4 overflow-y-auto">
<p className="text-xs text-gray-500">
- Upload one image to describe this {noun}, or several of the same {noun} to get the
- description common to all of them. A vision model turns them into image-gen-ready prose.
+ Add one image, or several of the same {noun}, from your device or your gallery.
+ {isCharacter
+ ? ' Describe them into the descriptor field, or build their structured details (palette, visual notes, expressions, …) from the reference.'
+ : ' A vision model turns them into image-gen-ready prose.'}
</p>
{/* Image picker + thumbnails */}
@@ -132,15 +229,15 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
/>
<div className="flex flex-wrap gap-2">
{images.map((img) => (
- <div key={img.filename} className="relative w-20 h-20">
+ <div key={imageKey(img)} className="relative w-20 h-20">
<img
- src={img.preview || `/api/screenshots/${encodeURIComponent(img.filename)}`}
+ src={img.preview || (img.source === 'upload' ? `/api/screenshots/${encodeURIComponent(img.filename)}` : `/data/images/${encodeURIComponent(img.filename)}`)}
alt="reference"
className="w-full h-full object-cover rounded border border-port-border"
/>
<button
type="button"
- onClick={() => removeImage(img.filename)}
+ onClick={() => removeImage(imageKey(img))}
title="Remove image"
aria-label="Remove image"
className="absolute -top-1.5 -right-1.5 bg-port-bg border border-port-border rounded-full p-0.5 text-gray-400 hover:text-port-error"
@@ -150,15 +247,25 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
</div>
))}
{images.length < MAX_IMAGES ? (
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
- disabled={uploading}
- className="w-20 h-20 flex flex-col items-center justify-center gap-1 rounded border border-dashed border-port-border text-gray-500 hover:text-port-accent hover:border-port-accent/50 disabled:opacity-50"
- >
- {uploading ? <Loader2 size={16} className="animate-spin" /> : <ImagePlus size={16} />}
- <span className="text-[10px]">{images.length ? 'Add' : 'Upload'}</span>
- </button>
+ <>
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={uploading}
+ className="w-20 h-20 flex flex-col items-center justify-center gap-1 rounded border border-dashed border-port-border text-gray-500 hover:text-port-accent hover:border-port-accent/50 disabled:opacity-50"
+ >
+ {uploading ? <Loader2 size={16} className="animate-spin" /> : <ImagePlus size={16} />}
+ <span className="text-[10px]">Upload</span>
+ </button>
+ <button
+ type="button"
+ onClick={() => setGalleryOpen(true)}
+ className="w-20 h-20 flex flex-col items-center justify-center gap-1 rounded border border-dashed border-port-border text-gray-500 hover:text-port-accent hover:border-port-accent/50"
+ >
+ <Images size={16} />
+ <span className="text-[10px]">Gallery</span>
+ </button>
+ </>
) : null}
</div>
</div>
@@ -179,7 +286,7 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
<p className="text-xs text-port-warning">
{providersLoading
? 'Loading providers…'
- : 'No API provider configured. Add one with a vision-capable model under Settings → Providers to describe images.'}
+ : 'No API provider configured. Add one with a vision-capable model under Settings → Providers to analyze images.'}
</p>
)}
@@ -199,17 +306,30 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
/>
</div>
- <button
- type="button"
- onClick={runDescribe}
- disabled={!canDescribe || providers.length === 0}
- 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"
- >
- {describing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- {describing ? 'Describing…' : `Describe from image${multi ? 's' : ''}`}
- </button>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={runDescribe}
+ disabled={!canRun}
+ 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"
+ >
+ {describing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {describing ? 'Describing…' : `Describe from image${multi ? 's' : ''}`}
+ </button>
+ {isCharacter ? (
+ <button
+ type="button"
+ onClick={runBuildAttributes}
+ disabled={!canRun}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded border border-port-accent text-port-accent text-sm disabled:opacity-40 disabled:cursor-not-allowed hover:bg-port-accent/10"
+ >
+ {building ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {building ? 'Analyzing…' : 'Build character details'}
+ </button>
+ ) : null}
+ </div>
- {/* Result — editable before applying */}
+ {/* Prose result — editable before applying */}
{result ? (
<div className="space-y-2">
<label htmlFor="vision-describe-result" className="block text-xs text-gray-500">
@@ -222,24 +342,76 @@ export default function VisionDescribeModal({ open, kind, entryName, onApply, on
rows={6}
className="w-full px-2 py-1.5 text-xs bg-port-bg border border-port-border rounded text-gray-200 whitespace-pre-wrap"
/>
+ <button
+ type="button"
+ onClick={applyDescription}
+ disabled={!result.trim()}
+ className="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"
+ >
+ Apply description
+ </button>
+ </div>
+ ) : null}
+
+ {/* Structured attribute review — characters only */}
+ {proposed && proposed.updatedFields.length > 0 ? (
+ <div className="space-y-2">
+ <p className="text-xs text-gray-500">
+ Proposed details (only blank fields). Uncheck any you don't want; edit text inline. Existing values are never overwritten.
+ </p>
+ <div className="space-y-2 max-h-72 overflow-y-auto pr-1">
+ {proposed.updatedFields.map((f) => {
+ const value = proposed.fields[f];
+ const isList = Array.isArray(value);
+ const checked = selectedFields.has(f);
+ return (
+ <div key={f} className="border border-port-border rounded p-2 bg-port-bg">
+ <label className="flex items-center gap-2 text-xs text-gray-300 mb-1">
+ <input type="checkbox" checked={checked} onChange={() => toggleField(f)} />
+ <span className="font-medium">{humanizeField(f)}</span>
+ {isList ? <span className="text-gray-500">({value.length} item{value.length > 1 ? 's' : ''})</span> : null}
+ </label>
+ {isList ? (
+ <p className="text-[11px] text-gray-400 pl-6">
+ {value.map((row) => row?.name || row?.label).filter(Boolean).join(', ') || '—'}
+ </p>
+ ) : (
+ <textarea
+ value={fieldEdits[f] ?? ''}
+ onChange={(e) => setFieldEdits((prev) => ({ ...prev, [f]: e.target.value }))}
+ disabled={!checked}
+ rows={2}
+ className="w-full px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-200 disabled:opacity-50"
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ <button
+ type="button"
+ onClick={applyAttributes}
+ disabled={selectedFields.size === 0}
+ className="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"
+ >
+ Apply {selectedFields.size} detail{selectedFields.size > 1 ? 's' : ''}
+ </button>
</div>
) : null}
</div>
<div className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">
<button type="button" onClick={onClose} className="px-3 py-1.5 rounded border border-port-border text-gray-300 text-sm hover:text-white">
- Cancel
- </button>
- <button
- type="button"
- onClick={apply}
- disabled={!result.trim()}
- className="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"
- >
- Apply to {noun}
+ Close
</button>
</div>
</div>
+
+ <GalleryImagePicker
+ open={galleryOpen}
+ onClose={() => setGalleryOpen(false)}
+ onSelect={handleGalleryPick}
+ />
</Modal>
);
}
diff --git a/client/src/components/universe/VisionDescribeModal.test.jsx b/client/src/components/universe/VisionDescribeModal.test.jsx
new file mode 100644
index 0000000000..56daaf059d
--- /dev/null
+++ b/client/src/components/universe/VisionDescribeModal.test.jsx
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import VisionDescribeModal from './VisionDescribeModal';
+
+// One enabled API provider so the action buttons are enabled-by-provider.
+vi.mock('../../hooks/useProviderModels', () => ({
+ default: () => ({
+ providers: [{ id: 'ollama', name: 'Ollama', type: 'api', enabled: true }],
+ selectedProviderId: 'ollama',
+ selectedModel: 'qwen-vl',
+ availableModels: ['qwen-vl'],
+ setSelectedProviderId: () => {},
+ setSelectedModel: () => {},
+ loading: false,
+ }),
+}));
+
+// The gallery picker pulls in the media/socket layer — stub it.
+vi.mock('../imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../ProviderModelSelector', () => ({ default: () => null }));
+
+const apiMocks = vi.hoisted(() => ({
+ describeEntityFromImages: vi.fn(),
+ expandEntityFromImages: vi.fn(),
+}));
+vi.mock('../../services/apiUniverseBuilder', () => apiMocks);
+
+describe('VisionDescribeModal', () => {
+ const baseProps = {
+ open: true, entryName: 'Freydis', universeId: 'uni-1', entryId: 'chr-1',
+ onApply: () => {}, onApplyFields: () => {}, onClose: () => {},
+ };
+
+ it('shows the "Build character details" action for characters', () => {
+ render(<VisionDescribeModal {...baseProps} kind="character" />);
+ expect(screen.getByRole('button', { name: /Build character details/i })).toBeInTheDocument();
+ // Both image sources are offered.
+ expect(screen.getByRole('button', { name: /Gallery/i })).toBeInTheDocument();
+ });
+
+ it('hides the structured action for non-character kinds', () => {
+ render(<VisionDescribeModal {...baseProps} kind="place" />);
+ expect(screen.queryByRole('button', { name: /Build character details/i })).not.toBeInTheDocument();
+ // The prose describe action is still present for places.
+ expect(screen.getByRole('button', { name: /Describe from image/i })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 7aba88e584..ee8b23abbf 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -13,7 +13,7 @@ import {
Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
ArrowUpCircle, ArrowLeft,
- BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree,
+ BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree, Images,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
@@ -32,6 +32,7 @@ import useUniverseAction from '../hooks/useUniverseAction';
import { useUniverseNav } from '../hooks/useUniverseNav';
import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';
import ProviderModelSelector from '../components/ProviderModelSelector';
+import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';
import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';
import ShareToButton from '../components/sharing/ShareToButton';
@@ -663,12 +664,16 @@ export default function UniverseBuilder() {
const [refining, setRefining] = useState(false);
const [refineRationale, setRefineRationale] = useState('');
const [refineChanges, setRefineChanges] = useState([]);
+ // Optional gallery image used as a visual style reference for refinement —
+ // { filename, preview }. When set, the server refines through a vision model.
+ const [refineImage, setRefineImage] = useState(null);
const resetRefinePanel = () => {
setRefineOpen(false);
setRefineFeedback('');
setRefineRationale('');
setRefineChanges([]);
+ setRefineImage(null);
};
const refresh = async () => {
@@ -1125,6 +1130,7 @@ export default function UniverseBuilder() {
compositeSheets: hasStructure ? draft.compositeSheets : undefined,
locked: locks,
feedback,
+ image: refineImage?.filename || undefined,
providerId: draft.llm?.provider || activeProviderId || undefined,
model: draft.llm?.model || undefined,
}).catch(() => null);
@@ -1155,6 +1161,7 @@ export default function UniverseBuilder() {
setRefineRationale(result.rationale || '');
setRefineChanges(Array.isArray(result.changes) ? result.changes : []);
setRefineFeedback('');
+ setRefineImage(null);
toast.success('Refined world applied');
};
@@ -1721,6 +1728,7 @@ export default function UniverseBuilder() {
feedback: refineFeedback, setFeedback: setRefineFeedback,
run: runRefine, running: refining, reset: resetRefinePanel,
rationale: refineRationale, changes: refineChanges,
+ image: refineImage, setImage: setRefineImage,
}}
totalVariations={totalVariations}
categoryKeyCount={categoryKeys.length}
@@ -2837,7 +2845,10 @@ function BibleTab({
feedback: refineFeedback, setFeedback: setRefineFeedback,
run: runRefine, running: refining, reset: resetRefinePanel,
rationale: refineRationale, changes: refineChanges,
+ image: refineImage, setImage: setRefineImage,
} = refine;
+ // Local-only: gallery picker visibility for the optional style-reference image.
+ const [refineGalleryOpen, setRefineGalleryOpen] = useState(false);
return (
<>
<section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
@@ -2917,6 +2928,42 @@ function BibleTab({
disabled={refining}
className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y disabled:opacity-60"
/>
+ {/* Optional visual style reference from the gallery — when set, the
+ server refines through a vision-capable API provider. */}
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">Style reference (optional)</span>
+ {refineImage ? (
+ <div className="relative w-14 h-14">
+ <img
+ src={refineImage.preview || `/data/images/${encodeURIComponent(refineImage.filename)}`}
+ alt="style reference"
+ className="w-full h-full object-cover rounded border border-port-border"
+ />
+ <button
+ type="button"
+ onClick={() => setRefineImage(null)}
+ title="Remove reference image"
+ aria-label="Remove reference image"
+ className="absolute -top-1.5 -right-1.5 bg-port-bg border border-port-border rounded-full p-0.5 text-gray-400 hover:text-port-error"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setRefineGalleryOpen(true)}
+ disabled={refining}
+ className="px-2.5 py-1.5 text-xs text-port-accent border border-port-accent/40 rounded flex items-center gap-1.5 hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ <Images size={14} />
+ Pick from gallery
+ </button>
+ )}
+ {refineImage ? (
+ <span className="text-[11px] text-gray-500">Folds the image's palette/mood into influences + style notes.</span>
+ ) : null}
+ </div>
<div className="flex items-center gap-2 flex-wrap">
<button
type="button"
@@ -2953,6 +3000,13 @@ function BibleTab({
)}
</div>
)}
+ <GalleryImagePicker
+ open={refineGalleryOpen}
+ onClose={() => setRefineGalleryOpen(false)}
+ onSelect={(item) => {
+ if (item?.filename) setRefineImage({ filename: item.filename, preview: item.previewUrl });
+ }}
+ />
</div>
)}
</section>
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 134b714665..51ab07c4ff 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -56,18 +56,35 @@ export const expandUniverse = ({
});
// Vision-to-prose: turn reference image(s) into an image-gen-ready prose
-// description for a canon entry. `screenshots` are filenames already uploaded
-// via uploadScreenshot(); multiple images → the model returns the description
-// common to all of them. `providerId`/`model` pick the (API/vision-capable)
-// provider on demand. Resolves to `{ description, llm: { provider, model } }`.
+// description for a canon entry. `images` is `[{ source: 'upload'|'gallery',
+// filename }]` — uploads were POSTed via uploadScreenshot(); gallery items are
+// generated-gallery filenames. Multiple images → the model returns the
+// description common to all of them. `providerId`/`model` pick the
+// (API/vision-capable) provider on demand. Resolves to `{ description, llm }`.
export const describeEntityFromImages = ({
- kind, name, context, screenshots, providerId, model,
+ kind, name, context, images, providerId, model,
} = {}, options = {}) => request('/universe-builder/describe-from-images', {
method: 'POST',
- body: JSON.stringify({ kind, name, context, screenshots, providerId, model }),
+ body: JSON.stringify({ kind, name, context, images, providerId, model }),
...options,
});
+// Vision-driven structured expand (characters only): a vision model reads
+// reference image(s) and PROPOSES values for the character's still-blank
+// structured fields. Review-only — resolves to `{ fields, updatedFields, llm }`
+// (or `{ locked: true }`); the caller applies the kept/edited values via the
+// normal entry patch. `images` shape matches describeEntityFromImages.
+export const expandEntityFromImages = (universeId, entryId, {
+ name, context, images, providerId, model,
+} = {}, options = {}) => request(
+ `/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/expand-from-images`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ name, context, images, providerId, model }),
+ ...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 = ({
@@ -95,6 +112,9 @@ export const refineWorldPrompts = ({
// Omit (or pass empty/falsy) to get the bible-only behavior.
categories, compositeSheets,
locked,
+ // Optional gallery filename used as a visual style reference. When present the
+ // server forces a vision-capable API provider.
+ image,
feedback, providerId, model,
} = {}) => request('/universe-builder/refine-prompts', {
method: 'POST',
@@ -105,6 +125,7 @@ export const refineWorldPrompts = ({
...(categories && Object.keys(categories).length ? { categories } : {}),
...(Array.isArray(compositeSheets) && compositeSheets.length ? { compositeSheets } : {}),
locked,
+ ...(image ? { image } : {}),
feedback, providerId, model,
}),
});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 59fbd1647f..b32ed7f2b6 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -191,6 +191,35 @@ export function assertProvider(provider, { message, code, status = 503 } = {}) {
throw new Error(message);
}
+/**
+ * Guard a vision run against a silent fallback to a non-API provider.
+ *
+ * Vision only works on the API path (executeApiRun base64-inlines images);
+ * CLI/TUI providers drop the images and return a completion hallucinated from
+ * the text prompt alone. `runPromptThroughProvider` can swap the provider two
+ * ways — a proactive swap inside createRun (`result.provider`) or a retry
+ * fallback after failure (`result.fallbackProvider`) — so the provider that
+ * ACTUALLY ran is the first of those, else the requested one. Throw
+ * VISION_FALLBACK_DROPPED_IMAGES when it isn't an API provider so callers don't
+ * report image-grounded output that was really text-only.
+ *
+ * Returns the provider that ran so callers can read its id/type.
+ *
+ * @param {object} result — the runPromptThroughProvider result
+ * @param {object} requestedProvider — the provider the caller asked to run
+ * @returns {object} the effective provider that ran
+ */
+export function assertVisionRunUsedImages(result, requestedProvider) {
+ const ran = result?.provider || result?.fallbackProvider || requestedProvider;
+ if (ran?.type && ran.type !== 'api') {
+ throw new ServerError(
+ 'The vision request fell back to a non-vision provider that cannot read images. Configure a reliable vision-capable API provider and retry.',
+ { status: 502, code: 'VISION_FALLBACK_DROPPED_IMAGES' },
+ );
+ }
+ return ran;
+}
+
/**
* Run a prompt through a provider and resolve with the streamed text +
* run id. Rejects (via the strictest discriminator) on any runner-
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index eacdd0fbfb..8c2c6be2e4 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -8,6 +8,7 @@
* DELETE /api/universe-builder/:id → { id }
* POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, places, objects, llm }
* POST /api/universe-builder/describe-from-images → { description, llm }
+ * POST /api/universe-builder/:id/characters/:entryId/expand-from-images → { fields, updatedFields, llm }
* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }
* GET /api/universe-builder/:id/runs → Run[]
*/
@@ -28,7 +29,8 @@ import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/sto
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 { sanitizeFilename, PATHS } from '../lib/fileUtils.js';
+import { expandEntityFromImages, VISION_EXPAND_MAX_IMAGES } from '../services/universeVisionExpand.js';
+import { sanitizeFilename, PATHS, resolveGalleryImage } from '../lib/fileUtils.js';
import { existsSync } from 'fs';
import { join } from 'path';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
@@ -288,6 +290,11 @@ const refinePromptsSchema = z.object({
// of what the LLM tries to write.
locked: lockedSchema.optional().default({}),
feedback: z.string().trim().min(1).max(3000),
+ // Optional gallery image used as a VISUAL style reference — when present the
+ // refiner forces a vision-capable API provider and folds the image's
+ // palette/lighting/mood into influences + styleNotes. Resolved to an absolute
+ // path in the handler before reaching the service.
+ image: z.string().trim().min(1).max(300).optional(),
providerId: z.string().trim().max(80).optional(),
// Whitespace-only model → undefined so the refiner's defaultModel /
// models[0] fallback kicks in instead of a blank string reaching the
@@ -398,44 +405,66 @@ router.post('/generate-variations', asyncHandler(async (req, res) => {
res.json(result);
}));
+// A reference image the vision routes accept from one of two sources:
+// - 'upload' → a filename the client already POSTed to /api/screenshots
+// (lives under data/screenshots; passed to the runner as a bare
+// filename, which it resolves under that dir).
+// - 'gallery' → a generated-gallery filename under data/images; resolved here
+// to an ABSOLUTE path, which the runner's loadImageAsBase64
+// accepts as-is (it only prefixes data/screenshots for bare
+// names).
+const imageSourceSchema = z.object({
+ source: z.enum(['upload', 'gallery']),
+ filename: z.string().trim().min(1).max(300),
+});
+
+// Resolve a mixed `[{ source, filename }]` list into runner-loadable paths,
+// failing loudly per the source's rules. The runner silently DROPS a missing
+// image and still sends the text prompt, so a stale/never-uploaded reference
+// would let the model describe with fewer references — or hallucinate from the
+// prompt alone if all are missing. Reject up front instead.
+function resolveImageSources(images) {
+ return images.map(({ source, filename }) => {
+ if (source === 'gallery') {
+ const abs = resolveGalleryImage(filename);
+ if (!abs) {
+ throw new ServerError(`Gallery image not found: ${filename} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });
+ }
+ return abs;
+ }
+ // 'upload' — the upload route already sanitizes on write, so a legitimately
+ // uploaded name round-trips unchanged. A hand-crafted name with path
+ // components is rejected outright (a 400, not a silent rewrite to a name
+ // that won't exist), keeping a traversal attempt distinguishable from a
+ // deleted/never-uploaded file.
+ const safe = sanitizeFilename(filename);
+ if (safe !== filename) {
+ throw new ServerError(`Invalid screenshot filename: ${filename}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (!existsSync(join(PATHS.screenshots, safe))) {
+ throw new ServerError(`Screenshot not found: ${safe} — re-upload the image and retry.`, { status: 400, code: 'SCREENSHOT_NOT_FOUND' });
+ }
+ return safe;
+ });
+}
+
// 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
-// field to write the result into. `screenshots` are filenames the client
-// already uploaded via POST /api/screenshots (server-sanitized again here as
-// defense-in-depth before the runner resolves them under data/screenshots).
-// Keep ahead of `/:id` so "describe-from-images" isn't parsed as a universe id.
+// field to write the result into. Images come from upload OR the gallery (see
+// resolveImageSources). Keep ahead of `/:id` so "describe-from-images" isn't
+// parsed as a universe id.
const describeFromImagesSchema = z.object({
kind: z.enum(VISION_KINDS),
name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),
context: z.string().trim().max(2000).optional(),
- screenshots: z.array(z.string().trim().min(1).max(300)).min(1).max(VISION_MAX_IMAGES),
+ images: z.array(imageSourceSchema).min(1).max(VISION_MAX_IMAGES),
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
});
router.post('/describe-from-images', asyncHandler(async (req, res) => {
const body = validateRequest(describeFromImagesSchema, req.body ?? {});
- // The upload route already sanitizes on write, so a legitimately-uploaded
- // filename round-trips unchanged here. A hand-crafted body with path
- // components is rejected outright (a 400, not a silent rewrite to a name
- // that won't exist on disk — which would surface as a confusing generic
- // "Image not found" from the runner), keeping a traversal attempt
- // distinguishable from a deleted/never-uploaded file.
- const screenshots = body.screenshots.map((f) => {
- const safe = sanitizeFilename(f);
- if (safe !== f) {
- throw new ServerError(`Invalid screenshot filename: ${f}`, { status: 400, code: 'VALIDATION_ERROR' });
- }
- // Preflight existence: the runner's loadImageAsBase64 silently DROPS a
- // missing image and still sends the text prompt, so a stale/never-uploaded
- // filename would otherwise let the model describe with fewer references —
- // or, if all are missing, hallucinate from the prompt alone. Fail loudly
- // here instead. data/screenshots is where POST /api/screenshots writes.
- if (!existsSync(join(PATHS.screenshots, safe))) {
- throw new ServerError(`Screenshot not found: ${safe} — re-upload the image and retry.`, { status: 400, code: 'SCREENSHOT_NOT_FOUND' });
- }
- return safe;
- });
+ const screenshots = resolveImageSources(body.images);
const result = await describeEntityFromImages({ ...body, screenshots });
res.json(result);
}));
@@ -445,7 +474,17 @@ router.post('/describe-from-images', asyncHandler(async (req, res) => {
// result back to a saved universe. Keep ahead of `/:id`.
router.post('/refine-prompts', asyncHandler(async (req, res) => {
const body = validateRequest(refinePromptsSchema, req.body ?? {});
- res.json(await refineWorldPrompts(body));
+ // Resolve the optional style-reference image to an absolute gallery path
+ // before the service runs — fail loudly on a stale/bogus filename rather than
+ // letting the runner silently drop it and refine text-only.
+ let imagePath = null;
+ if (body.image) {
+ imagePath = resolveGalleryImage(body.image);
+ if (!imagePath) {
+ throw new ServerError(`Gallery image not found: ${body.image} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });
+ }
+ }
+ res.json(await refineWorldPrompts({ ...body, imagePath }));
}));
// Static-path GETs must register BEFORE `/:id` so they aren't swallowed by
@@ -641,6 +680,34 @@ router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) =>
res.json(result);
}));
+// Vision-driven expand — a vision model reads reference image(s) (upload or
+// gallery) and PROPOSES values for the character's still-blank structured
+// fields (palette/visual notes/expressions/...). Review-only: returns the
+// proposed `{ field: value }` map; the client applies the kept/edited values
+// via the normal entry-PATCH path. No-clobber, characters-only, locked
+// characters return `{ locked: true }` with no LLM call.
+const expandFromImagesSchema = z.object({
+ name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),
+ context: z.string().trim().max(2000).optional(),
+ images: z.array(imageSourceSchema).min(1).max(VISION_EXPAND_MAX_IMAGES),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+router.post('/:id/characters/:entryId/expand-from-images', asyncHandler(async (req, res) => {
+ const body = validateRequest(expandFromImagesSchema, req.body ?? {});
+ const screenshots = resolveImageSources(body.images);
+ const result = await expandEntityFromImages({
+ universeId: req.params.id,
+ entryId: req.params.entryId,
+ name: body.name,
+ context: body.context,
+ screenshots,
+ providerId: body.providerId,
+ model: body.model,
+ }).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 ce3ec45728..216c3b6b25 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -7,12 +7,49 @@ import { mockNoPeers, mockNoPeerSync } from '../lib/mockPathsDataRoot.js';
const fileStore = new Map();
+// Gallery resolver: any filename containing "missing" resolves to null (the
+// not-found path); everything else resolves to a deterministic absolute path.
+const resolveGalleryImageMock = vi.fn((filename) => (
+ typeof filename === 'string' && !filename.includes('missing') ? `/mock/data/images/${filename}` : null
+));
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
- PATHS: { data: '/mock/data' },
+ PATHS: { data: '/mock/data', screenshots: '/mock/data/screenshots', images: '/mock/data/images' },
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)),
+ // sanitizeFilename: strip path components so a traversal attempt diverges
+ // from the input (the route 400s when safe !== input).
+ sanitizeFilename: vi.fn((f) => String(f).replace(/^.*[\\/]/, '').replace(/\.\./g, '')),
+ resolveGalleryImage: (...args) => resolveGalleryImageMock(...args),
+}));
+
+// existsSync gates uploaded-screenshot preflight: any name containing "absent"
+// is treated as missing; everything else exists.
+vi.mock('fs', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, existsSync: vi.fn((p) => !String(p).includes('absent')) };
+});
+
+// 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 } }));
+vi.mock('../services/universeVisionDescribe.js', async () => {
+ const actual = await vi.importActual('../services/universeVisionDescribe.js');
+ return { ...actual, describeEntityFromImages: (...args) => describeEntityFromImagesMock(...args) };
+});
+const expandEntityFromImagesMock = vi.fn(async () => ({ fields: { pronouns: 'she/her' }, updatedFields: ['pronouns'], llm: { provider: 'mock', model: null } }));
+vi.mock('../services/universeVisionExpand.js', async () => {
+ const actual = await vi.importActual('../services/universeVisionExpand.js');
+ return { ...actual, expandEntityFromImages: (...args) => expandEntityFromImagesMock(...args) };
+});
+const refineWorldPromptsMock = vi.fn(async (args) => ({
+ starterPrompt: 'refined', logline: '', premise: '', styleNotes: '',
+ influences: { embrace: [], avoid: [] }, locked: {}, rationale: 'r', changes: [],
+ providerId: 'mock', model: null, _imagePath: args?.imagePath ?? null,
+}));
+vi.mock('../services/universeBuilderRefine.js', () => ({
+ refineWorldPrompts: (...args) => refineWorldPromptsMock(...args),
}));
// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createUniverse dynamic-import hoist error alone.
@@ -1026,4 +1063,106 @@ describe('universe-builder routes', () => {
expect(mergeFieldsWithAIMock).not.toHaveBeenCalled();
});
});
+
+ describe('POST /describe-from-images (mixed image sources)', () => {
+ it('resolves an uploaded image to its bare filename', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/describe-from-images')
+ .send({ kind: 'character', images: [{ source: 'upload', filename: 'a.png' }] });
+ expect(res.status).toBe(200);
+ expect(describeEntityFromImagesMock).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['a.png'] }),
+ );
+ });
+
+ it('resolves a gallery image to its absolute path', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/describe-from-images')
+ .send({ kind: 'place', images: [{ source: 'gallery', filename: 'g.png' }] });
+ expect(res.status).toBe(200);
+ expect(describeEntityFromImagesMock).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['/mock/data/images/g.png'] }),
+ );
+ });
+
+ it('400 GALLERY_IMAGE_NOT_FOUND when the gallery image is missing', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/describe-from-images')
+ .send({ kind: 'object', images: [{ source: 'gallery', filename: 'missing.png' }] });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('GALLERY_IMAGE_NOT_FOUND');
+ });
+
+ it('400 SCREENSHOT_NOT_FOUND when the uploaded image is absent on disk', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/describe-from-images')
+ .send({ kind: 'character', images: [{ source: 'upload', filename: 'absent.png' }] });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('SCREENSHOT_NOT_FOUND');
+ });
+
+ it('400 VALIDATION_ERROR on a path-traversal upload filename', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/describe-from-images')
+ .send({ kind: 'character', images: [{ source: 'upload', filename: '../secrets.png' }] });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+ });
+
+ describe('POST /:id/characters/:entryId/expand-from-images', () => {
+ it('resolves mixed sources and forwards universeId/entryId', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/characters/chr-1/expand-from-images')
+ .send({ images: [{ source: 'gallery', filename: 'g.png' }, { source: 'upload', filename: 'a.png' }] });
+ expect(res.status).toBe(200);
+ expect(res.body.updatedFields).toEqual(['pronouns']);
+ expect(expandEntityFromImagesMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ universeId: 'uni-1', entryId: 'chr-1',
+ screenshots: ['/mock/data/images/g.png', 'a.png'],
+ }),
+ );
+ });
+
+ it('400 GALLERY_IMAGE_NOT_FOUND for a missing gallery image', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/uni-1/characters/chr-1/expand-from-images')
+ .send({ images: [{ source: 'gallery', filename: 'missing.png' }] });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('GALLERY_IMAGE_NOT_FOUND');
+ });
+ });
+
+ 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())
+ .post('/api/universe-builder/refine-prompts')
+ .send({ starterPrompt: 'seed', feedback: 'pull toward this', image: 'g.png' });
+ expect(res.status).toBe(200);
+ expect(refineWorldPromptsMock).toHaveBeenCalledWith(
+ expect.objectContaining({ imagePath: '/mock/data/images/g.png' }),
+ );
+ });
+
+ it('400 GALLERY_IMAGE_NOT_FOUND for a missing reference image', async () => {
+ refineWorldPromptsMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/refine-prompts')
+ .send({ starterPrompt: 'seed', feedback: 'x', image: 'missing.png' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('GALLERY_IMAGE_NOT_FOUND');
+ expect(refineWorldPromptsMock).not.toHaveBeenCalled();
+ });
+
+ it('passes imagePath null when no image is supplied', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/refine-prompts')
+ .send({ starterPrompt: 'seed', feedback: 'x' });
+ expect(res.status).toBe(200);
+ expect(refineWorldPromptsMock).toHaveBeenCalledWith(
+ expect.objectContaining({ imagePath: null }),
+ );
+ });
+ });
});
diff --git a/server/services/universeBuilderRefine.image.test.js b/server/services/universeBuilderRefine.image.test.js
new file mode 100644
index 0000000000..9124a19185
--- /dev/null
+++ b/server/services/universeBuilderRefine.image.test.js
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Style-reference-image refine path: forces a vision API provider, passes the
+// resolved image path as a screenshot, and rejects a non-API fallback.
+vi.mock('../lib/aiProvider.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, resolveAPIProvider: vi.fn() };
+});
+vi.mock('../lib/promptRunner.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ resolveProviderAndModel: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+ };
+});
+
+const aiProvider = await import('../lib/aiProvider.js');
+const promptRunner = await import('../lib/promptRunner.js');
+const { refineWorldPrompts } = await import('./universeBuilderRefine.js');
+
+const apiProvider = { id: 'ollama', type: 'api', enabled: true, defaultModel: 'qwen-vl' };
+const cliProvider = { id: 'claude-code', type: 'cli', enabled: true, defaultModel: 'sonnet' };
+
+const REFINE_JSON = JSON.stringify({
+ starterPrompt: 'a rust-toned scavenger world',
+ logline: 'l', premise: 'p', styleNotes: 'rust palette, low sun',
+ influences: { embrace: ['rust palette'], avoid: ['neon'] },
+ rationale: 'pulled toward the reference', changes: ['palette → rust'],
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: cliProvider, selectedModel: 'sonnet' });
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: REFINE_JSON, runId: 'r1', model: 'qwen-vl', provider: apiProvider,
+ });
+});
+
+describe('refineWorldPrompts — style-reference image', () => {
+ it('forces a vision API provider and passes the image path as a screenshot', async () => {
+ const out = await refineWorldPrompts({
+ starterPrompt: 'seed', feedback: 'pull toward this', imagePath: '/abs/data/images/ref.png',
+ });
+ expect(aiProvider.resolveAPIProvider).toHaveBeenCalled();
+ // The text-only resolver must NOT be used when an image is supplied.
+ expect(promptRunner.resolveProviderAndModel).not.toHaveBeenCalled();
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['/abs/data/images/ref.png'] }),
+ );
+ expect(out.starterPrompt).toBe('a rust-toned scavenger world');
+ // hasImage guidance reached the prompt.
+ const { prompt } = promptRunner.runPromptThroughProvider.mock.calls[0][0];
+ expect(prompt).toMatch(/REFERENCE IMAGE/);
+ });
+
+ it('throws NO_API_PROVIDER (503) when no vision provider is configured', async () => {
+ aiProvider.resolveAPIProvider.mockResolvedValue(null);
+ await expect(refineWorldPrompts({ starterPrompt: 'seed', feedback: 'x', imagePath: '/abs/ref.png' }))
+ .rejects.toMatchObject({ code: 'NO_API_PROVIDER', status: 503 });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('rejects (VISION_FALLBACK_DROPPED_IMAGES) when the run fell back to a non-API provider', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: REFINE_JSON, runId: 'r1', model: 'sonnet',
+ usedFallback: true, fallbackProvider: cliProvider,
+ });
+ await expect(refineWorldPrompts({ starterPrompt: 'seed', feedback: 'x', imagePath: '/abs/ref.png' }))
+ .rejects.toMatchObject({ code: 'VISION_FALLBACK_DROPPED_IMAGES', status: 502 });
+ });
+
+ it('uses the text-only provider resolution and sends no screenshots without an image', async () => {
+ // Text-only path returns an API provider here just so JSON parsing succeeds.
+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: apiProvider, selectedModel: 'qwen-vl' });
+ const out = await refineWorldPrompts({ starterPrompt: 'seed', feedback: 'x' });
+ expect(aiProvider.resolveAPIProvider).not.toHaveBeenCalled();
+ expect(promptRunner.resolveProviderAndModel).toHaveBeenCalled();
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: [] }),
+ );
+ const { prompt } = promptRunner.runPromptThroughProvider.mock.calls[0][0];
+ expect(prompt).not.toMatch(/REFERENCE IMAGE/);
+ expect(out.starterPrompt).toBe('a rust-toned scavenger world');
+ });
+});
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index b780fa9391..d69fa94de6 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -12,7 +12,8 @@
*/
import { ServerError } from "../lib/errorHandler.js";
-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from "../lib/promptRunner.js";
+import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "../lib/promptRunner.js";
+import { resolveAPIProvider } from "../lib/aiProvider.js";
import {
renderCategoriesForPrompt as renderCategoriesShared,
renderCompositesForPrompt as renderCompositesShared,
@@ -167,6 +168,7 @@ export function buildWorldRefinePrompt({
compositeSheets = null,
locked = {},
feedback,
+ hasImage = false,
}) {
const lockedRules = lockedList(locked);
const lockedSection = lockedRules.length
@@ -210,6 +212,12 @@ ${renderCategoriesForPrompt(categories) || " (none)"}
ORIGINAL COMPOSITE SHEETS (current draft):
${renderCompositesForPrompt(compositeSheets) || " (none)"}
+`
+ : "";
+
+ const imageGuidance = hasImage
+ ? `
+REFERENCE IMAGE: A reference image is attached. Treat it as a VISUAL STYLE reference for this universe — read its palette, lighting, linework/brushwork, texture, era, and overall mood. Fold those qualities into "influences.embrace" (as short prompt tokens) and into "styleNotes" (as prose), and add "influences.avoid" tokens for qualities the image deliberately lacks. The image informs STYLE ONLY — do NOT invent narrative, characters, or plot from it, and do not contradict the user's written feedback below where they conflict.
`
: "";
@@ -264,7 +272,7 @@ ${styleNotes || "(empty)"}
ORIGINAL INFLUENCES:
Embrace: ${embrace.length ? embrace.join(", ") : "(none)"}
Avoid: ${avoid.length ? avoid.join(", ") : "(none)"}
-${structureContext}
+${structureContext}${imageGuidance}
USER FEEDBACK:
${feedback}`;
}
@@ -331,9 +339,13 @@ const mergeCompositesWithLocks = (originalSheets, llmSheets) => {
// per-CLI argv quirks (codex `exec -`, gemini stdin pipe, claude `-p -`) live
// inside runner.js#buildCliArgs and the TUI paste/idle handshake lives in
// tuiPromptRunner.js — both reached via runPromptThroughProvider.
-async function runRefine(provider, model, prompt) {
+async function runRefine(provider, model, prompt, screenshots = []) {
return runPromptThroughProvider({
provider, prompt, source: "universe-builder-refine", model,
+ // Vision style-reference path: API providers base64-inline these as
+ // image_url blocks; CLI/TUI providers ignore them (the caller forces an API
+ // provider when an image is supplied).
+ screenshots: Array.isArray(screenshots) ? screenshots : [],
}).catch((err) => {
throw new ServerError(err?.message || "Universe refinement failed", {
status: 502,
@@ -378,6 +390,10 @@ export async function refineWorldPrompts({
feedback,
providerId,
model,
+ // Absolute path to a gallery image used as a visual style reference (resolved
+ // by the route). When set, refinement runs through a vision-capable API
+ // provider so the model can read the image.
+ imagePath = null,
} = {}) {
if (!feedback || !feedback.trim()) {
throw new ServerError("Feedback is required", {
@@ -408,7 +424,25 @@ export async function refineWorldPrompts({
);
}
- const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ const hasImage = typeof imagePath === "string" && imagePath.length > 0;
+ // With a style-reference image, vision is API-only (only executeApiRun
+ // base64-inlines images) — force an API provider so the model actually sees
+ // it rather than refining text-only. Without an image, keep the original
+ // resolution so CLI/TUI providers still work for text-only refines.
+ let provider;
+ let selectedModel;
+ if (hasImage) {
+ provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message:
+ "Refining with a reference 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,
+ });
+ selectedModel = resolveEffectiveModel(provider, model);
+ } else {
+ ({ provider, selectedModel } = await resolveProviderAndModel({ providerId, model }));
+ }
assertProvider(provider, {
message: "No AI provider available for universe refinement",
code: "NO_PROVIDER",
@@ -444,9 +478,16 @@ export async function refineWorldPrompts({
...originals,
locked: safeLocked,
feedback: trimTo(feedback, MAX_FEEDBACK),
+ hasImage,
});
- const { text, runId } = await runRefine(provider, selectedModel, llmPrompt);
+ const runResult = await runRefine(provider, selectedModel, llmPrompt, hasImage ? [imagePath] : []);
+ const { text, runId } = runResult;
+
+ // A CLI/TUI fallback silently drops the image and would refine from the text
+ // prompt alone — reject it so the user isn't told the image was used when it
+ // wasn't.
+ if (hasImage) assertVisionRunUsedImages(runResult, provider);
let parsed;
try {
diff --git a/server/services/universeBuilderRefine.test.js b/server/services/universeBuilderRefine.test.js
index 9aa89ea1ba..1d84858688 100644
--- a/server/services/universeBuilderRefine.test.js
+++ b/server/services/universeBuilderRefine.test.js
@@ -185,6 +185,18 @@ describe("universeBuilderRefine.buildWorldRefinePrompt", () => {
expect(out).toMatch(/Embrace: \(none\)/);
expect(out).toMatch(/Avoid: \(none\)/);
});
+
+ it("omits the reference-image guidance by default", () => {
+ const out = buildWorldRefinePrompt({ starterPrompt: "seed", feedback: "x" });
+ expect(out).not.toMatch(/REFERENCE IMAGE/);
+ });
+
+ it("injects reference-image guidance when hasImage is set", () => {
+ const out = buildWorldRefinePrompt({ starterPrompt: "seed", feedback: "x", hasImage: true });
+ expect(out).toMatch(/REFERENCE IMAGE/);
+ expect(out).toMatch(/VISUAL STYLE reference/);
+ expect(out).toMatch(/STYLE ONLY/);
+ });
});
describe("universeBuilderRefine.collapseStyleDirectionDupes", () => {
diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.js
index 1587c21038..b34b415d65 100644
--- a/server/services/universeCharacterExpand.js
+++ b/server/services/universeCharacterExpand.js
@@ -19,13 +19,15 @@ import { sanitizeCharacter } from '../lib/storyBible.js';
import { shortId } from '../lib/fileUtils.js';
// Adding a new extended field on `sanitizeCharacter` requires adding it here
-// too — otherwise the expand response key is silently dropped.
-const STRING_FIELDS = Object.freeze([
+// too — otherwise the expand response key is silently dropped. Exported so the
+// vision-driven expand (`universeVisionExpand.js`) fills the SAME canonical set
+// of fields from one source of truth rather than a drifting second copy.
+export const STRING_FIELDS = Object.freeze([
'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes',
'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',
'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',
]);
-const LIST_FIELDS = Object.freeze([
+export const LIST_FIELDS = Object.freeze([
'stats', 'colorPalette', 'props', 'expressions', 'handGestures',
]);
// `relationshipLinks` (#1287) is INTENTIONALLY excluded from both lists: each
@@ -46,8 +48,10 @@ const peerForExpandPrompt = (entry) => ({
});
const isAbsent = (v) => v === undefined || v === null;
-const isBlankString = (v) => typeof v !== 'string' || v.trim() === '';
-const isBlankArray = (v) => !Array.isArray(v) || v.length === 0;
+// Exported so the vision-expand path can compute the same "which fields are
+// still blank" set it narrows the LLM ask to.
+export const isBlankString = (v) => typeof v !== 'string' || v.trim() === '';
+export const isBlankArray = (v) => !Array.isArray(v) || v.length === 0;
/**
* Pure no-clobber merge of an LLM payload onto a character. Exported so the
diff --git a/server/services/universeCharacterExpand.test.js b/server/services/universeCharacterExpand.test.js
index 55022099f9..c5bc86b5b3 100644
--- a/server/services/universeCharacterExpand.test.js
+++ b/server/services/universeCharacterExpand.test.js
@@ -1,5 +1,16 @@
import { describe, it, expect } from 'vitest';
-import { applyExpansion } from './universeCharacterExpand.js';
+import { applyExpansion, STRING_FIELDS, LIST_FIELDS } from './universeCharacterExpand.js';
+
+describe('universeCharacterExpand — exported field lists', () => {
+ // These are the single source of truth for both the text expand and the
+ // vision-driven expand (universeVisionExpand.js). A drift here means one of
+ // the two flows silently stops filling a field.
+ it('exports the 16 string fields + 5 list fields', () => {
+ expect(STRING_FIELDS).toHaveLength(16);
+ expect(LIST_FIELDS).toHaveLength(5);
+ expect(LIST_FIELDS).toEqual(['stats', 'colorPalette', 'props', 'expressions', 'handGestures']);
+ });
+});
describe('universeCharacterExpand — applyExpansion (no-clobber merge semantics)', () => {
it('fills blank string fields from the LLM response', () => {
diff --git a/server/services/universeVisionDescribe.js b/server/services/universeVisionDescribe.js
index 800be471fe..cdcd67f9cc 100644
--- a/server/services/universeVisionDescribe.js
+++ b/server/services/universeVisionDescribe.js
@@ -19,7 +19,7 @@
*/
import { resolveAPIProvider, stripCodeFences } from '../lib/aiProvider.js';
-import { runPromptThroughProvider, assertProvider } from '../lib/promptRunner.js';
+import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';
import { ServerError } from '../lib/errorHandler.js';
// Singular kind → render-prompt focus. Mirrors the descriptor emphasis the
@@ -131,13 +131,7 @@ export async function describeEntityFromImages({ kind, name, context, screenshot
// 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 = result.provider || result.fallbackProvider || provider;
- if (ranProvider.type && ranProvider.type !== 'api') {
- throw new ServerError(
- 'The vision request fell back to a non-vision provider that cannot read images. Configure a reliable vision-capable API provider and retry.',
- { status: 502, code: 'VISION_FALLBACK_DROPPED_IMAGES' },
- );
- }
+ const ranProvider = assertVisionRunUsedImages(result, provider);
const description = stripCodeFences(result.text || '').trim();
if (!description) {
diff --git a/server/services/universeVisionExpand.js b/server/services/universeVisionExpand.js
new file mode 100644
index 0000000000..8262bcaad7
--- /dev/null
+++ b/server/services/universeVisionExpand.js
@@ -0,0 +1,205 @@
+/**
+ * Universe Character — vision-driven structured expansion.
+ *
+ * The text-based sibling `universeCharacterExpand.js` fleshes out a character's
+ * blank fields from its EXISTING data. This one does the same job from one or
+ * more REFERENCE IMAGES: a vision-capable model looks at the image(s) and
+ * returns a JSON object of the character's structured attributes (palette,
+ * physical/visual notes, expressions, …), which we merge no-clobber onto the
+ * canon entry.
+ *
+ * Review-then-apply, WITHOUT a second LLM round-trip: this service only
+ * PROPOSES. It runs the vision model once, computes the no-clobber merge
+ * against the character's still-blank fields, and returns the proposed field
+ * values for review. The client shows them (editable) and, on Apply, writes the
+ * kept values through the normal entry-PATCH path — so user edits are honored,
+ * the write is serialized by the existing universe write queue, and we never
+ * pay for a second non-deterministic LLM call.
+ *
+ * Vision is an API-provider-only capability (only the toolkit's executeApiRun
+ * base64-inlines images). We resolve an API provider up front and reject a
+ * fallback to a non-vision provider so the model is guaranteed to actually see
+ * the references rather than hallucinating attributes from the text prompt.
+ *
+ * Merge semantics mirror the text expand exactly (`applyExpansion`):
+ * - key absent → preserve existing
+ * - key present but empty → no-op
+ * - key present, non-empty → fill ONLY when the target field is blank
+ */
+
+import { getUniverse } from './universeBuilder.js';
+import {
+ applyExpansion,
+ STRING_FIELDS,
+ LIST_FIELDS,
+ isBlankString,
+ isBlankArray,
+} from './universeCharacterExpand.js';
+import { resolveAPIProvider, parseLLMJSON } from '../lib/aiProvider.js';
+import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { shortId } from '../lib/fileUtils.js';
+
+// Cap mirrors VISION_MAX_IMAGES in universeVisionDescribe.js — the runner
+// base64-inlines every image into a single request body, so a large batch
+// balloons the prompt and the provider's context window.
+export const VISION_EXPAND_MAX_IMAGES = 8;
+
+// Per-list-field row-shape guidance so the model returns rows that survive
+// `sanitizeCharacter` (which drops rows missing the required key). Keep in sync
+// with the sanitizer's row shapes in storyBible.js.
+const LIST_FIELD_SHAPES = {
+ stats: '{ "label": "<attribute name>", "value": "<value>" }',
+ colorPalette: '{ "name": "<swatch name>", "hex": "#rrggbb", "role": "<where it appears>" }',
+ props: '{ "name": "<prop name>", "purpose": "<why they carry it>", "materials": "<materials>", "notes": "<notes>" }',
+ expressions: '{ "name": "<expression>", "description": "<how it reads on their face>" }',
+ handGestures: '{ "name": "<gesture>", "description": "<the hand pose>" }',
+};
+
+/**
+ * Build the vision prompt. The model is told to return ONE JSON object keyed by
+ * the structured character fields, populating only those it can infer from the
+ * image(s) and focusing on the still-blank ones. No prose, no markdown.
+ */
+export function buildVisionExpandPrompt({ name, context, imageCount = 1, blankFields = [] }) {
+ const subject = name ? `the character "${name}"` : 'this character';
+ const intro = imageCount > 1
+ ? `You are looking at ${imageCount} reference images of the same character${name ? ` (${subject})` : ''}. They show the same subject under different conditions (angle, lighting, framing, background). Read the visual traits that stay CONSISTENT across all of them and describe that single shared subject — ignore differences incidental to any one shot.`
+ : `You are looking at a reference image of ${subject}.`;
+
+ const ctx = context && context.trim()
+ ? `\n\nKnown context (use it to disambiguate, do not contradict the images): ${context.trim()}`
+ : '';
+
+ // Narrow the ask to the fields that are still blank when we have that list;
+ // otherwise offer the full set. Populated fields are no-clobber server-side
+ // regardless, so this is purely to focus the model.
+ const stringTargets = blankFields.length
+ ? STRING_FIELDS.filter((f) => blankFields.includes(f))
+ : STRING_FIELDS;
+ const listTargets = blankFields.length
+ ? LIST_FIELDS.filter((f) => blankFields.includes(f))
+ : LIST_FIELDS;
+
+ const stringLines = stringTargets.map((f) => ` "${f}": "<string>"`).join(',\n');
+ const listLines = listTargets
+ .map((f) => ` "${f}": [ ${LIST_FIELD_SHAPES[f]} ]`)
+ .join(',\n');
+ const schemaBody = [stringLines, listLines].filter(Boolean).join(',\n');
+
+ return `${intro}
+
+You are a graphic-novelist's character-reference analyst. Extract the character's renderable visual + design attributes from the image(s) so they can seed a story bible.
+
+Return ONLY a single valid JSON object in this shape (replace every <…> with real content; do NOT output the literal angle-bracket text). OMIT any key you cannot confidently infer from the image(s) — an omitted key means "no opinion" and is preferred over a guess:
+{
+${schemaBody}
+}
+
+Rules:
+- Base every value on what is VISIBLE in the image(s). Do not invent backstory, plot, or facts the image cannot show.
+- String fields: concise, concrete, renderable phrasing (comma-separated descriptive phrases work well). No markdown, no headings, no commentary about the images themselves.
+- List fields: return an array of objects in the exact shape shown. Omit the whole field rather than emitting rows you cannot fill.
+- Output only the JSON object — no preamble, no code fences, no trailing prose.${ctx}`;
+}
+
+/**
+ * Expand a universe character's structured attributes from reference image(s).
+ *
+ * @param {object} args
+ * @param {string} args.universeId
+ * @param {string} args.entryId — character id
+ * @param {string} [args.name] — entity name, for prompt context
+ * @param {string} [args.context] — extra known context to disambiguate
+ * @param {string[]} args.screenshots — image paths the runner can load (bare
+ * filenames under data/screenshots, or absolute paths for gallery images)
+ * @param {string} [args.providerId] — preferred API provider id
+ * @param {string} [args.model] — preferred model id
+ * @returns {Promise<object>} `{ fields, updatedFields, llm }` where `fields` is
+ * a `{ name: value }` map of the blank attributes the model proposes filling
+ * (already merged + sanitized), or `{ locked: true, updatedFields: [] }` when
+ * the character is locked.
+ */
+export async function expandEntityFromImages({
+ universeId, entryId, name, context, screenshots, providerId, model,
+} = {}) {
+ const images = Array.isArray(screenshots) ? screenshots.filter((s) => typeof s === 'string' && s.trim()) : [];
+ if (images.length === 0) {
+ throw new ServerError('At least one image is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (images.length > VISION_EXPAND_MAX_IMAGES) {
+ throw new ServerError(`Too many images — analyze at most ${VISION_EXPAND_MAX_IMAGES} at once`, {
+ status: 400, code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const universe = await getUniverse(universeId);
+ const list = Array.isArray(universe.characters) ? universe.characters : [];
+ const idx = list.findIndex((e) => e.id === entryId);
+ if (idx < 0) {
+ throw new ServerError(`Character ${entryId} not found in universe`, {
+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',
+ });
+ }
+ const target = list[idx];
+ if (target.locked === true) {
+ return { universe, entry: target, locked: true, updatedFields: [] };
+ }
+
+ const blankFields = [
+ ...STRING_FIELDS.filter((f) => isBlankString(target[f])),
+ ...LIST_FIELDS.filter((f) => isBlankArray(target[f])),
+ ];
+
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message:
+ 'Analyzing 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,
+ });
+
+ const prompt = buildVisionExpandPrompt({
+ name, context, imageCount: images.length, blankFields,
+ });
+
+ const result = await runPromptThroughProvider({
+ provider,
+ prompt,
+ source: 'universe-vision-expand',
+ model: model || undefined,
+ screenshots: images,
+ });
+
+ // A CLI/TUI fallback silently drops the images and would return attributes
+ // hallucinated from the text prompt alone — reject it outright.
+ const ranProvider = assertVisionRunUsedImages(result, provider);
+
+ let content;
+ try {
+ content = parseLLMJSON(result.text || '');
+ } catch (e) {
+ throw new ServerError(e.message, { status: 502, code: 'UNIVERSE_VISION_EXPAND_BAD_JSON' });
+ }
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
+ throw new ServerError('The vision model returned a non-object response — try a different model or clearer images.', {
+ status: 502, code: 'UNIVERSE_VISION_EXPAND_BAD_JSON',
+ });
+ }
+
+ const llm = { provider: ranProvider.id || provider.id, model: result.model || null };
+
+ // Compute the no-clobber merge against the loaded target — `applyExpansion`
+ // fills only blank fields and sanitizes list rows. Surface just the fields it
+ // would fill (name → merged value) so the modal can present them for review;
+ // the client applies the kept/edited values via the normal entry-PATCH path.
+ const { merged, updatedFields } = applyExpansion(target, content);
+ const fields = {};
+ for (const f of updatedFields) fields[f] = merged[f];
+ if (updatedFields.length > 0) {
+ console.log(`✨ Universe vision expand proposed — universe=${shortId(universeId)} entry=${shortId(entryId)} fields=${updatedFields.length}`);
+ }
+ return { fields, updatedFields, llm };
+}
+
+export const __testing = { buildVisionExpandPrompt };
diff --git a/server/services/universeVisionExpand.test.js b/server/services/universeVisionExpand.test.js
new file mode 100644
index 0000000000..f6554d7678
--- /dev/null
+++ b/server/services/universeVisionExpand.test.js
@@ -0,0 +1,161 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// resolveAPIProvider drives provider selection; parseLLMJSON stays real so the
+// JSON-parse + fence-strip path is exercised end to end.
+vi.mock('../lib/aiProvider.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, resolveAPIProvider: vi.fn() };
+});
+
+// runPromptThroughProvider is the LLM boundary — mock it. assertProvider stays
+// real (the typed-throw helper we want exercised).
+vi.mock('../lib/promptRunner.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, runPromptThroughProvider: vi.fn() };
+});
+
+// getUniverse is the only universeBuilder surface the service 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 universeBuilder = await import('./universeBuilder.js');
+const {
+ expandEntityFromImages, buildVisionExpandPrompt, VISION_EXPAND_MAX_IMAGES, __testing,
+} = await import('./universeVisionExpand.js');
+
+const apiProvider = { id: 'ollama', type: 'api', defaultModel: 'qwen-vl' };
+
+// A minimal character with one populated field (role) and the rest blank.
+const makeUniverse = (overrides = {}) => ({
+ id: 'uni-1',
+ characters: [{ id: 'chr-1', name: 'Freydis', role: 'protagonist', ...overrides }],
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ universeBuilder.getUniverse.mockResolvedValue(makeUniverse());
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({ pronouns: 'she/her', age: 'late 20s' }),
+ runId: 'r1', model: 'qwen-vl',
+ });
+});
+
+describe('buildVisionExpandPrompt', () => {
+ it('asks for JSON keyed by the requested blank fields only', () => {
+ const p = buildVisionExpandPrompt({ name: 'Freydis', imageCount: 1, blankFields: ['pronouns', 'colorPalette'] });
+ expect(p).toMatch(/"pronouns"/);
+ expect(p).toMatch(/"colorPalette"/);
+ // A field NOT in blankFields shouldn't appear in the schema body.
+ expect(p).not.toMatch(/"speechAccent"/);
+ expect(p).toMatch(/reference image of the character "Freydis"/);
+ });
+
+ it('uses the multi-image consistent-subject framing', () => {
+ const p = buildVisionExpandPrompt({ name: 'Freydis', imageCount: 3, blankFields: ['age'] });
+ expect(p).toMatch(/3 reference images of the same character/);
+ expect(p).toMatch(/CONSISTENT across all/);
+ });
+
+ it('offers the full field set when no blank list is given', () => {
+ const p = buildVisionExpandPrompt({ imageCount: 1 });
+ expect(p).toMatch(/"speechPattern"/);
+ expect(p).toMatch(/"handGestures"/);
+ });
+
+ it('is re-exported on __testing', () => {
+ expect(__testing.buildVisionExpandPrompt).toBe(buildVisionExpandPrompt);
+ });
+});
+
+describe('expandEntityFromImages', () => {
+ it('proposes blank-field values without writing', async () => {
+ const out = await expandEntityFromImages({
+ universeId: 'uni-1', entryId: 'chr-1', name: 'Freydis', screenshots: ['a.png'],
+ });
+ expect(out.fields).toEqual({ pronouns: 'she/her', age: 'late 20s' });
+ expect(out.updatedFields).toEqual(expect.arrayContaining(['pronouns', 'age']));
+ expect(out.llm).toEqual({ provider: 'ollama', model: 'qwen-vl' });
+ // Review-only: the runner ran, but nothing in the service writes the universe.
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['a.png'], source: 'universe-vision-expand' }),
+ );
+ });
+
+ it('does not overwrite a populated field (no-clobber)', async () => {
+ universeBuilder.getUniverse.mockResolvedValue(makeUniverse({ pronouns: 'they/them' }));
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({ pronouns: 'she/her', age: 'late 20s' }), model: 'qwen-vl',
+ });
+ const out = await expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] });
+ expect(out.fields).not.toHaveProperty('pronouns');
+ expect(out.fields).toEqual({ age: 'late 20s' });
+ });
+
+ it('sanitizes proposed list rows and drops malformed ones', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ colorPalette: [{ name: 'rust', hex: '#b7410e', role: 'cloak' }, { hex: '#000' }],
+ }),
+ model: 'qwen-vl',
+ });
+ const out = await expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] });
+ expect(out.fields.colorPalette).toHaveLength(1);
+ expect(out.fields.colorPalette[0]).toMatchObject({ name: 'rust' });
+ });
+
+ it('short-circuits a locked character with no LLM call', async () => {
+ universeBuilder.getUniverse.mockResolvedValue(makeUniverse({ locked: true }));
+ const out = await expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] });
+ expect(out).toMatchObject({ locked: true, updatedFields: [] });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('404s when the character is not in the universe', async () => {
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'nope', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_CANON_NOT_FOUND', status: 404 });
+ });
+
+ it('throws NO_API_PROVIDER (503) when no API provider is configured', async () => {
+ aiProvider.resolveAPIProvider.mockResolvedValue(null);
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'NO_API_PROVIDER', status: 503 });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('rejects (VISION_FALLBACK_DROPPED_IMAGES) on a fallback to a non-API provider', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: '{}', model: 'sonnet', usedFallback: true, fallbackProvider: { id: 'claude-code', type: 'cli' },
+ });
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'VISION_FALLBACK_DROPPED_IMAGES', status: 502 });
+ });
+
+ it('rejects bad JSON (UNIVERSE_VISION_EXPAND_BAD_JSON 502)', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'not json at all', model: 'qwen-vl' });
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_VISION_EXPAND_BAD_JSON', status: 502 });
+ });
+
+ it('rejects a JSON array (non-object) response', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: '[1,2,3]', model: 'qwen-vl' });
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_VISION_EXPAND_BAD_JSON', status: 502 });
+ });
+
+ it('rejects when no images are supplied', async () => {
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: [] }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it(`rejects more than ${VISION_EXPAND_MAX_IMAGES} images`, async () => {
+ const tooMany = Array.from({ length: VISION_EXPAND_MAX_IMAGES + 1 }, (_, i) => `${i}.png`);
+ await expect(expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: tooMany }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+});