Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(pipeline): visual style catalog + per-stage overrides for image gen
[._.]/ Adam Eivyf017ee551c40
diff --git a/client/src/components/pipeline/VisualStylePicker.jsx b/client/src/components/pipeline/VisualStylePicker.jsxnew file mode 100644index 0000000000..400e7c67b7--- /dev/null+++ b/client/src/components/pipeline/VisualStylePicker.jsx@@ -0,0 +1,166 @@+/**+ * Drives both series-level default (`series.visualStyleDefault`) and per-stage+ * overrides (`issue.stages.<stageId>.visualStyleOverride`). Symmetric contract:+ * value: { id, customPrompt } | null+ * onChange(next | null)+ */++import { useEffect, useRef, useState } from 'react';+import { ChevronDown, Palette, X } from 'lucide-react';+import { listPipelineVisualStyles } from '../../services/apiPipeline';++export default function VisualStylePicker({+ value,+ onChange,+ disabled = false,+ // Pass from per-stage callers; series-level callers leave undefined.+ inheritedLabel = null,+ // Compact shrinks the chip — used in stage headers where vertical space is tight.+ compact = false,+}) {+ const [styles, setStyles] = useState([]);+ const [open, setOpen] = useState(false);+ const wrapRef = useRef(null);+ // Draft is only seeded when the menu opens — otherwise a parent re-render+ // that re-passes the same value reference would wipe in-progress typing.+ const [customDraft, setCustomDraft] = useState('');++ useEffect(() => {+ let cancelled = false;+ listPipelineVisualStyles()+ .then((res) => { if (!cancelled) setStyles(Array.isArray(res?.styles) ? res.styles : []); })+ .catch(() => { /* picker degrades to "no styles" rather than throwing */ });+ return () => { cancelled = true; };+ }, []);++ useEffect(() => {+ if (disabled && open) setOpen(false);+ }, [disabled, open]);++ useEffect(() => {+ if (!open) return undefined;+ setCustomDraft(value?.customPrompt || '');+ const onDoc = (e) => {+ if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);+ };+ const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };+ document.addEventListener('mousedown', onDoc);+ document.addEventListener('keydown', onKey);+ return () => {+ document.removeEventListener('mousedown', onDoc);+ document.removeEventListener('keydown', onKey);+ };+ // value?.customPrompt intentionally omitted — see comment on customDraft.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const activeId = value?.id || null;+ const activeStyle = activeId ? styles.find((s) => s.id === activeId) : null;+ const hasValue = !!(value?.id || value?.customPrompt);++ const triggerLabel = hasValue+ ? (activeStyle?.name || 'Custom')+ : (inheritedLabel || 'Pick style');++ const choose = (id) => {+ onChange?.({ id, customPrompt: value?.customPrompt || null });+ setOpen(false);+ };++ const clear = () => {+ onChange?.(null);+ setOpen(false);+ };++ const applyCustom = () => {+ const trimmed = (customDraft || '').trim();+ if (!trimmed && !value?.id) {+ onChange?.(null);+ } else {+ onChange?.({ id: value?.id || null, customPrompt: trimmed || null });+ }+ setOpen(false);+ };++ return (+ <div ref={wrapRef} className="relative inline-block">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ disabled={disabled}+ className={`inline-flex items-center gap-1.5 rounded-md border bg-port-card text-xs disabled:opacity-50 disabled:cursor-not-allowed ${+ compact ? 'px-2 py-1' : 'px-2.5 py-1.5'+ } ${+ hasValue+ ? 'border-port-accent/50 text-white'+ : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/50'+ }`}+ title={hasValue+ ? `Visual style: ${triggerLabel}${value?.customPrompt ? ' (+ custom)' : ''}`+ : 'Pick a visual style preset for downstream image generation'}+ aria-expanded={open}+ >+ <Palette size={12} className="text-gray-500" />+ <span className="font-medium">{triggerLabel}</span>+ {value?.customPrompt && <span className="text-[10px] text-gray-500">+ custom</span>}+ <ChevronDown size={12} className="text-gray-500" />+ </button>++ {open && (+ <div className="absolute right-0 mt-1 w-80 max-h-[70vh] overflow-y-auto bg-port-card border border-port-border rounded-lg shadow-lg z-30 p-1">+ {hasValue && (+ <button+ type="button"+ onClick={clear}+ className="w-full flex items-center gap-1.5 px-2 py-1.5 rounded text-xs text-gray-400 hover:bg-port-bg hover:text-white"+ >+ <X size={12} />+ <span>{inheritedLabel ? 'Reset to series default' : 'Clear style'}</span>+ </button>+ )}++ {styles.length === 0 && (+ <div className="px-2 py-1.5 text-xs text-gray-500">Loading styles…</div>+ )}++ {styles.map((s) => {+ const active = activeId === s.id;+ return (+ <button+ key={s.id}+ type="button"+ onClick={() => choose(s.id)}+ className={`w-full text-left px-2 py-1.5 rounded text-xs ${+ active ? 'bg-port-accent/15 text-white' : 'text-gray-300 hover:bg-port-bg hover:text-white'+ }`}+ >+ <div className="font-medium">{s.name}</div>+ <div className="text-[10px] text-gray-500 mt-0.5">{s.description}</div>+ </button>+ );+ })}++ <div className="mt-1 pt-1 px-2 py-1.5 border-t border-port-border">+ <div className="text-[10px] text-gray-500 mb-1">+ Custom additions (appended to the preset fragment)+ </div>+ <textarea+ value={customDraft}+ onChange={(e) => setCustomDraft(e.target.value)}+ placeholder="e.g. heavier ink weight, muted earth palette"+ rows={2}+ className="block w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs resize-y"+ />+ <button+ type="button"+ onClick={applyCustom}+ className="mt-1.5 w-full px-2 py-1 rounded bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90"+ >+ Apply custom additions+ </button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 840178cfb6..8ea307abc1 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -18,6 +18,7 @@ import {generatePipelineComicCover,updatePipelineComicPage,updatePipelineIssue,+ updateIssueStageVisualStyle,PIPELINE_STAGE_LABELS,PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,@@ -26,6 +27,7 @@ import { getSettings, updateSettings } from '../../../services/apiSystem';import { listImageModels } from '../../../services/apiImageVideo';import MediaJobThumb from '../MediaJobThumb';import MediaPreview from '../../media/MediaPreview';+import VisualStylePicker from '../VisualStylePicker';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';import { deriveAvailableBackends } from '../../../lib/imageGenBackends';@@ -271,6 +273,16 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions) : null}</div><div className="flex items-center gap-2">+ <VisualStylePicker+ compact+ value={comicPages.visualStyleOverride || null}+ inheritedLabel={series?.visualStyleDefault?.id ? 'Series default' : 'Pick style'}+ onChange={async (next) => {+ const updated = await updateIssueStageVisualStyle(issue.id, 'comicPages', next)+ .catch((err) => { toast.error(err.message || 'Save failed'); return null; });+ if (updated) onStageUpdate?.('comicPages', updated.stages.comicPages, updated);+ }}+ /><buttontype="button"onClick={openImageSettings}diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex f1b01885cc..6bccd57ab3 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -2,7 +2,8 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { Link } from 'react-router-dom';import { Film, ExternalLink, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react';import toast from '../../ui/Toast';-import { generatePipelineVisualImage } from '../../../services/api';+import { generatePipelineVisualImage, updateIssueStageVisualStyle } from '../../../services/api';+import VisualStylePicker from '../VisualStylePicker';import { getCreativeDirectorProject } from '../../../services/apiCreativeDirector';import { getSceneStatusBadge, PROJECT_STATUS_LABEL } from '../../creative-director/sceneStatus';import ScenePreview from '../../creative-director/ScenePreview';@@ -22,7 +23,7 @@ const STATUS_LABEL = {paused: 'Paused',};-export default function EpisodeVideoStage({ issue, onStageUpdate }) {+export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {const stage = issue.stages?.episodeVideo || {};const cdProjectId = stage.cdProjectId || null;const storyboardScenes = issue.stages?.storyboards?.scenes || [];@@ -145,6 +146,16 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {</div>{!cdProjectId ? (<div className="flex items-center gap-2 flex-wrap">+ <VisualStylePicker+ compact+ value={stage.visualStyleOverride || null}+ inheritedLabel={series?.visualStyleDefault?.id ? 'Series default' : 'Pick style'}+ onChange={async (next) => {+ const updated = await updateIssueStageVisualStyle(issue.id, 'episodeVideo', next)+ .catch((err) => { toast.error(err.message || 'Save failed'); return null; });+ if (updated) onStageUpdate?.('episodeVideo', updated.stages.episodeVideo, updated);+ }}+ /><selectvalue={aspectRatio}onChange={(e) => setAspectRatio(e.target.value)}diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex 4e12c0ee8f..2ee76f3bba 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -24,9 +24,11 @@ import {generatePipelineSceneVideo,refinePipelineSceneImagePrompt,updatePipelineIssue,+ updateIssueStageVisualStyle,extractPipelineStoryboardScenes,} from '../../../services/api';import MediaJobThumb from '../MediaJobThumb';+import VisualStylePicker from '../VisualStylePicker';import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';export default function StoryboardsStage({ issue, series, onStageUpdate, actionsGated = false }) {@@ -199,6 +201,16 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions</p></div><div className="flex items-center gap-2 flex-wrap">+ <VisualStylePicker+ compact+ value={issue.stages?.storyboards?.visualStyleOverride || null}+ inheritedLabel={series?.visualStyleDefault?.id ? 'Series default' : 'Pick style'}+ onChange={async (next) => {+ const updated = await updateIssueStageVisualStyle(issue.id, 'storyboards', next)+ .catch((err) => { toast.error(err.message || 'Save failed'); return null; });+ if (updated) onStageUpdate?.('storyboards', updated.stages.storyboards, updated);+ }}+ /><buttontype="button"onClick={() => onExtractClick('teleplay')}diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 0355a14025..07c8101af5 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -18,6 +18,7 @@ import {} from 'lucide-react';import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';+import VisualStylePicker from '../components/pipeline/VisualStylePicker';import {getPipelineSeries, updatePipelineSeries,listPipelineIssues,@@ -303,6 +304,18 @@ function BibleSidebar({ series, universes, patchSeries, onAddCharacter, onUpdate/></Field>+ <Field label="Visual style preset">+ <div className="flex items-center gap-2">+ <VisualStylePicker+ value={series.visualStyleDefault || null}+ onChange={(next) => patchSeries({ visualStyleDefault: next })}+ />+ <span className="text-xs text-gray-500">+ Applied to comic pages, storyboards, and episode video unless a stage overrides it.+ </span>+ </div>+ </Field>+<Field label="Linked World (from Universe Builder)"><div className="flex items-center gap-2"><selectdiff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 78a0e406dd..c6d2c976a2 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -53,6 +53,25 @@ export const PIPELINE_STAGE_STATUS_COLOR = Object.freeze({error: 'text-port-error',});+// ---- Visual styles catalog ----+// Module-level promise dedup: the catalog is immutable for the life of the+// server, so concurrent mounts share one in-flight fetch and subsequent calls+// resolve from cache. Cleared on rejection so a transient failure can retry.+let _visualStylesPromise = null;+export const listPipelineVisualStyles = () => {+ if (!_visualStylesPromise) {+ _visualStylesPromise = request('/pipeline/visual-styles')+ .catch((err) => { _visualStylesPromise = null; throw err; });+ }+ return _visualStylesPromise;+};++// Per-stage style override is identical-shaped across every visual stage —+// factor the PATCH shape here so the three stage components don't each+// hand-roll the body.+export const updateIssueStageVisualStyle = (issueId, stageId, next) =>+ updatePipelineIssue(issueId, { stages: { [stageId]: { visualStyleOverride: next } } });+// ---- Series ----export const listPipelineSeries = () => request('/pipeline/series');export const getPipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`);diff --git a/server/lib/visualStyles.js b/server/lib/visualStyles.jsnew file mode 100644index 0000000000..7dc45a069f--- /dev/null+++ b/server/lib/visualStyles.js@@ -0,0 +1,172 @@+/**+ * Curated catalog of named visual-style presets injected into every pipeline+ * image-gen call. Catalog is additive-only: never renumber existing ids, since+ * they are the persisted contract on `series.visualStyleDefault` and+ * `issue.stages.<id>.visualStyleOverride`.+ */++import { trimTo } from './storyBible.js';++export const CUSTOM_PROMPT_MAX = 2000;++export const VISUAL_STYLES = Object.freeze([+ {+ id: 'graphic-novel',+ name: 'Graphic Novel',+ description: 'Bold ink lines, halftone dots, saturated comic-book colors, panel-ready aesthetic.',+ promptFragment: 'graphic novel aesthetic, bold ink outlines, halftone shading dots, saturated comic-book color palette, dynamic compositions, clean panel-ready linework',+ },+ {+ id: 'cinematic',+ name: 'Cinematic Realism',+ description: 'Photorealistic film look, 35mm grain, shallow depth of field, dramatic lighting.',+ promptFragment: 'photorealistic, 35mm film, shallow depth of field, dramatic key lighting, soft falloff, cinematic color grade',+ },+ {+ id: 'anime',+ name: 'Anime',+ description: 'Cel-shaded Japanese animation, bold lines, vivid colors, expressive features.',+ promptFragment: 'anime style, Japanese animation, vivid colors, expressive features, cel-shaded, clean line art',+ },+ {+ id: 'film-noir',+ name: 'Film Noir',+ description: 'High-contrast black and white, deep shadows, hard light sources, chiaroscuro.',+ promptFragment: 'film noir, high contrast black and white, deep shadows, dramatic chiaroscuro lighting, hard light sources, venetian-blind shadows',+ },+ {+ id: 'watercolor',+ name: 'Watercolor',+ description: 'Soft washes, bleeding edges, hand-painted feel, visible paper texture.',+ promptFragment: 'watercolor painting style, soft washes, bleeding edges, hand-painted, visible paper texture, organic pigment pooling',+ },+ {+ id: 'oil-painting',+ name: 'Oil Painting',+ description: 'Classical fine art, rich impasto brushwork, layered glazes.',+ promptFragment: 'classical oil painting, rich impasto brushwork, layered glazes, painterly edges, gallery-style finish',+ },+ {+ id: 'pixar-3d',+ name: '3D Animation',+ description: 'Stylized 3D characters and environments, soft global illumination, family-friendly look.',+ promptFragment: 'stylized 3D animation, Pixar-grade rendering, soft global illumination, expressive proportions, polished surface shaders',+ },+ {+ id: 'retro-70s',+ name: 'Retro 70s',+ description: 'Warm film grain, faded Kodachrome palette, soft vignette, vintage feel.',+ promptFragment: 'retro 1970s film, warm grain, faded Kodachrome colors, vintage lens, soft focus vignette, occasional film burn',+ },+ {+ id: 'scifi-neon',+ name: 'Sci-Fi Neon',+ description: 'Cyberpunk neon glow, holographic UI, dark cityscapes, colored light spill.',+ promptFragment: 'sci-fi cyberpunk, neon glow, holographic UI, futuristic, dark atmosphere with colored light spill, rain-slick streets',+ },+ {+ id: 'documentary',+ name: 'Documentary',+ description: 'Naturalistic handheld feel, available light, real-world textures.',+ promptFragment: 'documentary style, naturalistic, handheld camera feel, available light, real-world textures, observational framing',+ },+ {+ id: 'dark-fantasy',+ name: 'Dark Fantasy',+ description: 'Epic scale, magical lighting, otherworldly atmosphere, ethereal glow.',+ promptFragment: 'dark fantasy art, ethereal glow, magical particles, epic landscapes, otherworldly atmosphere, painterly fantasy illustration',+ },+ {+ id: 'minimalist',+ name: 'Minimalist',+ description: 'Clean lines, muted palette, simple compositions with negative space.',+ promptFragment: 'minimalist illustration, clean lines, muted palette, generous negative space, simple geometric compositions',+ },+ {+ id: 'flat-vector',+ name: 'Flat Vector Explainer',+ description: 'Bold geometric shapes, vivid saturated palette, clean edges, explainer-video style.',+ promptFragment: 'flat vector illustration, bold geometric shapes, vivid saturated palette, clean edges, explainer-video aesthetic',+ },+ {+ id: 'lined-illustration',+ name: 'Lined Illustration',+ description: 'Hand-drawn outlines with textured fills, warm earthy tones, organic feel.',+ promptFragment: 'hand-drawn illustration, organic outlines with textured fills, warm earthy tones, sketchy editorial feel',+ },+ {+ id: 'paper-cutout',+ name: 'Paper Cut-Out',+ description: 'Layered paper craft, torn edges, collage-like compositions, stop-motion feel.',+ promptFragment: 'paper cut-out craft style, layered paper depth, torn edges, collage compositions, stop-motion feel',+ },+]);++const STYLES_BY_ID = new Map(VISUAL_STYLES.map((s) => [s.id, s]));++export function getVisualStyle(id) {+ if (!id || typeof id !== 'string') return null;+ return STYLES_BY_ID.get(id) || null;+}++// Catalog default per stage. Comic pages render to a graphic-novel aesthetic+// unless overridden; storyboards/episode videos default to cinematic so shot+// composition reads like film. Series-level default still wins when set.+const STAGE_FALLBACK = Object.freeze({+ comicPages: 'graphic-novel',+ storyboards: 'cinematic',+ episodeVideo: 'cinematic',+});++/**+ * Sanitize a visualStyleDefault / visualStyleOverride payload. Returns either+ * a valid object or `null` so readers don't have to defensively spread.+ *+ * Allows `{ id: null, customPrompt: "..." }` so a user can supply a one-off+ * custom style without picking a catalog preset.+ */+export function sanitizeVisualStyleRef(raw) {+ if (raw === null || raw === undefined) return null;+ if (typeof raw !== 'object') return null;+ const id = typeof raw.id === 'string' && raw.id.trim() ? raw.id.trim() : null;+ const validId = id && STYLES_BY_ID.has(id) ? id : null;+ const customPrompt = trimTo(raw.customPrompt, CUSTOM_PROMPT_MAX);+ if (!validId && !customPrompt) return null;+ return { id: validId, customPrompt: customPrompt || null };+}++/**+ * Resolve the effective style for a stage. Priority:+ * 1. issue.stages[stageId].visualStyleOverride+ * 2. series.visualStyleDefault+ * 3. STAGE_FALLBACK[stageId]+ *+ * The persisted refs are re-sanitized on read so hand-edited JSON and+ * future catalog deletions degrade gracefully instead of producing a broken+ * empty fragment.+ */+export function resolveVisualStyle(series, issue, stageId) {+ const override = sanitizeVisualStyleRef(issue?.stages?.[stageId]?.visualStyleOverride);+ const seriesDefault = sanitizeVisualStyleRef(series?.visualStyleDefault);+ const fallbackId = STAGE_FALLBACK[stageId] || null;+ const fallback = fallbackId ? { id: fallbackId, customPrompt: null } : null;+ const ref = override || seriesDefault || fallback;+ if (!ref) return null;+ const catalog = ref.id ? getVisualStyle(ref.id) : null;+ const fragmentParts = [+ catalog?.promptFragment || '',+ ref.customPrompt || '',+ ].map((p) => p.trim()).filter(Boolean);+ if (fragmentParts.length === 0) return null;+ return {+ id: ref.id,+ name: catalog?.name || 'Custom',+ promptFragment: fragmentParts.join(', '),+ };+}++// Returned as a plain (non-frozen) array so JSON serialization doesn't trip+// over the readonly trap on the catalog reference.+export function listVisualStyles() {+ return VISUAL_STYLES.map((s) => ({ ...s }));+}diff --git a/server/lib/visualStyles.test.js b/server/lib/visualStyles.test.jsnew file mode 100644index 0000000000..9c8547f6b4--- /dev/null+++ b/server/lib/visualStyles.test.js@@ -0,0 +1,149 @@+import { describe, it, expect } from 'vitest';+import {+ VISUAL_STYLES,+ getVisualStyle,+ sanitizeVisualStyleRef,+ resolveVisualStyle,+ listVisualStyles,+} from './visualStyles.js';++describe('visualStyles — catalog shape invariants', () => {+ it('catalog is a non-empty frozen array', () => {+ expect(Array.isArray(VISUAL_STYLES)).toBe(true);+ expect(VISUAL_STYLES.length).toBeGreaterThan(0);+ expect(Object.isFrozen(VISUAL_STYLES)).toBe(true);+ });++ it('every entry has id, name, description, and a non-empty promptFragment', () => {+ for (const s of VISUAL_STYLES) {+ expect(typeof s.id).toBe('string');+ expect(s.id.length).toBeGreaterThan(0);+ expect(typeof s.name).toBe('string');+ expect(s.name.length).toBeGreaterThan(0);+ expect(typeof s.description).toBe('string');+ expect(typeof s.promptFragment).toBe('string');+ expect(s.promptFragment.trim().length).toBeGreaterThan(0);+ }+ });++ it('ids are unique', () => {+ const ids = VISUAL_STYLES.map((s) => s.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('exposes a graphic-novel preset for the comic-pages default', () => {+ expect(VISUAL_STYLES.some((s) => s.id === 'graphic-novel')).toBe(true);+ });++ it('listVisualStyles returns a plain (non-frozen) copy', () => {+ const list = listVisualStyles();+ expect(Object.isFrozen(list)).toBe(false);+ expect(list.length).toBe(VISUAL_STYLES.length);+ });+});++describe('visualStyles — getVisualStyle', () => {+ it('returns the catalog entry for a known id', () => {+ const s = getVisualStyle('graphic-novel');+ expect(s).toBeTruthy();+ expect(s.id).toBe('graphic-novel');+ });++ it('returns null for unknown / empty / non-string ids', () => {+ expect(getVisualStyle('does-not-exist')).toBe(null);+ expect(getVisualStyle('')).toBe(null);+ expect(getVisualStyle(null)).toBe(null);+ expect(getVisualStyle(undefined)).toBe(null);+ expect(getVisualStyle(42)).toBe(null);+ });+});++describe('visualStyles — sanitizeVisualStyleRef', () => {+ it('returns null for null / undefined / non-objects', () => {+ expect(sanitizeVisualStyleRef(null)).toBe(null);+ expect(sanitizeVisualStyleRef(undefined)).toBe(null);+ expect(sanitizeVisualStyleRef('graphic-novel')).toBe(null);+ expect(sanitizeVisualStyleRef(42)).toBe(null);+ });++ it('drops unknown ids but keeps customPrompt', () => {+ const out = sanitizeVisualStyleRef({ id: 'does-not-exist', customPrompt: 'foo' });+ expect(out).toEqual({ id: null, customPrompt: 'foo' });+ });++ it('returns null when both id and customPrompt are empty', () => {+ expect(sanitizeVisualStyleRef({ id: '', customPrompt: '' })).toBe(null);+ expect(sanitizeVisualStyleRef({ id: 'unknown', customPrompt: ' ' })).toBe(null);+ });++ it('keeps a valid id with no customPrompt', () => {+ expect(sanitizeVisualStyleRef({ id: 'graphic-novel' })).toEqual({+ id: 'graphic-novel', customPrompt: null,+ });+ });++ it('trims customPrompt and caps at 2000 chars', () => {+ const long = 'x'.repeat(3000);+ const out = sanitizeVisualStyleRef({ id: 'cinematic', customPrompt: ` ${long} ` });+ expect(out.customPrompt.length).toBe(2000);+ expect(out.id).toBe('cinematic');+ });+});++describe('visualStyles — resolveVisualStyle priority', () => {+ const series = { visualStyleDefault: { id: 'cinematic' } };+ const issueWithOverride = {+ stages: { comicPages: { visualStyleOverride: { id: 'anime' } } },+ };+ const issueWithoutOverride = { stages: { comicPages: {} } };++ it('uses stage override when present', () => {+ const r = resolveVisualStyle(series, issueWithOverride, 'comicPages');+ expect(r.id).toBe('anime');+ });++ it('falls back to series default when no override', () => {+ const r = resolveVisualStyle(series, issueWithoutOverride, 'comicPages');+ expect(r.id).toBe('cinematic');+ });++ it('falls back to stage catalog default when neither override nor series default', () => {+ const r = resolveVisualStyle({}, { stages: { comicPages: {} } }, 'comicPages');+ expect(r.id).toBe('graphic-novel');+ });++ it('storyboards defaults to cinematic when nothing is set', () => {+ const r = resolveVisualStyle({}, {}, 'storyboards');+ expect(r.id).toBe('cinematic');+ });++ it('episodeVideo defaults to cinematic when nothing is set', () => {+ const r = resolveVisualStyle({}, {}, 'episodeVideo');+ expect(r.id).toBe('cinematic');+ });++ it('returns null when stageId has no fallback and nothing is configured', () => {+ expect(resolveVisualStyle({}, {}, 'unknown-stage')).toBe(null);+ });++ it('appends customPrompt onto the catalog promptFragment', () => {+ const r = resolveVisualStyle(+ { visualStyleDefault: { id: 'graphic-novel', customPrompt: 'extra ink weight' } },+ {},+ 'comicPages',+ );+ expect(r.promptFragment).toMatch(/halftone/);+ expect(r.promptFragment).toMatch(/extra ink weight/);+ });++ it('handles customPrompt-only refs (id: null)', () => {+ const r = resolveVisualStyle(+ { visualStyleDefault: { id: null, customPrompt: 'noir-leaning watercolor' } },+ {},+ 'comicPages',+ );+ expect(r.id).toBe(null);+ expect(r.name).toBe('Custom');+ expect(r.promptFragment).toBe('noir-leaning watercolor');+ });+});diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex c58007d1f3..77c8447b2c 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -49,6 +49,7 @@ import { refineCharacterDescription } from '../services/pipeline/nounRefine.js';import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';+import { listVisualStyles } from '../lib/visualStyles.js';import { parseComicScript } from '../lib/comicScriptParser.js';import {LENGTH_PROFILE_NAMES,@@ -108,6 +109,16 @@ const objectSchema = objectBibleCreateSchema.extend({id: z.string().trim().max(80).optional(),}).passthrough();+// Visual style ref — `{ id, customPrompt? }`. The id is validated lazily+// (against the catalog in server/lib/visualStyles.js) by the sanitizer at+// persist time so adding a new style doesn't force a schema bump. `id: null`+// + `customPrompt: "..."` is the valid "custom only" shape — preventing it+// here would force the UI to invent a sentinel id just to clear the picker.+const visualStyleRefSchema = z.object({+ id: z.string().trim().max(64).nullable().optional(),+ customPrompt: z.string().trim().max(2000).nullable().optional(),+}).nullable();+// Arc + Season — phase 2 of Story Arc Planning. The arc lives on the series// record itself; seasons get their own resource so the route layer can take// per-record CRUD without forcing the caller to PATCH the whole series.@@ -146,6 +157,7 @@ const seriesCreateSchema = z.object({arc: arcSchema.nullable().optional(),seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),+ visualStyleDefault: visualStyleRefSchema.optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,@@ -163,6 +175,7 @@ const seriesPatchSchema = z.object({arc: arcSchema.nullable().optional(),seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),+ visualStyleDefault: visualStyleRefSchema.optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,@@ -229,6 +242,10 @@ const visualStageInputSchema = stageInputSchema.extend({imageJobId: z.string().trim().max(200).nullable().optional(),prompt: z.string().max(16_000).nullable().optional(),}).nullable().optional(),+ // Per-stage visual style override. Validated lazily by the sanitizer+ // (unknown catalog ids are dropped) so adding a new style doesn't force+ // a schema bump on every client.+ visualStyleOverride: visualStyleRefSchema.optional(),});const issuePatchSchema = z.object({@@ -412,6 +429,12 @@ const autoRunSchema = z.object({modelId: z.string().trim().max(64).optional(),});+// Static catalog. Express's default ETag handles re-fetches; clients also+// dedup via the module-level promise cache in apiPipeline.js.+router.get('/visual-styles', asyncHandler(async (_req, res) => {+ res.json({ styles: listVisualStyles() });+}));+// =====================// Series routes// =====================diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex c8c3f7786c..704c26081e 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -26,6 +26,7 @@ import {CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,} from '../../lib/issueLength.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';+import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';import { ARC_ROLES } from '../../lib/storyArc.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';@@ -177,6 +178,9 @@ const sanitizeVisualStage = (raw, stageId = null) => {// field — `sanitizeStages` below threads the stageId through so the// canonical persistence path enforces the rule.cover: stageId === null || stageId === 'comicPages' ? sanitizeCover(raw?.cover) : null,+ // Per-stage override so a series can mix aesthetics+ // (e.g. graphic-novel panels + cinematic storyboards).+ visualStyleOverride: sanitizeVisualStyleRef(raw?.visualStyleOverride),};};diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex c458a300b2..24fb487132 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -19,6 +19,7 @@ import {isStr, trimTo,} from '../../lib/storyBible.js';import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';+import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';import { extractBible } from '../../lib/bibleExtractor.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';@@ -86,6 +87,11 @@ const sanitizeSeries = (raw) => {arc: sanitizeArc(raw.arc),seasons: sanitizeSeasonList(raw.seasons),styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),+ // Series-level default visual style (catalog id + optional custom prompt).+ // `null` when the user hasn't picked one — stage-level fallbacks in+ // resolveVisualStyle() handle that case so legacy series keep rendering+ // without a writer pass.+ visualStyleDefault: sanitizeVisualStyleRef(raw.visualStyleDefault),targetFormat,issueCountTarget,llm,@@ -194,6 +200,7 @@ export async function updateSeries(id, patch = {}) {...('arc' in patch ? { arc: patch.arc } : {}),...('seasons' in patch ? { seasons: patch.seasons } : {}),...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),+ ...('visualStyleDefault' in patch ? { visualStyleDefault: patch.visualStyleDefault } : {}),...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),...('origin' in patch ? { origin: patch.origin } : {}),diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 719cd579b3..15b66dba54 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -36,14 +36,22 @@ import {matchSettingsInText, matchObjectsInText,} from '../../lib/scenePrompt.js';import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';+import { resolveVisualStyle } from '../../lib/visualStyles.js';import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { runPromptRefine } from './refineHelpers.js';import { resolveSeriesCanonSync } from './seriesCanon.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';-const stackStyle = (series, extraStyle) =>- [series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');+const joinStyleParts = (...parts) =>+ parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');++const stackStyle = (series, extraStyle) => joinStyleParts(series?.styleNotes, extraStyle);++// Resolved fragment leads so the curated aesthetic dominates over the caller's+// free-text additions.+const composeExtraStyle = (series, issue, stageId, callerExtraStyle = '') =>+ joinStyleParts(resolveVisualStyle(series, issue, stageId)?.promptFragment, callerExtraStyle);const applyWorldStyle = (prompt, world) => {if (!world) return prompt;@@ -232,7 +240,8 @@ export async function enqueueComicCover(issueId, options = {}) {: (cover?.script || '');const mode = resolveMode(options, settings);const prompt = composeComicCoverPrompt({- series, world, issue, coverScript, extraStyle: options.extraStyle,+ series, world, issue, coverScript,+ extraStyle: composeExtraStyle(series, issue, 'comicPages', options.extraStyle),});const jobId = enqueueImageJob({prompt, world, settings, options, mode,@@ -394,7 +403,8 @@ export async function enqueueVisualComicPage(issueId, options = {}) {// already rejected above. The "(continuation of previous beat)" placeholder// covers panels with no description, so the prompt is non-empty by here.const prompt = composeComicPagePrompt({- series, world, page, pageNumber: pageIndex + 1, extraStyle: options.extraStyle,+ series, world, page, pageNumber: pageIndex + 1,+ extraStyle: composeExtraStyle(series, issue, 'comicPages', options.extraStyle),matchedCharacters, matchedSettings, matchedObjects,});@@ -419,14 +429,14 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {status: 400, code: 'PIPELINE_VISUAL_BAD_STAGE',});}- const { settings, series, world, canon } = await loadBibleContext(issueId);+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);const mode = resolveMode(options, settings);const matchedCharacters = matchCharactersInText(options.description || '', canon.characters);const prompt = composeVisualPrompt({series,description: options.description,slugline: options.slugline,- extraStyle: options.extraStyle,+ extraStyle: composeExtraStyle(series, issue, stageId, options.extraStyle),matchedCharacters,world,});@@ -493,7 +503,7 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =series,description: scene.description,slugline: scene.slugline || '',- extraStyle: options.extraStyle,+ extraStyle: composeExtraStyle(series, issue, 'storyboards', options.extraStyle),matchedCharacters,world,});diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 5853047220..48a81a4e08 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -225,6 +225,48 @@ describe('composeComicPagePrompt', () => {});});+describe('visual style resolution threads into image prompts', () => {+ it('applies series.visualStyleDefault catalog fragment to the cover prompt', async () => {+ const seriesMod = await import('./series.js');+ seriesMod.getSeries.mockResolvedValueOnce({+ id: 'ser-test', name: 'Test', styleNotes: '', characters: [], settings: [],+ visualStyleDefault: { id: 'graphic-novel', customPrompt: null },+ });+ const result = await enqueueComicCover('iss-test', {});+ // The graphic-novel preset's promptFragment lands inside the cover prompt's+ // `Art style: ...` clause via stackStyle's composition.+ expect(result.prompt).toMatch(/Art style:.*halftone/i);+ });++ it('stage override beats series default for comic page prompts', async () => {+ const seriesMod = await import('./series.js');+ seriesMod.getSeries.mockResolvedValueOnce({+ id: 'ser-test', name: 'Test', styleNotes: '', characters: [], settings: [],+ visualStyleDefault: { id: 'graphic-novel', customPrompt: null },+ });+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: {+ ...mockIssue.stages,+ comicPages: {+ ...mockIssue.stages.comicPages,+ visualStyleOverride: { id: 'anime', customPrompt: null },+ },+ },+ });+ const result = await enqueueComicCover('iss-test', {});+ expect(result.prompt).toMatch(/anime|cel-shaded/i);+ expect(result.prompt).not.toMatch(/halftone/i);+ });++ it('falls back to the storyboards catalog default (cinematic) when nothing is configured', async () => {+ const result = await enqueueStoryboardSceneVideo('iss-test', 0, { aspectRatio: '16:9' });+ // 'cinematic' fragment includes "photorealistic" and "35mm film".+ const params = enqueueJobMock.mock.calls.at(-1)[0].params;+ expect(params.prompt).toMatch(/photorealistic|35mm film/i);+ });+});+describe('enqueueStoryboardSceneVideo', () => {it('rejects a non-integer sceneIndex', async () => {await expect(enqueueStoryboardSceneVideo('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);