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

add vision-model image-to-prose describe for universe canon entries

[._.]/ Adam Eivy176df64187bb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6a72049d6d..6348a5c3c5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Describe a canon character / place / object from reference image(s)** — Each canon card in the Universe editor (Cast, Places, Objects) gains a **Describe from image(s)** button (the scan-text icon next to Render). Upload one reference image to turn it into an image-gen-ready prose description, or several images of the *same* subject (a character from multiple angles, a location across lighting conditions) and a vision model returns the description **common to all of them** — ignoring incidental differences like pose, background, and framing. You pick the **provider + model on demand** in the modal (only API/vision-capable providers are offered), edit the generated prose before applying, and it writes straight into the entry's descriptor field (`physicalDescription` for characters, `description` for places/objects) — the same field the render prompt reads. Vision runs through the existing API runner's `image_url` content-block path; the new `runPromptThroughProvider({ screenshots })` arg threads images through the shared runner, and the stateless `POST /api/universe-builder/describe-from-images` endpoint resolves an API provider (clear `NO_API_PROVIDER` error if none is configured) and builds the per-kind vision prompt. (`server/services/universeVisionDescribe.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/components/pipeline/CanonCard.jsx`, `client/src/components/universe/UniverseCanonSection.jsx`)
+
- **`/do:next` hot button on the app manage page** — The Agent Operations panel on an app's Overview tab gains a **`/do:next`** button alongside `/do:push`, `/do:review`, `/do:replan`, and the rest. One click queues a CoS agent that claims the next unclaimed `PLAN.md` item, works it in an isolated worktree, and ships a PR — the consumer counterpart to `/do:replan`. The bundled **slashdo** submodule was updated to the latest release (which ships the `do:next` command). (`lib/slashdo`, `client/src/components/apps/SlashDoPanel.jsx`, `server/routes/cosTaskRoutes.js`)
- **Add canon characters / places / objects by hand** — Each canon section in the Universe editor (Cast, Places, Objects) now has an **Add** button next to "Pick from Catalog" — the same manual-add affordance the variation buckets already had. Click it, type a name (and optionally a description), and Save mints a new canon entry you can immediately render, refine, and fill in. The entry lands unlocked (so its inline editors are usable right away), dedupes case-insensitively against existing names, and persists through the same optimistic-append path as the catalog picker — so you no longer have to extract from prose, pick from the catalog, or promote a variation just to start a character. (`client/src/components/universe/UniverseCanonSection.jsx`)
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index bc0918a2e1..14382c7240 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 } from 'lucide-react';
+import { Loader2, ImagePlus, 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';
@@ -264,6 +264,10 @@ export default function CanonCard({
// Optional — settings-only "Render clean plate" affordance. Called with
// `(entry)` so the parent can build the no-people prompt variant.
onRenderCleanPlate = null,
+ // Optional — "Describe from image(s)" affordance. Called with `(entry)` so
+ // the parent can open the vision-describe modal seeded with this entry. When
+ // omitted (e.g. the pipeline series view) the button is hidden.
+ onDescribeImages = null,
// 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.
@@ -451,6 +455,20 @@ export default function CanonCard({
{inFlightJobId ? <Loader2 size={14} className="animate-spin" /> : <Square size={14} />}
</button>
) : null}
+ {onDescribeImages ? (
+ <button
+ type="button"
+ onClick={() => onDescribeImages(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 generated description`
+ : `Describe ${entry.name} from a reference image (or several) using a vision model`}
+ aria-label={`Describe ${entry.name} from images`}
+ >
+ <ScanText size={14} />
+ </button>
+ ) : null}
{kind.key === 'characters' && onRefine ? (
<button
type="button"
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index e8e542963e..8242f1a268 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -18,6 +18,7 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import IngredientPicker from '../IngredientPicker';
+import VisionDescribeModal from './VisionDescribeModal';
import { linkCatalogIngredient } from '../../services/apiCatalog';
import {
extractUniverseCanon,
@@ -136,6 +137,8 @@ export default function UniverseCanonSection({
const [extractOpen, setExtractOpen] = useState(false);
// Which kind's "Pick from Catalog" modal is open (a KINDS entry, or null).
const [catalogPickerKind, setCatalogPickerKind] = useState(null);
+ // `{ kind, entry }` when the vision "Describe from image(s)" modal is open.
+ const [describeTarget, setDescribeTarget] = 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
@@ -805,6 +808,7 @@ export default function UniverseCanonSection({
togglingLockId={togglingLockId}
onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
onRenderCleanPlate={handleRenderCleanPlate}
+ onDescribeImages={(entry) => setDescribeTarget({ kind, entry })}
seriesNameMap={usage?.seriesNameMap || null}
onBulkLock={(nextLocked) => handleBulkLockKind(kind, nextLocked)}
bulkLocking={bulkLockingKindKey === kind.key}
@@ -837,11 +841,30 @@ export default function UniverseCanonSection({
refKind="universe"
refId={universeId}
/>
+
+ {/* Vision "Describe from image(s)" — turns reference images into an
+ image-gen-ready description and writes it into the entry's descriptor
+ field (the same field CanonCard's inline editor binds to). */}
+ {describeTarget ? (
+ <VisionDescribeModal
+ open
+ kind={describeTarget.kind.apiKind}
+ entryName={describeTarget.entry.name}
+ onApply={(description) => {
+ if (describeTarget.kind.descField) {
+ handlePatchEntry(describeTarget.kind, describeTarget.entry.id, {
+ [describeTarget.kind.descField]: description,
+ });
+ }
+ }}
+ onClose={() => setDescribeTarget(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, seriesNameMap, onBulkLock, bulkLocking, fullList, 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, seriesNameMap, onBulkLock, bulkLocking, fullList, 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
@@ -1039,6 +1062,7 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
togglingLock={togglingLockId === entry.id}
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
+ onDescribeImages={onDescribeImages}
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
new file mode 100644
index 0000000000..5920c2a1a5
--- /dev/null
+++ b/client/src/components/universe/VisionDescribeModal.jsx
@@ -0,0 +1,223 @@
+/**
+ * Vision-to-prose modal for a canon entry (character / place / object).
+ *
+ * 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, …).
+ *
+ * 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.
+ */
+
+import { useState, useCallback, useRef } from 'react';
+import { Loader2, ImagePlus, Sparkles, X } from 'lucide-react';
+import Modal from '../ui/Modal';
+import toast from '../ui/Toast';
+import ProviderModelSelector from '../ProviderModelSelector';
+import useProviderModels from '../../hooks/useProviderModels';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { processScreenshotUploads } from '../../utils/fileUpload';
+import { describeEntityFromImages } 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.
+const apiProviderFilter = (p) => p.enabled !== false && p.type === 'api';
+
+// Mirror server VISION_MAX_IMAGES so the UI stops the user before the request
+// 400s.
+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.
+ const [images, setImages] = useState([]);
+ const [uploading, setUploading] = useState(false);
+ const [result, setResult] = useState('');
+ const fileInputRef = useRef(null);
+
+ const {
+ providers, selectedProviderId, selectedModel, availableModels,
+ setSelectedProviderId, setSelectedModel, loading: providersLoading,
+ } = useProviderModels({ filter: apiProviderFilter, silent: true });
+
+ const noun = KIND_NOUN[kind] || 'subject';
+
+ const handleFiles = useCallback(async (fileList) => {
+ // Respect the cap across the already-selected set. Slice BEFORE uploading
+ // so over-cap files never hit the screenshots dir as orphans.
+ const room = MAX_IMAGES - images.length;
+ if (room <= 0) {
+ toast.error(`Up to ${MAX_IMAGES} images at a time`);
+ return;
+ }
+ const files = Array.from(fileList || []);
+ 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 }])),
+ onError: (msg) => toast.error(msg),
+ });
+ setUploading(false);
+ }, [images.length]);
+
+ const removeImage = useCallback((filename) => {
+ setImages((prev) => prev.filter((img) => img.filename !== filename));
+ }, []);
+
+ const [runDescribe, describing] = useAsyncAction(async () => {
+ const res = await describeEntityFromImages({
+ kind,
+ name: entryName || undefined,
+ screenshots: images.map((img) => img.filename),
+ providerId: selectedProviderId || undefined,
+ model: selectedModel || undefined,
+ }, { silent: true });
+ if (res?.description) setResult(res.description);
+ return res;
+ }, { errorMessage: 'Failed to describe image(s)' });
+
+ const apply = () => {
+ onApply(result.trim());
+ toast.success(`Applied description to ${entryName || `this ${noun}`}`);
+ onClose();
+ };
+
+ const canDescribe = images.length > 0 && !describing && !uploading;
+ const multi = images.length > 1;
+
+ return (
+ <Modal open={open} onClose={onClose} size="lg" closeOnBackdrop={false} ariaLabel={`Describe ${noun} from images`}>
+ <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" />
+ Describe {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} />
+ </button>
+ </div>
+
+ <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.
+ </p>
+
+ {/* Image picker + thumbnails */}
+ <div>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ multiple
+ className="hidden"
+ onChange={(e) => { handleFiles(e.target.files); e.target.value = ''; }}
+ />
+ <div className="flex flex-wrap gap-2">
+ {images.map((img) => (
+ <div key={img.filename} className="relative w-20 h-20">
+ <img
+ src={img.preview || `/api/screenshots/${encodeURIComponent(img.filename)}`}
+ alt="reference"
+ className="w-full h-full object-cover rounded border border-port-border"
+ />
+ <button
+ type="button"
+ onClick={() => removeImage(img.filename)}
+ title="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"
+ >
+ <X size={11} />
+ </button>
+ </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>
+ ) : null}
+ </div>
+ </div>
+
+ {/* Provider + model picker (API/vision-capable providers only) */}
+ {providers.length > 0 ? (
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={setSelectedProviderId}
+ onModelChange={setSelectedModel}
+ label="Vision provider"
+ layout="row"
+ />
+ ) : (
+ <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.'}
+ </p>
+ )}
+
+ <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>
+
+ {/* Result — editable before applying */}
+ {result ? (
+ <div className="space-y-2">
+ <label htmlFor="vision-describe-result" className="block text-xs text-gray-500">
+ Generated description (edit before applying if you like)
+ </label>
+ <textarea
+ id="vision-describe-result"
+ value={result}
+ onChange={(e) => setResult(e.target.value)}
+ 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"
+ />
+ </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}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 0e4eb772c0..134b714665 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -55,6 +55,19 @@ 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 } }`.
+export const describeEntityFromImages = ({
+ kind, name, context, screenshots, providerId, model,
+} = {}, options = {}) => request('/universe-builder/describe-from-images', {
+ method: 'POST',
+ body: JSON.stringify({ kind, name, context, screenshots, 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 = ({
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 66ca3576bc..e50d9e5059 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -217,6 +217,14 @@ export function assertProvider(provider, { message, code, status = 503 } = {}) {
* `text` value — callers receive the full buffered text either way.
* For TUI providers the stripped chunks are emitted; the final `text`
* is the cleaned response with the prompt-echo elided.
+ * @param {string[]} [args.screenshots] — image paths for a vision/multimodal
+ * call (relative to the runner's screenshots dir, or absolute). API providers
+ * only: the toolkit's executeApiRun base64-encodes each and sends them as
+ * `image_url` content blocks ahead of the prompt text. CLI/TUI providers
+ * ignore them (no vision path), so callers needing vision must resolve an
+ * API provider up front. On a fallback to a non-API provider the images are
+ * silently dropped — the fallback only fires after the primary API call has
+ * already failed.
* @param {number} [args.timeout] — per-call timeout in ms; falls back to
* `provider.timeout`, then DEFAULT_TIMEOUT_MS. Callers like the loop
* runner expose a user-configurable timeout that isn't a provider attr.
@@ -475,7 +483,7 @@ function stripFallbackContext(err) {
* swapped to a fallback when the requested provider was already marked
* unavailable).
*/
-async function executeProviderRunOnce({ provider, prompt, source, model, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride }) {
+async function executeProviderRunOnce({ provider, prompt, source, model, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride, screenshots = [] }) {
// Resolve the model that'll actually run BEFORE creating the run record
// so the record reflects reality. resolveEffectiveModel handles both
// the override-honored fallback chain AND the args-baked-CLI case
@@ -622,7 +630,7 @@ async function executeProviderRunOnce({ provider, prompt, source, model, runId:
stopRun(runId).catch(() => { /* best-effort cancel */ });
safeReject(new Error(`API execution timed out after ${effectiveTimeout}ms`));
}, effectiveTimeout);
- executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: [], onData, onComplete }).catch(safeReject);
+ executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete }).catch(safeReject);
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,
// interactive view this TUI run surfaces in the Shell page.
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index b7fed32067..cf60f4cc1c 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -126,6 +126,32 @@ describe('promptRunner — happy paths', () => {
expect(runner.executeCliRun).not.toHaveBeenCalled();
});
+ it('forwards screenshots to executeApiRun for a vision/multimodal call', async () => {
+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));
+
+ await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'describe',
+ source: 'test',
+ model: 'gpt-vision',
+ screenshots: ['a.png', 'b.png'],
+ });
+
+ expect(runner.executeApiRun).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['a.png', 'b.png'] }),
+ );
+ });
+
+ it('defaults screenshots to [] when omitted', async () => {
+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));
+
+ await runPromptThroughProvider({ provider: apiProvider(), prompt: 'p', source: 'test' });
+
+ expect(runner.executeApiRun).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: [] }),
+ );
+ });
+
it('runs the fallbackModel (not the primary model) when createRun proactively swaps to a fallback', async () => {
// Primary is benched at call time, so the toolkit createRun swaps to an
// API fallback and surfaces the configured fallbackModel. The run must
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 3803464f3c..e0aca26cb4 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -7,6 +7,7 @@
* PATCH /api/universe-builder/:id → Universe
* 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/render → { runId, collectionId, jobIds, promptCount }
* GET /api/universe-builder/:id/runs → Run[]
*/
@@ -26,6 +27,8 @@ 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 { sanitizeFilename } from '../lib/fileUtils.js';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';
import { autoSortOtherBuckets } from '../services/universeBuilderAutoSort.js';
@@ -393,6 +396,31 @@ router.post('/generate-variations', asyncHandler(async (req, res) => {
res.json(result);
}));
+// 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.
+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),
+ 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 ?? {});
+ // Strip any path components so a crafted filename can't escape the
+ // screenshots dir when the runner joins it (the upload route already
+ // sanitizes on write; this guards a hand-crafted request body too).
+ const screenshots = body.screenshots.map((f) => sanitizeFilename(f));
+ const result = await describeEntityFromImages({ ...body, screenshots });
+ res.json(result);
+}));
+
// Refines the 3 top-level prompts (starter / style / negative) based on
// user feedback. Stateless — the caller decides whether to write the
// result back to a saved universe. Keep ahead of `/:id`.
diff --git a/server/services/universeVisionDescribe.js b/server/services/universeVisionDescribe.js
new file mode 100644
index 0000000000..b463425659
--- /dev/null
+++ b/server/services/universeVisionDescribe.js
@@ -0,0 +1,145 @@
+/**
+ * Universe Builder — vision-to-prose describer.
+ *
+ * Takes one or more reference images of a character / place / object and asks
+ * a vision-capable model to turn them into an image-gen-ready prose
+ * description that can seed the canon entry's descriptor field.
+ *
+ * Single image → describe that subject. Multiple images → find the visual
+ * traits CONSISTENT across all of them (the same character shot from several
+ * angles, a location across lighting conditions, a prop in different hands) and
+ * describe that shared subject, ignoring incidental differences.
+ *
+ * Vision is an API-provider-only capability: the toolkit's executeApiRun is the
+ * only runner path that base64-encodes images into `image_url` content blocks
+ * (CLI/TUI providers receive prompts via stdin only). So we resolve an
+ * API-type provider up front and throw NO_API_PROVIDER when none is configured,
+ * rather than silently running a text-only completion that hallucinates a
+ * description from nothing.
+ */
+
+import { resolveAPIProvider, stripCodeFences } from '../lib/aiProvider.js';
+import { runPromptThroughProvider, assertProvider } from '../lib/promptRunner.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+// Singular kind → render-prompt focus. Mirrors the descriptor emphasis the
+// canon render path already uses (CanonCard's descField placeholders).
+export const VISION_KINDS = ['character', 'place', 'object'];
+
+// Cap the number of images per call. The runner base64-inlines every image
+// into a single request body, so a large batch balloons the prompt and the
+// provider's context window. 8 angles is plenty to triangulate a consistent
+// subject.
+export const VISION_MAX_IMAGES = 8;
+
+const KIND_NOUN = {
+ character: 'character',
+ place: 'place / location',
+ object: 'object / prop',
+};
+
+const KIND_FOCUS = {
+ character:
+ 'Focus on the figure itself: apparent age range, build, face, hair, skin, distinctive features, wardrobe/clothing, posture, signature props, and color palette. Ignore background and incidental scenery unless it is part of who they are.',
+ place:
+ 'Focus on the location: architecture or terrain, scale, materials, dominant color palette, lighting and time of day, weather, atmosphere/mood, and recurring visual motifs. Ignore any people or transient subjects passing through.',
+ object:
+ '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.',
+};
+
+/**
+ * Build the vision prompt. The model is told to return ONE prose paragraph
+ * suitable for a Stable-Diffusion-style image generator — no markdown, no
+ * preamble, no bullet lists — so the result can drop straight into the canon
+ * descriptor field.
+ */
+function buildVisionPrompt({ kind, name, context, imageCount }) {
+ const noun = KIND_NOUN[kind];
+ const focus = KIND_FOCUS[kind];
+ const subject = name ? `the ${noun} "${name}"` : `this ${noun}`;
+ const intro = imageCount > 1
+ ? `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}`;
+}
+
+/**
+ * Describe a canon entity from reference image(s).
+ *
+ * @param {object} args
+ * @param {'character'|'place'|'object'} args.kind
+ * @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
+ * (filenames under data/screenshots, or absolute paths)
+ * @param {string} [args.providerId] — preferred API provider id
+ * @param {string} [args.model] — preferred model id
+ * @returns {Promise<{ description: string, llm: { provider: string, model: string|null } }>}
+ */
+export async function describeEntityFromImages({ kind, name, context, screenshots, providerId, model } = {}) {
+ if (!VISION_KINDS.includes(kind)) {
+ throw new ServerError(`Unsupported kind "${kind}" — expected one of ${VISION_KINDS.join(', ')}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+ 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_MAX_IMAGES) {
+ throw new ServerError(`Too many images — describe at most ${VISION_MAX_IMAGES} at once`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message:
+ '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,
+ });
+
+ const prompt = buildVisionPrompt({ kind, name, context, imageCount: images.length });
+
+ 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,
+ });
+
+ 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',
+ });
+ }
+
+ return {
+ description,
+ // Report the provider/model that ACTUALLY ran (a fallback may have swapped
+ // it), so the UI's picker can reflect reality instead of the request.
+ llm: {
+ provider: result.fallbackProvider?.id || provider.id,
+ model: result.model || null,
+ },
+ };
+}
+
+export const __testing = { buildVisionPrompt };
diff --git a/server/services/universeVisionDescribe.test.js b/server/services/universeVisionDescribe.test.js
new file mode 100644
index 0000000000..f90c84fb6e
--- /dev/null
+++ b/server/services/universeVisionDescribe.test.js
@@ -0,0 +1,106 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// resolveAPIProvider drives provider selection; stripCodeFences is real (re-
+// exported through the partial mock so the cleanup of the runner's text works).
+vi.mock('../lib/aiProvider.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, resolveAPIProvider: vi.fn() };
+});
+
+// runPromptThroughProvider is the LLM boundary — mock it. assertProvider is
+// real (it's the typed-throw helper we want exercised end to end).
+vi.mock('../lib/promptRunner.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, runPromptThroughProvider: 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 apiProvider = { id: 'ollama', type: 'api', defaultModel: 'llava' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'a weathered scavenger', runId: 'r1', model: 'llava' });
+});
+
+describe('buildVisionPrompt', () => {
+ it('asks to describe a single subject for one image', () => {
+ const p = __testing.buildVisionPrompt({ kind: 'character', name: 'Vex', imageCount: 1 });
+ expect(p).toMatch(/reference image of the character "Vex"/);
+ expect(p).not.toMatch(/CONSISTENT across all/);
+ });
+
+ it('asks for the common description across multiple images', () => {
+ const p = __testing.buildVisionPrompt({ kind: 'place', name: 'The Foundry', imageCount: 3 });
+ expect(p).toMatch(/3 reference images of the same place/);
+ expect(p).toMatch(/CONSISTENT across all/);
+ });
+
+ it('folds per-kind focus + known context into the prompt', () => {
+ const p = __testing.buildVisionPrompt({ kind: 'object', context: 'a relic blade', imageCount: 1 });
+ expect(p).toMatch(/Focus on the object/);
+ expect(p).toMatch(/Known context.*a relic blade/s);
+ });
+});
+
+describe('describeEntityFromImages', () => {
+ it('returns the cleaned description + the provider/model that ran', async () => {
+ const out = await describeEntityFromImages({
+ kind: 'character', name: 'Vex', screenshots: ['a.png'], providerId: 'ollama', model: 'llava',
+ });
+ expect(out).toEqual({ description: 'a weathered scavenger', llm: { provider: 'ollama', model: 'llava' } });
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ screenshots: ['a.png'], source: 'universe-vision-describe' }),
+ );
+ });
+
+ it('reports the fallback provider id when the runner swapped providers', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: 'x', model: 'gpt-vision', fallbackProvider: { id: 'openai' },
+ });
+ const out = await describeEntityFromImages({ kind: 'place', screenshots: ['a.png'] });
+ expect(out.llm).toEqual({ provider: 'openai', model: 'gpt-vision' });
+ });
+
+ it('strips code fences the model may wrap the prose in', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: '```\nfenced prose\n```', model: 'llava' });
+ const out = await describeEntityFromImages({ kind: 'object', screenshots: ['a.png'] });
+ expect(out.description).toBe('fenced prose');
+ });
+
+ it('rejects an unsupported kind', async () => {
+ await expect(describeEntityFromImages({ kind: 'spaceship', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it('rejects when no images are supplied', async () => {
+ await expect(describeEntityFromImages({ kind: 'character', screenshots: [] }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it(`rejects more than ${VISION_MAX_IMAGES} images`, async () => {
+ const tooMany = Array.from({ length: VISION_MAX_IMAGES + 1 }, (_, i) => `${i}.png`);
+ await expect(describeEntityFromImages({ kind: 'character', screenshots: tooMany }))
+ .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ });
+
+ it('throws NO_API_PROVIDER (503) when no API provider is configured', async () => {
+ aiProvider.resolveAPIProvider.mockResolvedValue(null);
+ await expect(describeEntityFromImages({ kind: 'character', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'NO_API_PROVIDER', status: 503 });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('throws VISION_EMPTY (502) when the model returns blank prose', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: ' ', model: 'llava' });
+ await expect(describeEntityFromImages({ kind: 'character', screenshots: ['a.png'] }))
+ .rejects.toMatchObject({ code: 'VISION_EMPTY', status: 502 });
+ });
+
+ it('exports the three canon kinds', () => {
+ expect(VISION_KINDS).toEqual(['character', 'place', 'object']);
+ });
+});