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 Decks: a Create-section designer for playing-card and tarot decks

[._.]/ Adam Eivy8132ccf8f911
diff --git a/client/src/App.jsx b/client/src/App.jsx
index f73fb26859..44c0218e87 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -79,6 +79,8 @@ const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));
const Sprites = lazyWithReload(() => import('./pages/Sprites'));
const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));
const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));
+const Decks = lazyWithReload(() => import('./pages/Decks'));
+const DeckDetail = lazyWithReload(() => import('./pages/DeckDetail'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
const Templates = lazyWithReload(() => import('./pages/Templates'));
const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));
@@ -544,6 +546,8 @@ export default function App() {
<Route path="catalog/:type/:id" element={<CatalogIngredient />} />
<Route path="mood-boards" element={<MoodBoards />} />
<Route path="mood-boards/:id" element={<MoodBoardDetail />} />
+ <Route path="decks" element={<Decks />} />
+ <Route path="decks/:id" element={<DeckDetail />} />
<Route path="universes" element={<Universes />} />
<Route path="universes/new" element={<UniverseBuilder />} />
<Route path="universes/:universeId" element={<UniverseBuilder />} />
diff --git a/client/src/components/decks/DeckCardDrawer.jsx b/client/src/components/decks/DeckCardDrawer.jsx
new file mode 100644
index 0000000000..b6320e9541
--- /dev/null
+++ b/client/src/components/decks/DeckCardDrawer.jsx
@@ -0,0 +1,118 @@
+import { useEffect, useState } from 'react';
+import { Link2, Loader2, Sparkles, Star, Trash2 } from 'lucide-react';
+import Drawer from '../Drawer';
+import { composeCardRenderPrompt } from '../../lib/decks';
+
+const INPUT_CLASS = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
+
+/**
+ * Per-card editor: the subject prompt and negative (saved explicitly), the
+ * composed prompt the renderer will actually send, the canon link, the render
+ * history (pick a primary, drop a stale render), and a re-render button.
+ */
+export default function DeckCardDrawer({ deck, card, open, inFlight, onClose, onSave, onRender, onPreview, saving = false }) {
+ const [prompt, setPrompt] = useState('');
+ const [negative, setNegative] = useState('');
+ useEffect(() => {
+ setPrompt(card?.prompt || '');
+ setNegative(card?.negativePrompt || '');
+ }, [card?.id, card?.prompt, card?.negativePrompt]);
+
+ if (!card) return null;
+ const dirty = prompt !== (card.prompt || '') || negative !== (card.negativePrompt || '');
+ const composed = composeCardRenderPrompt(deck, { ...card, prompt, negativePrompt: negative });
+ const refs = Array.isArray(card.imageRefs) ? card.imageRefs : [];
+
+ return (
+ <Drawer open={open} onClose={onClose} title={card.name} subtitle={card.groupLabel} size="md" closeLabel="Close card">
+ <div className="p-4 space-y-4">
+ {card.canonRef?.name ? (
+ <p className="inline-flex items-center gap-1.5 text-xs text-gray-300 rounded border border-port-border px-2 py-1">
+ <Link2 size={12} aria-hidden="true" /> Depicts <span className="text-white">{card.canonRef.name}</span> <span className="text-gray-500">({card.canonRef.kind})</span>
+ </p>
+ ) : null}
+ {card.motif ? <p className="text-xs text-gray-500">Traditional motif: {card.motif}</p> : null}
+
+ <div>
+ <label htmlFor="deck-card-prompt" className="block text-xs text-gray-400 mb-1">Subject prompt</label>
+ <textarea id="deck-card-prompt" rows={6} value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Figures, pose, setting, symbols, the suit emblem count…" className={INPUT_CLASS} />
+ </div>
+ <div>
+ <label htmlFor="deck-card-negative" className="block text-xs text-gray-400 mb-1">Extra negative (this card only)</label>
+ <input id="deck-card-negative" value={negative} onChange={(e) => setNegative(e.target.value)} className={INPUT_CLASS} />
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => onSave({ prompt, negativePrompt: negative })}
+ disabled={!dirty || saving}
+ className="min-h-[38px] rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50"
+ >
+ {saving ? 'Saving…' : 'Save prompt'}
+ </button>
+ <button
+ type="button"
+ onClick={onRender}
+ disabled={!prompt.trim() || dirty || !!inFlight || saving}
+ title={dirty ? 'Save the prompt first' : 'Queue a render for this card'}
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-accent/40 px-3 py-2 text-sm text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ {inFlight ? <Loader2 size={14} className="animate-spin" aria-hidden="true" /> : <Sparkles size={14} aria-hidden="true" />}
+ {inFlight ? 'Rendering…' : refs.length ? 'Re-render' : 'Render'}
+ </button>
+ </div>
+
+ <details className="rounded border border-port-border bg-port-bg/40 p-2">
+ <summary className="text-xs text-gray-400 cursor-pointer">Composed render prompt</summary>
+ <p className="mt-2 text-xs text-gray-300 whitespace-pre-wrap">{composed.prompt}</p>
+ {composed.negativePrompt ? <p className="mt-2 text-xs text-port-error/80">Negative: {composed.negativePrompt}</p> : null}
+ </details>
+
+ <section>
+ <h3 className="text-xs text-gray-400 mb-2">Renders ({refs.length})</h3>
+ {refs.length ? (
+ <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4">
+ {[...refs].reverse().map((filename) => {
+ const isPrimary = filename === card.primaryImageRef;
+ return (
+ <li key={filename} className="space-y-1">
+ <button type="button" onClick={() => onPreview(filename)} className="block w-full" title="Open">
+ <img src={`/data/images/${encodeURIComponent(filename)}`} alt={`${card.name} render`} className={`aspect-[2/3] w-full rounded object-cover border ${isPrimary ? 'border-port-accent' : 'border-port-border'}`} />
+ </button>
+ <div className="flex items-center justify-between">
+ <button
+ type="button"
+ onClick={() => onSave({ primaryImageRef: filename })}
+ disabled={isPrimary || saving}
+ className={`min-h-[32px] min-w-[32px] inline-flex items-center justify-center rounded ${isPrimary ? 'text-port-accent' : 'text-gray-500 hover:text-white'}`}
+ aria-label={isPrimary ? 'Primary render' : 'Make primary'}
+ title={isPrimary ? 'Primary render' : 'Make primary'}
+ >
+ <Star size={13} fill={isPrimary ? 'currentColor' : 'none'} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onSave({ imageRefs: refs.filter((f) => f !== filename) })}
+ disabled={saving}
+ className="min-h-[32px] min-w-[32px] inline-flex items-center justify-center rounded text-gray-500 hover:text-port-error"
+ aria-label="Remove this render from the card"
+ title="Remove from card (the gallery keeps the image)"
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="text-xs text-gray-600">Nothing rendered yet.</p>
+ )}
+ </section>
+ {card.render?.status === 'failed' && card.render.error ? (
+ <p className="text-xs text-port-error">Last render failed: {card.render.error}</p>
+ ) : null}
+ </div>
+ </Drawer>
+ );
+}
diff --git a/client/src/components/decks/DeckCardGrid.jsx b/client/src/components/decks/DeckCardGrid.jsx
new file mode 100644
index 0000000000..52e9205b1c
--- /dev/null
+++ b/client/src/components/decks/DeckCardGrid.jsx
@@ -0,0 +1,88 @@
+import { useMemo } from 'react';
+import { Link2 } from 'lucide-react';
+import EntryThumbSlot from '../universe/EntryThumbSlot';
+import Pill from '../ui/Pill';
+import { CARD_STATUS, cardInFlightJobId, cardStatus } from '../../lib/decks';
+
+const STATUS_TONE = {
+ [CARD_STATUS.EMPTY]: 'context',
+ [CARD_STATUS.PROMPTED]: 'muted',
+ [CARD_STATUS.QUEUED]: 'accent',
+ [CARD_STATUS.RUNNING]: 'accent',
+ [CARD_STATUS.RENDERED]: 'success',
+ [CARD_STATUS.FAILED]: 'error',
+};
+const STATUS_LABEL = {
+ [CARD_STATUS.EMPTY]: 'needs prompt',
+ [CARD_STATUS.PROMPTED]: 'ready',
+ // The queue never stamps 'running' on the card; the slot's live thumb shows
+ // progress, so both in-flight states read as one word.
+ [CARD_STATUS.QUEUED]: 'rendering',
+ [CARD_STATUS.RUNNING]: 'rendering',
+ [CARD_STATUS.RENDERED]: 'rendered',
+ [CARD_STATUS.FAILED]: 'failed',
+};
+
+/**
+ * The deck laid out by group (suit / arcana / jokers / back), one three-state
+ * thumbnail slot per card: pending render → live progress, rendered → the
+ * primary image, empty → a one-click render affordance. Status and in-flight
+ * job derive from the card's persisted `render` record, so a slot settling
+ * locally and a reload after the server filed the render read the same way.
+ * Clicking a card's name opens its drawer; the slot's image opens the lightbox.
+ */
+export default function DeckCardGrid({ deck, onOpenCard, onRenderCard, onPreview, onRenderComplete, onRenderTerminal }) {
+ const groups = useMemo(() => {
+ const byGroup = Map.groupBy(deck.cards, (card) => card.group);
+ return [...byGroup].map(([key, cards]) => ({ key, label: cards[0].groupLabel || key, cards }));
+ }, [deck.cards]);
+
+ return (
+ <div className="space-y-6">
+ {groups.map((group) => (
+ <section key={group.key} aria-label={group.label}>
+ <h2 className="text-sm font-medium text-white mb-2 flex items-center gap-2">
+ {group.label}
+ <span className="text-xs text-gray-500">{group.cards.filter((c) => c.imageRefs?.length).length}/{group.cards.length}</span>
+ </h2>
+ <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">
+ {group.cards.map((card) => {
+ const inFlight = cardInFlightJobId(card);
+ const status = cardStatus(card);
+ return (
+ <li key={card.id} className="flex flex-col items-center gap-1.5 rounded-lg border border-port-border bg-port-card p-2">
+ <EntryThumbSlot
+ size="xl"
+ inFlightJobId={inFlight}
+ imageRefs={card.imageRefs}
+ primaryImageRef={card.primaryImageRef}
+ onRender={() => onRenderCard(card)}
+ onPreview={() => onPreview(card)}
+ onComplete={(filename) => onRenderComplete(card.id, filename)}
+ onTerminalStatus={(s) => onRenderTerminal(card.id, s)}
+ canRender={!!card.prompt && !inFlight}
+ alt={card.name}
+ />
+ <button
+ type="button"
+ onClick={() => onOpenCard(card)}
+ className="w-full min-h-[44px] text-center text-xs text-gray-200 hover:text-white leading-tight"
+ title="Edit this card"
+ >
+ <span className="block truncate font-medium">{card.name}</span>
+ {card.canonRef?.name ? (
+ <span className="mt-0.5 inline-flex max-w-full items-center gap-1 text-[11px] text-gray-400">
+ <Link2 size={10} aria-hidden="true" /><span className="truncate">{card.canonRef.name}</span>
+ </span>
+ ) : null}
+ </button>
+ <Pill tone={STATUS_TONE[status]} size="xs">{STATUS_LABEL[status]}</Pill>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/components/decks/DeckCardGrid.test.jsx b/client/src/components/decks/DeckCardGrid.test.jsx
new file mode 100644
index 0000000000..44fb4567e9
--- /dev/null
+++ b/client/src/components/decks/DeckCardGrid.test.jsx
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent, within } from '@testing-library/react';
+import DeckCardGrid from './DeckCardGrid';
+
+// MediaJobThumb (the pending branch of EntryThumbSlot) subscribes to a socket;
+// stub the hook so the in-flight card renders without a live queue.
+vi.mock('../../hooks/useMediaJobProgress', () => ({
+ default: () => ({ status: 'running', progress: 0.4, step: 4, totalSteps: 10, currentImage: null, filename: null, error: null }),
+}));
+
+const card = (id, group, extra = {}) => ({
+ id, key: id, name: `Card ${id}`, group, groupLabel: group === 'major' ? 'Major Arcana' : 'Cups',
+ prompt: '', imageRefs: [], primaryImageRef: null, render: null, canonRef: null, ...extra,
+});
+const deck = {
+ id: 'd1',
+ cards: [
+ card('a', 'major', { prompt: 'a fool' }),
+ card('b', 'major', { prompt: 'a magician', imageRefs: ['b.png'], primaryImageRef: 'b.png', canonRef: { kind: 'character', id: 'c1', name: 'Alice' } }),
+ card('c', 'cups', { prompt: 'an ace', render: { jobId: 'job-c', status: 'queued' } }),
+ card('d', 'cups', { prompt: 'a two', render: { jobId: 'job-d', status: 'canceled' } }),
+ card('e', 'cups'),
+ ],
+};
+
+const renderGrid = (over = {}) => {
+ const props = {
+ deck, onOpenCard: vi.fn(), onRenderCard: vi.fn(), onPreview: vi.fn(),
+ onRenderComplete: vi.fn(), onRenderTerminal: vi.fn(), ...over,
+ };
+ render(<DeckCardGrid {...props} />);
+ return props;
+};
+
+describe('DeckCardGrid', () => {
+ it('groups cards by suit/arcana with a rendered count per group', () => {
+ renderGrid();
+ const major = screen.getByRole('region', { name: 'Major Arcana' });
+ expect(within(major).getByText('1/2')).toBeInTheDocument();
+ expect(within(screen.getByRole('region', { name: 'Cups' })).getByText('0/3')).toBeInTheDocument();
+ });
+
+ it('offers a render only for prompted, idle cards and routes the click to that card', () => {
+ const props = renderGrid();
+ // EntryThumbSlot names the empty slot by its state: a renderable card reads
+ // "Render image…", a blocked one carries the slot's disabled copy. Card a
+ // (prompted) and d (failed, retryable) are enabled; e has no prompt.
+ const enabled = screen.getAllByRole('button', { name: /render image for this item/i });
+ expect(enabled).toHaveLength(2);
+ expect(screen.getByRole('button', { name: /save the universe first/i })).toBeDisabled();
+ fireEvent.click(enabled[0]);
+ expect(props.onRenderCard).toHaveBeenCalledWith(expect.objectContaining({ id: 'a' }));
+ });
+
+ it('derives every badge from the card record: in-flight, rendered, failed, ready, needs prompt', () => {
+ renderGrid();
+ expect(screen.getByText('rendering')).toBeInTheDocument();
+ expect(screen.getByText('rendered')).toBeInTheDocument();
+ expect(screen.getByText('failed')).toBeInTheDocument();
+ expect(screen.getByText('ready')).toBeInTheDocument();
+ expect(screen.getByText('needs prompt')).toBeInTheDocument();
+ });
+
+ it('opens the drawer from the card name and shows the cast canon entry', () => {
+ const props = renderGrid();
+ // The completed thumb is also a button named by the card, so reach the
+ // name button through its title (second card of the first group).
+ fireEvent.click(screen.getAllByTitle('Edit this card')[1]);
+ expect(props.onOpenCard).toHaveBeenCalledWith(expect.objectContaining({ id: 'b' }));
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/decks/DeckLlmPinPicker.jsx b/client/src/components/decks/DeckLlmPinPicker.jsx
new file mode 100644
index 0000000000..da17602317
--- /dev/null
+++ b/client/src/components/decks/DeckLlmPinPicker.jsx
@@ -0,0 +1,54 @@
+import { useEffect, useState } from 'react';
+import ProviderModelSelector from '../ProviderModelSelector';
+import useProviderModels from '../../hooks/useProviderModels';
+
+/**
+ * Provider / model / effort pin for the deck's text-LLM jobs (casting + prompt
+ * writing). The persisted pin is the source of truth: it is mirrored into the
+ * picker whenever it changes (a refetched deck, another surface's edit), and
+ * every user change is lifted as `{ providerId, model, effort }` — an empty
+ * provider means "the active provider", matching the server's fallback.
+ */
+export default function DeckLlmPinPicker({ pin, onChange, label = 'Prompt model', disabled = false }) {
+ const {
+ providers, selectedProviderId, selectedModel, availableModels,
+ setSelectedProviderId, setSelectedModel, loading,
+ } = useProviderModels({ allowDefault: true, withEffort: true, silent: true });
+ const [effort, setEffort] = useState(pin?.effort || '');
+
+ const pinProvider = pin?.providerId || '';
+ const pinModel = pin?.model || '';
+ const pinEffort = pin?.effort || '';
+ useEffect(() => {
+ if (loading) return;
+ setSelectedProviderId(providers.some((p) => p.id === pinProvider) ? pinProvider : '');
+ setSelectedModel(pinModel);
+ setEffort(pinEffort);
+ }, [loading, providers, pinProvider, pinModel, pinEffort, setSelectedProviderId, setSelectedModel]);
+
+ const emit = (next) => onChange?.({
+ providerId: next.providerId ?? selectedProviderId,
+ model: next.model ?? selectedModel,
+ effort: next.effort ?? effort,
+ });
+
+ return (
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={(id) => { setSelectedProviderId(id); emit({ providerId: id, model: '' }); }}
+ onModelChange={(m) => { setSelectedModel(m); emit({ model: m }); }}
+ effort={effort}
+ onEffortChange={(e) => { setEffort(e); emit({ effort: e }); }}
+ emptyProviderOption="Active provider"
+ emptyModelOption="Default model"
+ alwaysShowModel
+ compact
+ label={label}
+ loading={loading}
+ disabled={disabled}
+ />
+ );
+}
diff --git a/client/src/components/decks/DeckRenderControls.jsx b/client/src/components/decks/DeckRenderControls.jsx
new file mode 100644
index 0000000000..7723193dd1
--- /dev/null
+++ b/client/src/components/decks/DeckRenderControls.jsx
@@ -0,0 +1,94 @@
+import { Loader2, Play, Sparkles, WandSparkles } from 'lucide-react';
+import RecordRenderPinRow from '../imageGen/RecordRenderPinRow';
+import DeckLlmPinPicker from './DeckLlmPinPicker';
+import useImageRenderSettings from '../../hooks/useImageRenderSettings';
+import { RENDER_TARGET, modeLabel } from '../../lib/imageGenBackends';
+
+/**
+ * The action bar above the card grid: which image backend this deck renders
+ * on (its own pin over the Settings "Deck card renders" default), the LLM pin
+ * for casting + prompt writing, and the three batch buttons — generate
+ * prompts for empty cards, render every card still missing an image, render
+ * the whole deck again.
+ */
+export default function DeckRenderControls({
+ deck, completion, onPatch, onGeneratePrompts, onRenderMissing, onRenderAll, generating = false, rendering = false,
+}) {
+ const { imageCfg, backends } = useImageRenderSettings({ record: deck, target: RENDER_TARGET.DECK });
+ const missing = Math.max(0, (completion?.total || 0) - (completion?.rendered || 0) - (completion?.inFlight || 0));
+ const unprompted = Math.max(0, (completion?.total || 0) - (completion?.prompted || 0));
+ const busy = generating || rendering;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-md p-3 space-y-3">
+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2 lg:items-start">
+ <div className="space-y-1">
+ <RecordRenderPinRow
+ idPrefix="deck-render"
+ label="Image backend"
+ imageMode={deck.imageMode}
+ imageModelId={deck.imageModelId}
+ onChange={(pin) => onPatch(pin)}
+ options={backends.length ? backends.map((b) => ({ id: b.id, label: b.label })) : null}
+ autoLabel="Auto (Settings default)"
+ />
+ {backends.length ? (
+ <p className="text-[11px] text-gray-500">
+ Renders on <span className="text-gray-300">{modeLabel(imageCfg.mode)}</span>
+ {imageCfg.cloudModel || imageCfg.modelId ? <> · <span className="text-gray-300">{imageCfg.cloudModel || imageCfg.modelId}</span></> : null}
+ {' '}at {deck.cardSize?.width}×{deck.cardSize?.height}
+ </p>
+ ) : null}
+ </div>
+ <DeckLlmPinPicker
+ label="Prompt model"
+ pin={deck.promptLlm}
+ onChange={(pin) => onPatch({ promptLlm: pin })}
+ disabled={busy}
+ />
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => onGeneratePrompts({ overwrite: false })}
+ disabled={busy || unprompted === 0}
+ title={unprompted === 0 ? 'Every card already has a prompt' : `Write prompts for ${unprompted} card(s) without one`}
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" aria-hidden="true" /> : <WandSparkles size={14} aria-hidden="true" />}
+ {generating ? 'Writing prompts…' : `Generate prompts${unprompted ? ` (${unprompted})` : ''}`}
+ </button>
+ <button
+ type="button"
+ onClick={() => onGeneratePrompts({ overwrite: true })}
+ disabled={busy}
+ title="Rewrite every card's prompt (keeps the universe casting)"
+ className="min-h-[38px] rounded border border-port-border px-3 py-2 text-sm text-gray-200 hover:bg-white/5 disabled:opacity-50"
+ >
+ Rewrite all prompts
+ </button>
+ <span className="hidden sm:block h-6 w-px bg-port-border" aria-hidden="true" />
+ <button
+ type="button"
+ onClick={onRenderMissing}
+ disabled={busy || missing === 0 || !completion?.prompted}
+ title={missing === 0 ? 'Every card is rendered' : `Render the ${missing} card(s) without an image`}
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-accent/40 px-3 py-2 text-sm text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ {rendering ? <Loader2 size={14} className="animate-spin" aria-hidden="true" /> : <Play size={14} aria-hidden="true" />}
+ Render missing{missing ? ` (${missing})` : ''}
+ </button>
+ <button
+ type="button"
+ onClick={onRenderAll}
+ disabled={busy || !completion?.prompted}
+ title="Queue a fresh render for every card with a prompt"
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-border px-3 py-2 text-sm text-gray-200 hover:bg-white/5 disabled:opacity-50"
+ >
+ <Sparkles size={14} aria-hidden="true" />
+ Render whole deck
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/decks/DeckSampleModal.jsx b/client/src/components/decks/DeckSampleModal.jsx
new file mode 100644
index 0000000000..041332f280
--- /dev/null
+++ b/client/src/components/decks/DeckSampleModal.jsx
@@ -0,0 +1,164 @@
+import { useState } from 'react';
+import { ImagePlus, Loader2, Sparkles, X } from 'lucide-react';
+import Modal from '../ui/Modal';
+import toast from '../ui/Toast';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import VisionProviderPicker from '../universe/VisionProviderPicker';
+import StyleDiffPreview from '../universeBuilder/StyleDiffPreview';
+import { addDeckSample, analyzeDeckSample } from '../../services/api';
+
+const TITLE_MAX = 120;
+
+/**
+ * "Add sample design" flow: choose or upload a gallery image (a poster, another
+ * card, a painting), analyze it with a vision model into a proposed deck style
+ * guide, review the diff, then persist the sample alone or adopt the proposal
+ * with it. Mirrors the universe art-style reference modal.
+ */
+export default function DeckSampleModal({ deck, open, onClose, onSaved }) {
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [image, setImage] = useState(null);
+ const [title, setTitle] = useState('');
+ const [vision, setVision] = useState({ providerId: '', model: '' });
+ const [analysis, setAnalysis] = useState(null);
+ const [analyzing, setAnalyzing] = useState(false);
+ const [persisting, setPersisting] = useState(false);
+
+ const reset = () => { setImage(null); setTitle(''); setAnalysis(null); };
+ const close = () => {
+ if (analyzing || persisting) return;
+ onClose?.();
+ reset();
+ };
+
+ const analyze = async () => {
+ if (!image?.filename || !vision.model) return;
+ setAnalyzing(true);
+ const result = await analyzeDeckSample(deck.id, {
+ image: image.filename,
+ title: title.trim() || undefined,
+ providerId: vision.providerId || undefined,
+ model: vision.model,
+ }, { silent: true }).catch((error) => {
+ toast.error(`Sample analysis failed: ${error.message}`);
+ return null;
+ });
+ setAnalyzing(false);
+ if (!result) return;
+ setAnalysis(result);
+ setTitle(result.sample?.title || '');
+ };
+
+ const persist = async (adopt) => {
+ if (!analysis || !title.trim()) return;
+ setPersisting(true);
+ const next = await addDeckSample(deck.id, {
+ sample: { ...analysis.sample, title: title.trim() },
+ adopt: adopt ? analysis.proposed : undefined,
+ }, { silent: true }).catch((error) => {
+ toast.error(`Failed to save sample: ${error.message}`);
+ return null;
+ });
+ setPersisting(false);
+ if (!next) return;
+ toast.success(adopt ? 'Style guide adopted from sample' : 'Sample added');
+ onSaved?.(next);
+ onClose?.();
+ reset();
+ };
+
+ const layoutDiff = analysis?.diff?.layoutPrompt;
+
+ return (
+ <>
+ <Modal
+ open={open}
+ onClose={close}
+ size="2xl"
+ closeOnBackdrop={!analyzing && !persisting}
+ usePortal
+ panelClassName="bg-port-card border border-port-border rounded-xl"
+ ariaLabel="Add a sample design"
+ >
+ <div className="p-4 space-y-4">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <h2 className="text-base font-semibold text-white">Add sample design</h2>
+ <p className="text-xs text-gray-500">A poster, another card, a painting — anything whose visual language this deck should share.</p>
+ </div>
+ <button type="button" onClick={close} disabled={analyzing || persisting} className="p-1 text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center" aria-label="Close">
+ <X size={18} />
+ </button>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4">
+ <div>
+ {image ? (
+ <button type="button" onClick={() => { setImage(null); setAnalysis(null); }} className="block w-full" title="Choose another image">
+ <img src={image.preview || `/data/images/${encodeURIComponent(image.filename)}`} alt="Selected sample design" className="aspect-[2/3] w-full rounded-lg border border-port-border object-cover" />
+ </button>
+ ) : (
+ <button type="button" onClick={() => setGalleryOpen(true)} className="flex aspect-[2/3] w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-port-border text-xs text-gray-400 hover:border-port-accent hover:text-white">
+ <ImagePlus size={24} />
+ Upload or choose image
+ </button>
+ )}
+ </div>
+ <div className="space-y-3">
+ <div>
+ <label htmlFor="deck-sample-title" className="mb-1 block text-xs text-gray-400">Title (optional before analysis)</label>
+ <input id="deck-sample-title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={TITLE_MAX} placeholder="Generated from the image when blank" className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none" />
+ </div>
+ <VisionProviderPicker label="Vision model for sample analysis" onChange={setVision} />
+ {analysis?.sample?.prompt ? (
+ <div>
+ <div className="text-xs text-gray-400 mb-1">Recreation prompt</div>
+ <p className="text-xs text-gray-300 max-h-32 overflow-y-auto rounded border border-port-border bg-port-bg/60 p-2">{analysis.sample.prompt}</p>
+ </div>
+ ) : null}
+ </div>
+ </div>
+
+ <StyleDiffPreview analysis={analysis} description="Review before deciding whether the sample should update the deck's style guide." />
+ {layoutDiff?.changed ? (
+ <section className="rounded-lg border border-port-border bg-port-bg/60 p-3 space-y-1">
+ <h3 className="text-sm font-medium text-white">Card layout</h3>
+ <p className="text-xs text-gray-500 line-through">{layoutDiff.before || 'None'}</p>
+ <p className="text-xs text-gray-200">{layoutDiff.after}</p>
+ </section>
+ ) : null}
+
+ <div className="flex items-center justify-end gap-2 flex-wrap">
+ <button type="button" onClick={close} disabled={analyzing || persisting} className="min-h-[38px] px-3 text-sm text-gray-400 hover:text-white disabled:opacity-50">Cancel</button>
+ {!analysis ? (
+ <button type="button" onClick={analyze} disabled={analyzing || !image?.filename || !vision.model} className="inline-flex min-h-[38px] items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">
+ {analyzing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {analyzing ? 'Analyzing…' : 'Analyze sample'}
+ </button>
+ ) : (
+ <>
+ <button type="button" onClick={() => persist(false)} disabled={persisting || !title.trim()} className="min-h-[38px] rounded border border-port-border px-3 py-2 text-sm text-gray-200 hover:bg-white/5 disabled:opacity-50">
+ Add sample only
+ </button>
+ <button type="button" onClick={() => persist(true)} disabled={persisting || !title.trim()} className="inline-flex min-h-[38px] items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">
+ {persisting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ Adopt style + add
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ </Modal>
+ <GalleryImagePicker
+ open={galleryOpen}
+ onClose={() => setGalleryOpen(false)}
+ allowUpload
+ onSelect={(item) => {
+ if (!item?.filename) return;
+ setImage({ filename: item.filename, preview: item.previewUrl });
+ setAnalysis(null);
+ }}
+ />
+ </>
+ );
+}
diff --git a/client/src/components/decks/DeckStylePanel.jsx b/client/src/components/decks/DeckStylePanel.jsx
new file mode 100644
index 0000000000..af2bcbb76a
--- /dev/null
+++ b/client/src/components/decks/DeckStylePanel.jsx
@@ -0,0 +1,120 @@
+import { useState } from 'react';
+import { ImagePlus, Trash2 } from 'lucide-react';
+import InfluenceChipsInput from '../universeBuilder/InfluenceChipsInput';
+import DeckSampleModal from './DeckSampleModal';
+import useFieldDraft from '../../hooks/useFieldDraft';
+import { DECK_KIND_LABELS } from '../../lib/decks';
+
+const INPUT_CLASS = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
+
+/**
+ * Style tab: the deck's style guide (notes + embrace/avoid influences + the
+ * shared card layout clause), its sample designs, and the universe link.
+ * Text fields buffer locally and PATCH on blur; chips PATCH on change.
+ */
+export default function DeckStylePanel({ deck, universes, onPatch, onDeckReplaced, onRemoveSample }) {
+ const [sampleOpen, setSampleOpen] = useState(false);
+ const description = useFieldDraft(deck.description, (v) => onPatch({ description: v }));
+ const styleNotes = useFieldDraft(deck.styleNotes, (v) => onPatch({ styleNotes: v }));
+ const layoutPrompt = useFieldDraft(deck.layoutPrompt, (v) => onPatch({ layoutPrompt: v }));
+ const influences = deck.influences || { embrace: [], avoid: [] };
+ const samples = Array.isArray(deck.samples) ? deck.samples : [];
+
+ return (
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <section className="space-y-3 bg-port-card border border-port-border rounded-md p-3">
+ <h2 className="text-sm font-medium text-white">Style guide</h2>
+ <div>
+ <label htmlFor="deck-description" className="block text-xs text-gray-400 mb-1">Concept</label>
+ <textarea id="deck-description" rows={2} value={description.value} onChange={description.onChange} onBlur={description.onBlur} placeholder="What this deck is about — its world, its mood, who it is for." className={INPUT_CLASS} />
+ </div>
+ <div>
+ <label htmlFor="deck-style-notes" className="block text-xs text-gray-400 mb-1">Art direction</label>
+ <textarea id="deck-style-notes" rows={4} value={styleNotes.value} onChange={styleNotes.onChange} onBlur={styleNotes.onBlur} placeholder="Medium, palette, ornament, era, mood — prose the prompt writer reads." className={INPUT_CLASS} />
+ </div>
+ <div>
+ <div className="text-xs text-gray-400 mb-1">Style prompt (prepended to every card render)</div>
+ <InfluenceChipsInput
+ tokens={influences.embrace}
+ onChange={(next) => onPatch({ influences: { ...influences, embrace: next } })}
+ placeholder="copperplate engraving, aged cream paper, teal and gold…"
+ ariaLabel="Add style prompt token"
+ tone="success"
+ />
+ </div>
+ <div>
+ <div className="text-xs text-gray-400 mb-1">Negative prompt</div>
+ <InfluenceChipsInput
+ tokens={influences.avoid}
+ onChange={(next) => onPatch({ influences: { ...influences, avoid: next } })}
+ placeholder="blurry, photographic, neon, watermark…"
+ ariaLabel="Add negative prompt token"
+ tone="error"
+ />
+ </div>
+ <div>
+ <label htmlFor="deck-layout-prompt" className="block text-xs text-gray-400 mb-1">Shared card layout ({DECK_KIND_LABELS[deck.kind] || deck.kind})</label>
+ <textarea id="deck-layout-prompt" rows={3} value={layoutPrompt.value} onChange={layoutPrompt.onChange} onBlur={layoutPrompt.onBlur} className={INPUT_CLASS} />
+ <p className="text-[11px] text-gray-500 mt-1">Sits between the style prompt and each card's subject so every card shares one border, index and title treatment.</p>
+ </div>
+ <div>
+ <label htmlFor="deck-universe" className="block text-xs text-gray-400 mb-1">Universe</label>
+ <select id="deck-universe" value={deck.universeId || ''} onChange={(e) => onPatch({ universeId: e.target.value || null })} className={INPUT_CLASS}>
+ <option value="">— none —</option>
+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ <p className="text-[11px] text-gray-500 mt-1">With a universe linked, "Generate prompts" first casts its characters, places and objects onto the cards.</p>
+ </div>
+ </section>
+
+ <section className="space-y-3 bg-port-card border border-port-border rounded-md p-3">
+ <div className="flex items-start justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-sm font-medium text-white">Sample designs</h2>
+ <p className="text-xs text-gray-500">Analyzed by a vision model into the style guide above.</p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setSampleOpen(true)}
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-accent/40 px-2.5 py-1.5 text-xs text-port-accent hover:bg-port-accent/10"
+ >
+ <ImagePlus size={14} aria-hidden="true" />
+ Add sample
+ </button>
+ </div>
+ {samples.length ? (
+ <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {samples.map((sample) => (
+ <li key={sample.id} className="flex gap-3 rounded-lg border border-port-border bg-port-bg/40 p-2">
+ <img
+ src={`/data/images/${encodeURIComponent(sample.imageRef || '')}`}
+ alt={sample.title}
+ className="h-24 w-16 shrink-0 rounded object-cover bg-port-bg"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-start justify-between gap-2">
+ <h3 className="text-sm font-medium text-white">{sample.title}</h3>
+ <button
+ type="button"
+ onClick={() => onRemoveSample(sample.id)}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center shrink-0 rounded p-1 text-gray-500 hover:bg-white/5 hover:text-port-error"
+ aria-label={`Remove ${sample.title}`}
+ title="Remove sample"
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
+ </div>
+ <p className="mt-1 line-clamp-4 text-xs text-gray-400">{sample.prompt}</p>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-gray-600">No samples yet. Add a poster, a card from another deck, or any image whose look this deck should share.</p>
+ )}
+ </section>
+
+ <DeckSampleModal deck={deck} open={sampleOpen} onClose={() => setSampleOpen(false)} onSaved={onDeckReplaced} />
+ </div>
+ );
+}
diff --git a/client/src/components/ui/Pill.jsx b/client/src/components/ui/Pill.jsx
index 99a5740d10..9e920d766d 100644
--- a/client/src/components/ui/Pill.jsx
+++ b/client/src/components/ui/Pill.jsx
@@ -32,6 +32,7 @@ const TONES = {
note: 'text-gray-500 bg-port-bg border-port-border italic',
context: 'text-gray-500 border-port-border uppercase tracking-wide',
success: 'text-port-success bg-port-success/10 border-port-success/20',
+ error: 'text-port-error bg-port-error/10 border-port-error/20',
warning: 'text-port-warning bg-port-warning/10 border-port-warning/20',
bare: '',
};
diff --git a/client/src/hooks/useImageRenderSettings.js b/client/src/hooks/useImageRenderSettings.js
index 52eb5e37df..feb265b262 100644
--- a/client/src/hooks/useImageRenderSettings.js
+++ b/client/src/hooks/useImageRenderSettings.js
@@ -23,7 +23,9 @@ import {
* @param {object} [opts]
* @param {object|null} [opts.record] - Record whose `imageMode`/`imageModelId` pin wins.
* @param {string|null} [opts.target] - RENDER_TARGET id whose `renderDefaults` pin is next.
- * @returns {{ imageCfg: object }}
+ * @returns {{ imageCfg: object, backends: Array<{id:string,label:string}> }} —
+ * `backends` is the enabled, non-external list the pin ladder was gated on
+ * (empty until settings land), for callers that also render a backend picker.
*/
export default function useImageRenderSettings({ record = null, target = null } = {}) {
// `null` = not fetched yet (or the fetch failed), which is NOT the same as a
@@ -43,13 +45,15 @@ export default function useImageRenderSettings({ record = null, target = null }
// a freshly-fetched draft object on every save, and re-deriving an identical
// cfg would churn the render opts for every consumer downstream.
return useMemo(() => {
- if (!settings) return { imageCfg: PIPELINE_IMAGE_DEFAULTS };
+ if (!settings) return { imageCfg: PIPELINE_IMAGE_DEFAULTS, backends: [] };
+ const backends = deriveAvailableBackends(settings, { excludeExternal: true });
return {
imageCfg: applyRecordRenderPin(
readPipelineImageSettings(settings),
[record, renderTargetPin(settings, target)],
- deriveAvailableBackends(settings, { excludeExternal: true }),
+ backends,
),
+ backends,
};
}, [settings, target, record?.imageMode, record?.imageModelId]);
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index ff92b27076..40bc633364 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -88,6 +88,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. |
| `imageGenBackends.js` | Icon metadata, `deriveAvailableBackends`, and `imageGenReadiness(status)` — a compatibility-safe `ready` / `unavailable` / `unknown` read of image-gen status responses; re-exports everything from `imageGenModes.js` so consumers keep one import site. |
| `imageGenModes.js` | Node-safe image/video backend constants + pure helpers. Re-exports the backend / render-target / lane alphabets from the server leaves `server/lib/generationModes.js` + `server/lib/renderTargets.js` (see its header for why nothing is copied); adds the Settings rows (`RENDER_TARGET_OPTIONS`), `applyRecordRenderPin` (fold a record's `imageMode`/`imageModelId` pin over a settings-derived cfg), `isCloudCliMode`/`isCloudVideoMode`, `modeLabel`, `mediaJobLane` (a projected media job's scheduler lane, re-derived for responses predating the server's `executionLane` field), and the cloud/model-override/i2i capability mirrors of the server service specs. Imported by the server-side parity suite — must stay importable without client packages. |
+| `decks.js` | Deck alphabet, card roster/status/completion rules and render-prompt composition — re-exported from `server/lib/deckTemplates.js` (one definition, no client copy). |
| `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. |
| `imageGenResolutions.js` | Shared resolution presets for image generation. |
| `imageTo3dReasons.js` | Client mirror of the image-to-3D unavailable-reason labels in `server/services/imageTo3d/targets.js`: `UNAVAILABLE_REASONS` (reason code → user-facing label), `UNAVAILABLE_REASON_FALLBACK`, and `unavailableReasonLabel(code, fallback?)`, plus `isTargetReady(target)` — the shared readiness predicate (`installed` is tri-state: `null` = a hosted lane with no install concept, ready as soon as it is available). Use these anywhere a target's `unavailableReason` or readiness is rendered — never re-declare the codes or re-derive readiness from `target.installed` truthiness. Parity + code coverage enforced by `server/services/imageTo3d/unavailableReasons.parity.test.js`. |
diff --git a/client/src/lib/decks.js b/client/src/lib/decks.js
new file mode 100644
index 0000000000..c158eea7db
--- /dev/null
+++ b/client/src/lib/decks.js
@@ -0,0 +1,16 @@
+// Decks — the deck alphabet, card status/completion rules and render-prompt
+// composition, re-exported from the server's pure leaf so the client never
+// carries a second copy of the roster or the completion math.
+export {
+ CARD_STATUS,
+ DECK_BACK_KEY,
+ DECK_CARD_SIZE,
+ DECK_KIND,
+ DECK_KINDS,
+ DECK_KIND_LABELS,
+ DEFAULT_LAYOUT_PROMPT,
+ cardInFlightJobId,
+ cardStatus,
+ composeCardRenderPrompt,
+ deckCompletion,
+} from '../../../server/lib/deckTemplates.js';
diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.js
index 9223ffa273..db2be51ee4 100644
--- a/client/src/lib/imageGenModes.js
+++ b/client/src/lib/imageGenModes.js
@@ -126,6 +126,7 @@ export const RENDER_TARGET_OPTIONS = Object.freeze([
{ id: RENDER_TARGET.MUSIC_VIDEO, label: 'Music Video scene frames & clips', video: true },
{ id: RENDER_TARGET.LORA_DATASET, label: 'LoRA training datasets' },
{ id: RENDER_TARGET.CREATIVE_AGENT, label: 'Creative agent renders', video: true },
+ { id: RENDER_TARGET.DECK, label: 'Deck card renders (playing cards & tarot)' },
]);
// True when a video backend renders in a provider's cloud rather than on the
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index a693d7d3bc..6f62834c89 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -7,6 +7,7 @@ export * from './publicGuestRoutes.js';
export * from './canonPrompt.js';
export * from './cleanPlatePrompt.js';
export * from './composeStyledPrompt.js';
+export * from './decks.js';
export * from './personaTraitBlend.js';
export * from './scenePrompt.js';
export * from './seasonStructure.js';
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index ea7c466bab..91900b58eb 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -24,6 +24,7 @@ import {
Film,
MessageSquare,
Palette,
+ Spade,
PenLine,
Sparkles,
Target,
@@ -172,6 +173,7 @@ export const NAV_PRESENTATION = {
'/game': { icon: Gamepad2 },
'/importer': { icon: FileInput },
'/media': { icon: Layers },
+ '/decks': { icon: Spade },
'/mood-boards': { icon: Palette },
'/music': { icon: Mic },
'/music-video': { icon: Music },
diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsx
new file mode 100644
index 0000000000..eee09bddf9
--- /dev/null
+++ b/client/src/pages/DeckDetail.jsx
@@ -0,0 +1,302 @@
+/**
+ * Deck editor — `/decks/:id`.
+ *
+ * Header (name, kind, universe, completion) → action bar (backend + LLM pins,
+ * generate prompts, render missing / all) → tabs: the card grid (one
+ * three-state slot per card, drawer per card) and the style guide + samples.
+ * Every card render rides the shared media queue; the server files a finished
+ * image onto the card, and the grid's live slots settle through
+ * `MediaJobThumb`. In-flight state lives on each card's `render` record —
+ * stamped optimistically when a render is queued, flipped when the slot
+ * settles — so a render started here or on a previous visit reads the same.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Link, useNavigate, useParams } from 'react-router';
+import { ArrowLeft, Globe, Trash2 } from 'lucide-react';
+import PageSkeleton from '../components/ui/PageSkeleton';
+import ProgressBar from '../components/ui/ProgressBar';
+import TabPills from '../components/ui/TabPills';
+import Pill from '../components/ui/Pill';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import EmptyState from '../components/EmptyState';
+import toast from '../components/ui/Toast';
+import MediaPreview from '../components/media/MediaPreview';
+import { normalizeImage } from '../components/media/normalize';
+import DeckCardGrid from '../components/decks/DeckCardGrid';
+import DeckCardDrawer from '../components/decks/DeckCardDrawer';
+import DeckStylePanel from '../components/decks/DeckStylePanel';
+import DeckRenderControls from '../components/decks/DeckRenderControls';
+import useMounted from '../hooks/useMounted';
+import useUrlParams from '../hooks/useUrlParams';
+import usePreviewRoute from '../hooks/usePreviewRoute';
+import useFieldDraft from '../hooks/useFieldDraft';
+import { DECK_KIND_LABELS, cardInFlightJobId, deckCompletion } from '../lib/decks';
+import {
+ deleteDeck, generateDeckPrompts, getDeck, listUniverseSummaries, removeDeckSample,
+ renderDeckCard, renderDeckCards, updateDeck, updateDeckCard,
+} from '../services/api';
+
+const TABS = [{ id: 'cards', label: 'Cards' }, { id: 'style', label: 'Style & samples' }];
+
+export default function DeckDetail() {
+ const { id } = useParams();
+ // Route changes replace the editor so every draft, drawer and pending-render
+ // map belongs to one deck.
+ return <DeckEditor key={id} id={id} />;
+}
+
+function DeckEditor({ id }) {
+ const navigate = useNavigate();
+ const mountedRef = useMounted();
+ const [params, updateParams] = useUrlParams();
+ const tab = TABS.some((t) => t.id === params.get('tab')) ? params.get('tab') : 'cards';
+ const cardParam = params.get('card');
+
+ const [deck, setDeck] = useState(null);
+ const [universes, setUniverses] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+ const [generating, setGenerating] = useState(false);
+ const [rendering, setRendering] = useState(false);
+ const [savingCard, setSavingCard] = useState(false);
+ const loadSeqRef = useRef(0);
+
+ const load = useCallback(async () => {
+ const seq = ++loadSeqRef.current;
+ setLoading(true);
+ const [data, worlds] = await Promise.all([
+ getDeck(id, { silent: true }).catch(() => null),
+ listUniverseSummaries({ silent: true }).catch(() => []),
+ ]);
+ if (!mountedRef.current || seq !== loadSeqRef.current) return;
+ setDeck(data);
+ setUniverses(Array.isArray(worlds) ? worlds : []);
+ if (!data) toast.error('Deck not found');
+ setLoading(false);
+ }, [id, mountedRef]);
+
+ useEffect(() => { load(); }, [load]);
+
+ // Merge a patch into one card of the local deck.
+ const patchLocalCard = useCallback((cardId, patch) => {
+ setDeck((prev) => (prev ? {
+ ...prev,
+ cards: prev.cards.map((c) => (c.id === cardId ? { ...c, ...(typeof patch === 'function' ? patch(c) : patch) } : c)),
+ } : prev));
+ }, []);
+
+ const patchDeck = useCallback(async (patch) => {
+ const next = await updateDeck(id, patch, { silent: true }).catch((err) => {
+ toast.error(`Save failed: ${err.message}`);
+ return null;
+ });
+ if (next && mountedRef.current) setDeck(next);
+ return !!next;
+ }, [id, mountedRef]);
+
+ const nameDraft = useFieldDraft(deck?.name, (v) => { if (v.trim()) patchDeck({ name: v.trim() }); });
+
+ const completion = useMemo(() => (deck ? deckCompletion(deck.cards) : null), [deck]);
+ const selectedCard = useMemo(
+ () => (deck && cardParam ? deck.cards.find((c) => c.id === cardParam) || null : null),
+ [deck, cardParam],
+ );
+ const previewItems = useMemo(() => (deck
+ ? deck.cards.flatMap((c) => c.imageRefs.map((filename) => normalizeImage({ filename, path: `/data/images/${filename}`, prompt: c.prompt })))
+ : []), [deck]);
+ const [preview, setPreview] = usePreviewRoute(previewItems);
+ const previewFilename = (filename) => {
+ const item = previewItems.find((i) => i.filename === filename);
+ if (item) setPreview(item);
+ };
+
+ const openCard = (card) => updateParams({ card: card.id });
+ const closeCard = () => updateParams({ card: null });
+
+ // Stamp the queued jobs onto their cards, mirroring what the server wrote.
+ const queueJobs = (result) => {
+ const byCard = new Map(result.jobs.map((j) => [j.cardId, j.jobId]));
+ setDeck((prev) => (prev ? {
+ ...prev,
+ cards: prev.cards.map((c) => (byCard.has(c.id) ? { ...c, render: { jobId: byCard.get(c.id), status: 'queued', mode: result.mode } } : c)),
+ } : prev));
+ };
+
+ const renderCard = async (card) => {
+ const result = await renderDeckCard(id, card.id, {}, { silent: true }).catch((err) => {
+ toast.error(`Render failed to queue: ${err.message}`);
+ return null;
+ });
+ if (result && mountedRef.current) queueJobs(result);
+ };
+
+ const renderBatch = async (body, label) => {
+ setRendering(true);
+ const result = await renderDeckCards(id, body, { silent: true }).catch((err) => {
+ toast.error(`${label} failed: ${err.message}`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setRendering(false);
+ if (!result) return;
+ queueJobs(result);
+ toast.success(`${result.jobs.length} card render${result.jobs.length === 1 ? '' : 's'} queued`);
+ };
+
+ const generatePrompts = async ({ overwrite }) => {
+ setGenerating(true);
+ const result = await generateDeckPrompts(id, { overwrite }, { silent: true }).catch((err) => {
+ toast.error(`Prompt generation failed: ${err.message}`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setGenerating(false);
+ if (!result) return;
+ setDeck(result.deck);
+ toast.success(`${result.written} prompt${result.written === 1 ? '' : 's'} written${result.cast ? `, ${result.cast} cards cast from the universe` : ''}`);
+ };
+
+ const saveCard = async (patch) => {
+ if (!selectedCard) return;
+ setSavingCard(true);
+ const card = await updateDeckCard(id, selectedCard.id, patch, { silent: true }).catch((err) => {
+ toast.error(`Card save failed: ${err.message}`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setSavingCard(false);
+ if (card) patchLocalCard(card.id, card);
+ };
+
+ // The slot settled with a file — the same merge the server hook performs.
+ const onRenderComplete = useCallback((cardId, filename) => {
+ if (!filename) return;
+ patchLocalCard(cardId, (c) => ({
+ imageRefs: [...c.imageRefs.filter((f) => f !== filename), filename],
+ primaryImageRef: filename,
+ render: { ...(c.render || {}), status: 'completed', filename },
+ }));
+ }, [patchLocalCard]);
+
+ const onRenderTerminal = useCallback((cardId, status) => {
+ patchLocalCard(cardId, (c) => ({ render: { ...(c.render || {}), status } }));
+ }, [patchLocalCard]);
+
+ const handleDelete = async () => {
+ setConfirmingDelete(false);
+ const ok = await deleteDeck(id, { silent: true }).then(() => true).catch(() => false);
+ if (!ok) { toast.error('Failed to delete deck'); return; }
+ toast.success('Deck deleted');
+ navigate('/decks');
+ };
+
+ const handleRemoveSample = async (sampleId) => {
+ const next = await removeDeckSample(id, sampleId, { silent: true }).catch(() => null);
+ if (next && mountedRef.current) setDeck(next);
+ else if (mountedRef.current) toast.error('Failed to remove sample');
+ };
+
+ if (loading) return <PageSkeleton header="none" label="Loading deck" cards={4} sidebar={false} />;
+ if (!deck) {
+ return (
+ <EmptyState title="Deck not found" message="This deck may have been deleted." actionTo="/decks" actionLabel="Back to decks" />
+ );
+ }
+
+ const universe = universes.find((u) => u.id === deck.universeId) || null;
+
+ return (
+ <div className="max-w-7xl mx-auto space-y-4">
+ <div className="flex items-start gap-3 flex-wrap">
+ <Link to="/decks" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-gray-400 hover:text-white" aria-label="Back to decks">
+ <ArrowLeft className="w-5 h-5" aria-hidden="true" />
+ </Link>
+ <div className="flex-1 min-w-[240px] space-y-1">
+ <h1 className="sr-only">{deck.name}</h1>
+ <label htmlFor="deck-name" className="sr-only">Deck name</label>
+ <input
+ id="deck-name"
+ value={nameDraft.value}
+ onChange={nameDraft.onChange}
+ onBlur={nameDraft.onBlur}
+ maxLength={120}
+ className="w-full bg-transparent text-xl font-semibold text-white border-b border-transparent hover:border-port-border focus:border-port-accent focus:outline-none"
+ />
+ <div className="flex items-center gap-3 text-xs text-gray-400 flex-wrap">
+ <Pill tone="context" size="xs">{DECK_KIND_LABELS[deck.kind] || deck.kind}</Pill>
+ {universe ? (
+ <Link to={`/universes/${universe.id}`} className="inline-flex items-center gap-1 hover:text-white"><Globe className="w-3 h-3" aria-hidden="true" />{universe.name}</Link>
+ ) : null}
+ <span>{completion.rendered}/{completion.total} rendered · {completion.prompted} prompted{completion.inFlight ? ` · ${completion.inFlight} rendering` : ''}{completion.failed ? ` · ${completion.failed} failed` : ''}</span>
+ </div>
+ <div className="max-w-md">
+ <ProgressBar percent={completion.percent} label="Deck render progress" tone={completion.percent === 100 ? 'success' : 'accent'} />
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setConfirmingDelete(true)}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-gray-500 hover:text-port-error"
+ aria-label={`Delete ${deck.name}`}
+ title="Delete deck"
+ >
+ <Trash2 className="w-4 h-4" aria-hidden="true" />
+ </button>
+ </div>
+ {confirmingDelete ? (
+ <InlineConfirmRow
+ question={`Delete "${deck.name}"? Its cards and prompts are removed; rendered images stay in the gallery.`}
+ onConfirm={handleDelete}
+ onCancel={() => setConfirmingDelete(false)}
+ />
+ ) : null}
+
+ <DeckRenderControls
+ deck={deck}
+ completion={completion}
+ onPatch={patchDeck}
+ onGeneratePrompts={generatePrompts}
+ onRenderMissing={() => renderBatch({ onlyMissing: true }, 'Render missing')}
+ onRenderAll={() => renderBatch({}, 'Render whole deck')}
+ generating={generating}
+ rendering={rendering}
+ />
+
+ <TabPills tabs={TABS} activeTab={tab} onChange={(next) => updateParams({ tab: next === 'cards' ? null : next })} ariaLabel="Deck sections" />
+
+ {tab === 'style' ? (
+ <DeckStylePanel
+ deck={deck}
+ universes={universes}
+ onPatch={patchDeck}
+ onDeckReplaced={setDeck}
+ onRemoveSample={handleRemoveSample}
+ />
+ ) : (
+ <DeckCardGrid
+ deck={deck}
+ onOpenCard={openCard}
+ onRenderCard={renderCard}
+ onPreview={(card) => previewFilename(card.primaryImageRef || card.imageRefs.at(-1))}
+ onRenderComplete={onRenderComplete}
+ onRenderTerminal={onRenderTerminal}
+ />
+ )}
+
+ <DeckCardDrawer
+ deck={deck}
+ card={selectedCard}
+ open={!!selectedCard}
+ inFlight={selectedCard ? cardInFlightJobId(selectedCard) : null}
+ saving={savingCard}
+ onClose={closeCard}
+ onSave={saveCard}
+ onRender={() => selectedCard && renderCard(selectedCard)}
+ onPreview={previewFilename}
+ />
+
+ <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />
+ </div>
+ );
+}
diff --git a/client/src/pages/Decks.jsx b/client/src/pages/Decks.jsx
new file mode 100644
index 0000000000..5b445e1fe2
--- /dev/null
+++ b/client/src/pages/Decks.jsx
@@ -0,0 +1,180 @@
+/**
+ * Decks page — deck index (Create → Decks).
+ *
+ * Lists every card deck (playing cards or tarot) with its render completion,
+ * and creates a new one: name, kind, and an optional universe link whose cast,
+ * places and objects the casting pass places onto the cards. The editor lives
+ * at `/decks/:id`. Mirrors the Mood Boards index.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { Link, useNavigate } from 'react-router';
+import { Globe, Plus, Spade, Trash2 } from 'lucide-react';
+import PageSkeleton from '../components/ui/PageSkeleton';
+import ProgressBar from '../components/ui/ProgressBar';
+import toast from '../components/ui/Toast';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import EmptyState from '../components/EmptyState';
+import { timeAgo } from '../utils/formatters';
+import { DECK_KIND, DECK_KINDS, DECK_KIND_LABELS } from '../lib/decks';
+import Pill from '../components/ui/Pill';
+import { createDeck, deleteDeck, listDecks, listUniverseSummaries } from '../services/api';
+
+const INPUT_CLASS = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
+
+export default function Decks() {
+ const navigate = useNavigate();
+ const [decks, setDecks] = useState([]);
+ const [universes, setUniverses] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [confirmingId, setConfirmingId] = useState(null);
+ const [name, setName] = useState('');
+ const [kind, setKind] = useState(DECK_KIND.TAROT);
+ const [universeId, setUniverseId] = useState('');
+ const [seedStyle, setSeedStyle] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const [rows, worlds] = await Promise.all([
+ listDecks({ silent: true }).catch(() => null),
+ listUniverseSummaries({ silent: true }).catch(() => []),
+ ]);
+ if (rows) setDecks(Array.isArray(rows) ? rows : []);
+ else toast.error('Failed to load decks');
+ setUniverses(Array.isArray(worlds) ? worlds : []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const handleCreate = async (event) => {
+ event.preventDefault();
+ if (creating || !name.trim()) return;
+ setCreating(true);
+ const deck = await createDeck({
+ name: name.trim(),
+ kind,
+ universeId: universeId || null,
+ seedStyleFromUniverse: seedStyle,
+ }, { silent: true }).catch((err) => { toast.error(`Failed to create deck: ${err.message}`); return null; });
+ setCreating(false);
+ if (!deck) return;
+ navigate(`/decks/${deck.id}`);
+ };
+
+ const handleDelete = async (id) => {
+ setConfirmingId(null);
+ const ok = await deleteDeck(id, { silent: true }).then(() => true).catch(() => false);
+ if (!ok) { toast.error('Failed to delete deck'); return; }
+ setDecks((prev) => prev.filter((d) => d.id !== id));
+ toast.success('Deck deleted');
+ };
+
+ const universeName = (id) => universes.find((u) => u.id === id)?.name || null;
+
+ return (
+ <div className="max-w-5xl mx-auto">
+ <div className="flex items-center gap-2 mb-4">
+ <Spade className="w-6 h-6 text-port-accent" aria-hidden="true" />
+ <h1 className="text-xl font-semibold text-white">Decks</h1>
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ Design a deck of playing cards or tarot cards: analyze a sample design into a style guide, write or generate a prompt per card, and render single cards or the whole deck with any image backend.
+ </p>
+
+ <form onSubmit={handleCreate} className="bg-port-card border border-port-border rounded-md p-3 mb-5 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-[1fr_160px_1fr_auto] lg:items-end">
+ <div>
+ <label htmlFor="deck-new-name" className="block text-xs text-gray-400 mb-1">Deck name</label>
+ <input id="deck-new-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={120} placeholder="Swarm Safe" className={INPUT_CLASS} />
+ </div>
+ <div>
+ <label htmlFor="deck-new-kind" className="block text-xs text-gray-400 mb-1">Kind</label>
+ <select id="deck-new-kind" value={kind} onChange={(e) => setKind(e.target.value)} className={INPUT_CLASS}>
+ {DECK_KINDS.map((k) => <option key={k} value={k}>{DECK_KIND_LABELS[k]}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="deck-new-universe" className="block text-xs text-gray-400 mb-1">Universe (optional)</label>
+ <select id="deck-new-universe" value={universeId} onChange={(e) => setUniverseId(e.target.value)} className={INPUT_CLASS}>
+ <option value="">— none —</option>
+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ {universeId ? (
+ <label htmlFor="deck-new-seed" className="mt-1.5 flex items-center gap-2 text-xs text-gray-400">
+ <input id="deck-new-seed" type="checkbox" checked={seedStyle} onChange={(e) => setSeedStyle(e.target.checked)} />
+ Seed the style guide from this universe
+ </label>
+ ) : null}
+ </div>
+ <button
+ type="submit"
+ disabled={creating || !name.trim()}
+ className="flex min-h-[44px] items-center justify-center gap-1.5 px-3 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ >
+ <Plus className="w-4 h-4" aria-hidden="true" />
+ New Deck
+ </button>
+ </form>
+
+ {loading ? (
+ <PageSkeleton header="none" label="Loading decks" cards={3} sidebar={false} />
+ ) : decks.length === 0 ? (
+ <EmptyState
+ icon={Spade}
+ title="No decks yet"
+ message="Name a deck above, pick playing cards or tarot, and optionally link a universe so its cast lands on the cards."
+ />
+ ) : (
+ <ul className="space-y-2">
+ {decks.map((deck) => {
+ const c = deck.completion || {};
+ const linked = universeName(deck.universeId);
+ return (
+ <li key={deck.id} className="bg-port-card border border-port-border rounded-md overflow-hidden">
+ {confirmingId === deck.id ? (
+ <InlineConfirmRow
+ variant="separator"
+ question={`Delete "${deck.name}"? Its cards and prompts are removed; rendered images stay in the gallery.`}
+ onConfirm={() => handleDelete(deck.id)}
+ onCancel={() => setConfirmingId(null)}
+ />
+ ) : null}
+ <div className="flex items-center gap-3 p-3">
+ <Link to={`/decks/${deck.id}`} className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-white font-medium truncate">{deck.name}</span>
+ <Pill tone="context" size="xs">{DECK_KIND_LABELS[deck.kind] || deck.kind}</Pill>
+ {linked ? (
+ <span className="inline-flex items-center gap-1 text-xs text-gray-400"><Globe className="w-3 h-3" aria-hidden="true" />{linked}</span>
+ ) : null}
+ </div>
+ <div className="mt-2 max-w-md">
+ <ProgressBar percent={c.percent || 0} label={`${deck.name} render progress`} tone={c.percent === 100 ? 'success' : 'accent'} />
+ </div>
+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-500 flex-wrap">
+ <span>{c.rendered ?? 0}/{c.total ?? 0} rendered</span>
+ <span>{c.prompted ?? 0} prompted</span>
+ {c.inFlight ? <span className="text-port-accent">{c.inFlight} rendering</span> : null}
+ {c.failed ? <span className="text-port-error">{c.failed} failed</span> : null}
+ <span>· {timeAgo(deck.updatedAt)}</span>
+ </div>
+ </Link>
+ <button
+ type="button"
+ onClick={() => setConfirmingId(deck.id)}
+ title="Delete deck"
+ aria-label={`Delete ${deck.name}`}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-500 hover:text-port-error transition-colors"
+ >
+ <Trash2 className="w-4 h-4" aria-hidden="true" />
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 27dc659352..976c3d7eab 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -104,6 +104,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel + status), character→LoRA link lookup. |
| `apiMedia.js` | Screenshots + media assets. Also owns the multi-file upload orchestration — `processScreenshotUploads` / `processAttachmentUploads` — moved from `utils/fileUpload.js` since they perform network I/O, not pure transforms. `utils/fileUpload.js` keeps only the pure helpers/constants and no longer re-exports these. |
| `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). |
+| `apiDecks.js` | Decks (playing-card / tarot designer) — deck + card CRUD, sample-design style analysis, universe casting + prompt generation, single/batch card renders. |
| `apiCreativeDirector.js` | Creative Director (video production). |
| `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). |
| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, AI authoring lanes, and the bounded editorial/playthrough autopilot lifecycle. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 9f8cc46366..6254ac01ce 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -84,6 +84,7 @@ export * from './apiContinuousVideo.js';
export * from './apiSprites.js';
export * from './apiShell.js';
export * from './apiMoodBoard.js';
+export * from './apiDecks.js';
export * from './apiThreejsModels.js';
export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
diff --git a/client/src/services/apiDecks.js b/client/src/services/apiDecks.js
new file mode 100644
index 0000000000..fab8b4d50e
--- /dev/null
+++ b/client/src/services/apiDecks.js
@@ -0,0 +1,50 @@
+import { request } from './apiCore.js';
+
+// Decks — playing-card / tarot deck designer (Create → Decks). Decks are
+// db-primary and machine-local; card images live in the shared gallery.
+// `options` is forwarded to the request helper so callers that own their own
+// error UI can pass `{ silent: true }`. Paths stay literal template strings so
+// the client↔server route-parity scan can resolve every call site.
+
+const json = (method, body) => ({ method, body: JSON.stringify(body ?? {}) });
+
+export const listDecks = (options) => request('/decks', options);
+
+export const getDeck = (id, options) => request(`/decks/${encodeURIComponent(id)}`, options);
+
+export const createDeck = (data, options) => request('/decks', { ...json('POST', data), ...options });
+
+export const updateDeck = (id, patch, options) =>
+ request(`/decks/${encodeURIComponent(id)}`, { ...json('PATCH', patch), ...options });
+
+export const deleteDeck = (id, options) =>
+ request(`/decks/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
+
+export const updateDeckCard = (id, cardId, patch, options) =>
+ request(`/decks/${encodeURIComponent(id)}/cards/${encodeURIComponent(cardId)}`, { ...json('PATCH', patch), ...options });
+
+// Stateless: returns `{ sample, proposed, diff, rationale, llm }` for review.
+export const analyzeDeckSample = (id, { image, title, providerId, model, effort } = {}, options) =>
+ request(`/decks/${encodeURIComponent(id)}/analyze-sample`, {
+ ...json('POST', { image, title, providerId, model, effort }), ...options,
+ });
+
+// Persist a reviewed sample; `adopt` applies the proposed style guide too.
+export const addDeckSample = (id, { sample, adopt } = {}, options) =>
+ request(`/decks/${encodeURIComponent(id)}/samples`, { ...json('POST', { sample, adopt }), ...options });
+
+export const removeDeckSample = (id, sampleId, options) =>
+ request(`/decks/${encodeURIComponent(id)}/samples/${encodeURIComponent(sampleId)}`, { method: 'DELETE', ...options });
+
+// Casting (universe-linked decks) + prompt writing. Returns
+// `{ deck, written, requested, cast, llm }`.
+export const generateDeckPrompts = (id, body = {}, options) =>
+ request(`/decks/${encodeURIComponent(id)}/generate-prompts`, { ...json('POST', body), ...options });
+
+// Batch render — `{ cardIds?, onlyMissing?, mode?, model?, seed? }` →
+// `{ mode, jobs: [{ cardId, key, jobId }], skipped }`.
+export const renderDeckCards = (id, body = {}, options) =>
+ request(`/decks/${encodeURIComponent(id)}/render`, { ...json('POST', body), ...options });
+
+export const renderDeckCard = (id, cardId, body = {}, options) =>
+ request(`/decks/${encodeURIComponent(id)}/cards/${encodeURIComponent(cardId)}/render`, { ...json('POST', body), ...options });
diff --git a/docs/API.md b/docs/API.md
index a8bd7d5938..713fa02493 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -615,6 +615,25 @@ return an `{ items, total }` envelope.
| POST | `/agents/tools/moltworld/say` | Send chat message |
| GET | `/agents/tools/moltworld/status` | Get world status |
+### Decks
+
+Playing-card / tarot deck designer (Create → Decks). Decks are db-primary and machine-local; card images live in the shared gallery and are referenced by filename.
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/decks` | List decks with render completion |
+| POST | `/decks` | Create a deck (`name`, `kind` = `playing` \| `tarot`, optional `universeId`, `seedStyleFromUniverse`); mints the full card roster |
+| GET | `/decks/:id` | Deck + cards + completion |
+| PATCH | `/decks/:id` | Style guide (`styleNotes`, `influences`, `layoutPrompt`), universe link, render pin (`imageMode`/`imageModelId`), LLM pins |
+| DELETE | `/decks/:id` | Delete the deck and its cards (gallery images are kept) |
+| PATCH | `/decks/:id/cards/:cardId` | Edit a card (`prompt`, `negativePrompt`, `primaryImageRef`, `imageRefs`, `canonRef`) |
+| POST | `/decks/:id/analyze-sample` | Stateless vision analysis of a gallery image → proposed style guide + diff |
+| POST | `/decks/:id/samples` | Persist a reviewed sample; `adopt` applies the proposal in the same write |
+| DELETE | `/decks/:id/samples/:sampleId` | Remove a sample |
+| POST | `/decks/:id/generate-prompts` | Cast a linked universe onto the cards, then write subject prompts (`cardIds`, `overwrite`, `cast`, provider/model/effort) |
+| POST | `/decks/:id/render` | Queue card renders through the media queue (`cardIds`, `onlyMissing`, `mode`, `model`, `seed`) |
+| POST | `/decks/:id/cards/:cardId/render` | Queue one card |
+
## Route Domain Index
Every mounted API prefix (see `server/index.js` for the authoritative list). Domains documented in detail above are omitted. Each prefix corresponds to a router in `server/routes/`.
@@ -689,6 +708,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/fableloom` | FableLoom interactive story generation |
| `/api/music-video` | Music video projects |
| `/api/mood-boards` | Mood boards |
+| `/api/decks` | Decks (playing-card / tarot designer) |
| `/api/writers-room` | Writers Room |
| `/api/universe-builder` | Universe Builder |
| `/api/authors`, `/api/artists`, `/api/albums`, `/api/tracks`, `/api/music` | Music/creator catalogs |
diff --git a/scripts/migrations/386-decks.js b/scripts/migrations/386-decks.js
new file mode 100644
index 0000000000..df21ef506b
--- /dev/null
+++ b/scripts/migrations/386-decks.js
@@ -0,0 +1,9 @@
+/** Decks (playing-card / tarot design projects) are db-primary. Idempotent DDL
+ * runs through ensureSchema at boot and ships in init-db.sql for fresh installs.
+ * No user data is seeded. */
+export default {
+ async up() {
+ console.log('🃏 Deck and deck-card tables are installed by ensureSchema at boot');
+ return { success: true };
+ },
+};
diff --git a/server/index.js b/server/index.js
index 652add72a8..69119a3009 100644
--- a/server/index.js
+++ b/server/index.js
@@ -138,6 +138,7 @@ import fableLoomRoutes from './routes/fableLoom.js';
import musicVideoRoutes from './routes/musicVideo.js';
import spriteRoutes from './routes/sprites.js';
import moodBoardRoutes from './routes/moodBoard.js';
+import deckRoutes from './routes/decks.js';
import threejsModelsRoutes from './routes/threejsModels.js';
import imageTo3dRoutes from './routes/imageTo3d.js';
import riggingRoutes from './routes/rigging.js';
@@ -408,6 +409,7 @@ app.use('/api/fableloom', fableLoomRoutes);
app.use('/api/music-video', musicVideoRoutes);
app.use('/api/sprites', spriteRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
+app.use('/api/decks', deckRoutes);
app.use('/api/threejs-models', threejsModelsRoutes);
app.use('/api/image-to-3d', imageTo3dRoutes);
app.use('/api/rigging', riggingRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index a65d6d052a..8198a52d92 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -646,3 +646,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation with deterministic latest-per-category selection across peers. |
| `mindToolRecipes.js` | Closed recipe schemas, current semantic-contract validation, and safe JSON field binding resolution. |
+| `deckTemplates.js` | Decks (playing cards / tarot): kind alphabet, per-kind card roster (`deckCardRoster`), shared layout clause, render prompt composition (`composeCardRenderPrompt`), per-card status and `deckCompletion`. Pure — re-exported by `client/src/lib/decks.js`. |
+| `deckValidation.js` | Zod schemas + limits for the `/api/decks` routes (create/update deck, card patch, sample analysis, prompt generation, render). |
diff --git a/server/lib/creativeLatitude.js b/server/lib/creativeLatitude.js
index 755cf82991..6a394d7c96 100644
--- a/server/lib/creativeLatitude.js
+++ b/server/lib/creativeLatitude.js
@@ -70,6 +70,7 @@ export function withCreativeLatitude(prompt) {
/** Prefixes whose stages/runs generate or edit creative work (story, art, canon). */
export const CREATIVE_PREFIXES = Object.freeze([
'cd-', // Creative Director: treatments, plans, scene evaluation
+ 'deck-', // Decks: sample-image style analysis, deck casting, card prompts
'fableloom-',
'importer-', // extracts canon/arcs out of existing (often licensed) source works
'media-prompt-', // image/video render-prompt refinement + reverse-engineering
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index d3800624a6..ea0e56d3eb 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -54,3 +54,4 @@ init-db.sql, each with a one-line reason.
`pool.query` in order.
| `mindToolRecipes.js` | `mindToolRecipesDdl`: machine-local recipe definitions and immutable revisions. |
+| `decks.js` | `decksDdl`: machine-local deck design projects (`decks`) and their per-card rows (`deck_cards`). |
diff --git a/server/lib/db/schema/decks.js b/server/lib/db/schema/decks.js
new file mode 100644
index 0000000000..909c6306fc
--- /dev/null
+++ b/server/lib/db/schema/decks.js
@@ -0,0 +1,27 @@
+// Decks (#decks): playing-card / tarot deck design projects. A deck row carries
+// the style guide + sample references + render pins in `definition`; each card
+// is its own row so a completed render attaches to ONE card without a
+// read-modify-write of the whole deck. Rendered bytes live in the shared
+// gallery (`data/images/`) and are referenced by filename from the card row.
+// Machine-local: decks never federate.
+export const decksDdl = [
+ `CREATE TABLE IF NOT EXISTS decks (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('playing', 'tarot')),
+ universe_id TEXT,
+ definition JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )`,
+ `CREATE TABLE IF NOT EXISTS deck_cards (
+ id UUID PRIMARY KEY,
+ deck_id UUID NOT NULL REFERENCES decks (id) ON DELETE CASCADE,
+ position INTEGER NOT NULL,
+ key TEXT NOT NULL,
+ definition JSONB NOT NULL DEFAULT '{}'::jsonb,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (deck_id, key)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_deck_cards_deck ON deck_cards (deck_id, position)`,
+];
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index d40ba1e45c..d7566bb9f8 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -31,6 +31,7 @@ import { privacyDdl } from './privacy.js';
import { stackerNewsDdl } from './stackerNews.js';
import { xDdl } from './x.js';
import { mindToolRecipesDdl } from './mindToolRecipes.js';
+import { decksDdl } from './decks.js';
import { beeperDdl } from './beeper.js';
import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';
@@ -55,6 +56,7 @@ export {
xDdl,
beeperDdl,
mindToolRecipesDdl,
+ decksDdl,
auditDdl,
auditedTables,
buildAuditTriggers,
@@ -95,6 +97,7 @@ export function buildCatalogDdl() {
...xDdl,
...beeperDdl,
...mindToolRecipesDdl,
+ ...decksDdl,
...auditDdl,
...buildAuditTriggers(),
];
diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.js
index eb413cd827..d0760d58d1 100644
--- a/server/lib/db/schema/schema.test.js
+++ b/server/lib/db/schema/schema.test.js
@@ -68,6 +68,7 @@ describe('db/schema barrel + composer (#2832)', () => {
...schema.xDdl,
...schema.beeperDdl,
...schema.mindToolRecipesDdl,
+ ...schema.decksDdl,
...schema.auditDdl,
...buildAuditTriggers(),
];
diff --git a/server/lib/deckTemplates.js b/server/lib/deckTemplates.js
new file mode 100644
index 0000000000..820732d80e
--- /dev/null
+++ b/server/lib/deckTemplates.js
@@ -0,0 +1,225 @@
+/**
+ * Decks — the pure, dependency-free half of the card-deck designer.
+ *
+ * Owns the deck alphabet (`playing` | `tarot`), the card roster each kind
+ * mints on creation, the layout clause each kind renders with, the render
+ * prompt composition (deck style → layout → card subject), and the completion
+ * math the index page and the detail header both show. Keeping this leaf
+ * import-free lets `client/src/lib/decks.js` re-export it verbatim, so the
+ * client never carries a second copy of the roster or the completion rule.
+ *
+ * Zod schemas for the routes live in `deckValidation.js`; DB access lives in
+ * `services/decks.js`.
+ */
+
+import { composeStyledPrompt } from './composeStyledPrompt.js';
+import { buildVisualStyleClause, universeVisualStyleTokens } from './universeVisualStyle.js';
+
+export const DECK_KIND = Object.freeze({ PLAYING: 'playing', TAROT: 'tarot' });
+export const DECK_KINDS = Object.freeze(Object.values(DECK_KIND));
+
+export const DECK_KIND_LABELS = Object.freeze({
+ [DECK_KIND.PLAYING]: 'Playing cards',
+ [DECK_KIND.TAROT]: 'Tarot',
+});
+
+// 2:3 portrait — the aspect every deck kind renders at, and the same frame the
+// universe canon thumbnails already assume, so a card slots into the shared
+// `EntryThumbSlot` without cropping.
+export const DECK_CARD_SIZE = Object.freeze({ width: 1024, height: 1536 });
+
+// The one card every deck has that is not a face: the shared back design.
+export const DECK_BACK_KEY = 'back';
+
+// Card render states derived from the persisted render record + image refs.
+export const CARD_STATUS = Object.freeze({
+ EMPTY: 'empty', // no prompt yet
+ PROMPTED: 'prompted', // prompt authored, nothing rendered
+ QUEUED: 'queued',
+ RUNNING: 'running',
+ RENDERED: 'rendered',
+ FAILED: 'failed',
+});
+
+// Per-kind layout clause. Every card of a deck shares it (editable on the deck)
+// so the whole set reads as ONE physical object — same border, same index
+// treatment — while the card prompt carries only the subject.
+export const DEFAULT_LAYOUT_PROMPT = Object.freeze({
+ [DECK_KIND.PLAYING]: 'Complete playing-card face, 2:3 portrait, ornate decorative border, the rank and suit index drawn in the top-left and bottom-right corners, symmetrical composition',
+ [DECK_KIND.TAROT]: 'Complete tarot card, 2:3 portrait, decorative framed border, the card title lettered in a banner along the bottom edge, symbolic centered composition',
+});
+
+const PLAYING_SUITS = Object.freeze([
+ { key: 'spades', name: 'Spades', symbol: '♠' },
+ { key: 'hearts', name: 'Hearts', symbol: '♥' },
+ { key: 'diamonds', name: 'Diamonds', symbol: '♦' },
+ { key: 'clubs', name: 'Clubs', symbol: '♣' },
+]);
+const PLAYING_RANKS = Object.freeze([
+ { key: 'A', name: 'Ace' }, { key: '2', name: 'Two' }, { key: '3', name: 'Three' },
+ { key: '4', name: 'Four' }, { key: '5', name: 'Five' }, { key: '6', name: 'Six' },
+ { key: '7', name: 'Seven' }, { key: '8', name: 'Eight' }, { key: '9', name: 'Nine' },
+ { key: '10', name: 'Ten' }, { key: 'J', name: 'Jack' }, { key: 'Q', name: 'Queen' },
+ { key: 'K', name: 'King' },
+]);
+
+// Major arcana with the traditional motif each card carries — the prompt
+// generator gets these as grounding so a deck stays recognizable as tarot even
+// when a universe's cast is placed on the cards.
+const MAJOR_ARCANA = Object.freeze([
+ ['The Fool', 'a carefree traveler stepping toward a cliff edge, a small dog at their heels, a white rose in hand'],
+ ['The Magician', 'a figure at a table bearing a cup, a sword, a wand and a coin, one hand raised to the sky, one pointing to the earth'],
+ ['The High Priestess', 'a seated veiled figure between two pillars, a crescent moon at their feet, a scroll in their lap'],
+ ['The Empress', 'a crowned figure enthroned in a lush field of grain and flowing water, a shield bearing a symbol of love'],
+ ['The Emperor', 'a stern crowned ruler on a stone throne carved with rams, a scepter in hand, mountains behind'],
+ ['The Hierophant', 'a robed teacher between two pillars, hand raised in blessing, two acolytes kneeling, crossed keys below'],
+ ['The Lovers', 'two figures beneath a radiant winged presence, a tree of flame and a tree of fruit, a mountain between'],
+ ['The Chariot', 'an armored figure standing in a chariot drawn by two sphinxes, one black and one white, a starry canopy above'],
+ ['Strength', 'a calm figure gently closing the jaws of a lion, an infinity sign above their head, a garland of flowers'],
+ ['The Hermit', 'a cloaked elder on a mountain peak holding a lantern with a six-pointed star, leaning on a staff'],
+ ['Wheel of Fortune', 'a great wheel inscribed with symbols, a sphinx atop it, creatures reading books in the four corners'],
+ ['Justice', 'a crowned figure enthroned holding an upright sword and a set of balanced scales, between two pillars'],
+ ['The Hanged Man', 'a serene figure suspended upside down by one foot from a living tree, a halo of light around the head'],
+ ['Death', 'an armored skeletal rider on a pale horse carrying a black banner with a white rose, a sunrise between two towers'],
+ ['Temperance', 'a winged figure with one foot in water and one on land, pouring water between two cups, a path to a distant crown of light'],
+ ['The Devil', 'a horned figure on a black pedestal, two chained figures below, an inverted five-pointed star, a raised torch'],
+ ['The Tower', 'a tower on a crag struck by lightning, its crown toppling, two figures falling, flames from the windows'],
+ ['The Star', 'a kneeling figure pouring water from two vessels onto land and pool beneath one great star and seven smaller stars'],
+ ['The Moon', 'a full moon over a path between two towers, a dog and a wolf howling, a crayfish emerging from a pool'],
+ ['The Sun', 'a radiant sun above a joyful child on a white horse, sunflowers over a garden wall, a red banner'],
+ ['Judgement', 'a winged herald sounding a trumpet from the clouds while figures rise from open graves below, mountains behind'],
+ ['The World', 'a dancing figure wreathed in a laurel oval holding two wands, the four living creatures in the corners'],
+]);
+
+const TAROT_SUITS = Object.freeze([
+ { key: 'wands', name: 'Wands' },
+ { key: 'cups', name: 'Cups' },
+ { key: 'swords', name: 'Swords' },
+ { key: 'pentacles', name: 'Pentacles' },
+]);
+const TAROT_RANKS = Object.freeze([
+ { key: 'ace', name: 'Ace' }, { key: '2', name: 'Two' }, { key: '3', name: 'Three' },
+ { key: '4', name: 'Four' }, { key: '5', name: 'Five' }, { key: '6', name: 'Six' },
+ { key: '7', name: 'Seven' }, { key: '8', name: 'Eight' }, { key: '9', name: 'Nine' },
+ { key: '10', name: 'Ten' }, { key: 'page', name: 'Page' }, { key: 'knight', name: 'Knight' },
+ { key: 'queen', name: 'Queen' }, { key: 'king', name: 'King' },
+]);
+
+const ROMAN = ['0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX', 'XXI'];
+
+const backCard = () => ({
+ key: DECK_BACK_KEY,
+ name: 'Card back',
+ group: 'back',
+ groupLabel: 'Back',
+ rank: null,
+ motif: 'the shared reverse-side pattern every card in the deck carries — a repeating symmetrical emblem, no figures, no text',
+});
+
+function playingRoster() {
+ const cards = [];
+ for (const suit of PLAYING_SUITS) {
+ for (const rank of PLAYING_RANKS) {
+ cards.push({
+ key: `${suit.key}-${rank.key}`,
+ name: `${rank.name} of ${suit.name}`,
+ group: suit.key,
+ groupLabel: suit.name,
+ rank: rank.key,
+ motif: null,
+ });
+ }
+ }
+ cards.push({ key: 'joker-1', name: 'Joker (red)', group: 'jokers', groupLabel: 'Jokers', rank: 'joker', motif: 'a jester figure in the deck\'s world' });
+ cards.push({ key: 'joker-2', name: 'Joker (black)', group: 'jokers', groupLabel: 'Jokers', rank: 'joker', motif: 'a second, contrasting jester figure' });
+ cards.push(backCard());
+ return cards;
+}
+
+function tarotRoster() {
+ const cards = MAJOR_ARCANA.map(([name, motif], i) => ({
+ key: `major-${i}`,
+ name: `${ROMAN[i]} · ${name}`,
+ group: 'major',
+ groupLabel: 'Major Arcana',
+ rank: ROMAN[i],
+ motif,
+ }));
+ for (const suit of TAROT_SUITS) {
+ for (const rank of TAROT_RANKS) {
+ cards.push({
+ key: `${suit.key}-${rank.key}`,
+ name: `${rank.name} of ${suit.name}`,
+ group: suit.key,
+ groupLabel: suit.name,
+ rank: rank.key,
+ motif: null,
+ });
+ }
+ }
+ cards.push(backCard());
+ return cards;
+}
+
+/**
+ * The card roster a deck of `kind` mints on creation, in display order. Each
+ * entry is `{ key, name, group, groupLabel, rank, motif }` — `key` is the
+ * stable per-deck slot identity (`hearts-Q`, `major-17`, `back`).
+ */
+export function deckCardRoster(kind) {
+ if (kind === DECK_KIND.PLAYING) return playingRoster();
+ if (kind === DECK_KIND.TAROT) return tarotRoster();
+ throw new Error(`Unknown deck kind: ${kind}`);
+}
+
+const trimmed = (v) => (typeof v === 'string' ? v.trim() : '');
+
+/**
+ * Compose the prompt one card renders with. Order is deliberate: the deck's
+ * embrace influences lead (diffusion models weight early tokens heaviest),
+ * then the shared layout clause, then the card's own subject. The avoid list
+ * becomes the negative prompt, after any per-card negative.
+ */
+export function composeCardRenderPrompt(deck, card) {
+ // A deck carries the same `influences` shape a universe does, so the
+ // universe's visual-style projection is the one definition of "what the
+ // embrace/avoid lists contribute to an image prompt".
+ const embrace = buildVisualStyleClause(deck);
+ const avoid = universeVisualStyleTokens(deck).avoid.join(', ');
+ const layout = trimmed(deck?.layoutPrompt);
+ const subject = [trimmed(card?.name), trimmed(card?.prompt)].filter(Boolean).join(': ');
+ const body = [layout, subject].filter(Boolean).join('. ');
+ return composeStyledPrompt(body, trimmed(card?.negativePrompt), { prompt: embrace, negativePrompt: avoid });
+}
+
+const IN_FLIGHT_RENDER = new Set(['queued', 'running']);
+
+/** The media-job id a card is currently waiting on, or null. */
+export const cardInFlightJobId = (card) => (
+ IN_FLIGHT_RENDER.has(card?.render?.status) && card.render.jobId ? card.render.jobId : null
+);
+
+/** Derived render state for one card row. */
+export function cardStatus(card) {
+ const render = card?.render || null;
+ if (render?.status === 'queued') return CARD_STATUS.QUEUED;
+ if (render?.status === 'running') return CARD_STATUS.RUNNING;
+ if (Array.isArray(card?.imageRefs) && card.imageRefs.length) return CARD_STATUS.RENDERED;
+ if (render?.status === 'failed' || render?.status === 'canceled') return CARD_STATUS.FAILED;
+ return trimmed(card?.prompt) ? CARD_STATUS.PROMPTED : CARD_STATUS.EMPTY;
+}
+
+/** Completion counters for a deck's card list. */
+export function deckCompletion(cards) {
+ const list = Array.isArray(cards) ? cards : [];
+ const counts = { total: list.length, prompted: 0, rendered: 0, inFlight: 0, failed: 0 };
+ for (const card of list) {
+ if (trimmed(card?.prompt)) counts.prompted += 1;
+ const status = cardStatus(card);
+ if (status === CARD_STATUS.RENDERED) counts.rendered += 1;
+ else if (status === CARD_STATUS.QUEUED || status === CARD_STATUS.RUNNING) counts.inFlight += 1;
+ else if (status === CARD_STATUS.FAILED) counts.failed += 1;
+ }
+ counts.percent = counts.total ? Math.round((counts.rendered / counts.total) * 100) : 0;
+ return counts;
+}
diff --git a/server/lib/deckTemplates.test.js b/server/lib/deckTemplates.test.js
new file mode 100644
index 0000000000..623b3b30f3
--- /dev/null
+++ b/server/lib/deckTemplates.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CARD_STATUS, DECK_BACK_KEY, DECK_KIND, cardStatus, composeCardRenderPrompt, deckCardRoster, deckCompletion,
+} from './deckTemplates.js';
+
+describe('deckCardRoster', () => {
+ it('mints a full playing deck (52 faces + 2 jokers + back) with unique keys', () => {
+ const roster = deckCardRoster(DECK_KIND.PLAYING);
+ expect(roster).toHaveLength(55);
+ expect(new Set(roster.map((c) => c.key)).size).toBe(55);
+ expect(roster.find((c) => c.key === 'hearts-Q')).toMatchObject({ name: 'Queen of Hearts', group: 'hearts', rank: 'Q' });
+ expect(roster.at(-1).key).toBe(DECK_BACK_KEY);
+ });
+
+ it('mints a full tarot deck (22 major + 56 minor + back) with motifs on the majors', () => {
+ const roster = deckCardRoster(DECK_KIND.TAROT);
+ expect(roster).toHaveLength(79);
+ expect(new Set(roster.map((c) => c.key)).size).toBe(79);
+ expect(roster.filter((c) => c.group === 'major')).toHaveLength(22);
+ expect(roster.find((c) => c.key === 'major-16')).toMatchObject({ name: 'XVI · The Tower', rank: 'XVI' });
+ expect(roster.find((c) => c.key === 'major-16').motif).toMatch(/lightning/);
+ expect(roster.find((c) => c.key === 'cups-knight')).toMatchObject({ name: 'Knight of Cups', group: 'cups' });
+ });
+
+ it('rejects an unknown kind', () => {
+ expect(() => deckCardRoster('uno')).toThrow(/Unknown deck kind/);
+ });
+});
+
+describe('composeCardRenderPrompt', () => {
+ const deck = {
+ influences: { embrace: ['copperplate engraving', ' aged paper '], avoid: ['blurry'] },
+ layoutPrompt: 'Full tarot card, framed border',
+ };
+
+ it('leads with the style tokens, then the layout, then the titled subject; negatives merge card-first', () => {
+ const out = composeCardRenderPrompt(deck, { name: 'XVII · The Star', prompt: 'a kneeling figure pouring water', negativePrompt: 'text' });
+ expect(out.prompt).toBe('copperplate engraving, aged paper. Full tarot card, framed border. XVII · The Star: a kneeling figure pouring water');
+ expect(out.negativePrompt).toBe('text, blurry');
+ });
+
+ it('degrades cleanly when the deck has no style guide yet', () => {
+ const out = composeCardRenderPrompt({}, { name: 'Ace of Spades', prompt: 'one large ornate spade' });
+ expect(out).toEqual({ prompt: 'Ace of Spades: one large ornate spade', negativePrompt: '' });
+ });
+});
+
+describe('cardStatus + deckCompletion', () => {
+ it('derives the render state from the persisted render record and image refs', () => {
+ expect(cardStatus({ prompt: '' })).toBe(CARD_STATUS.EMPTY);
+ expect(cardStatus({ prompt: 'x' })).toBe(CARD_STATUS.PROMPTED);
+ expect(cardStatus({ prompt: 'x', render: { status: 'queued' } })).toBe(CARD_STATUS.QUEUED);
+ expect(cardStatus({ prompt: 'x', render: { status: 'running' } })).toBe(CARD_STATUS.RUNNING);
+ // A prior image survives a later failed re-render — the card is still rendered.
+ expect(cardStatus({ prompt: 'x', imageRefs: ['a.png'], render: { status: 'failed' } })).toBe(CARD_STATUS.RENDERED);
+ expect(cardStatus({ prompt: 'x', imageRefs: [], render: { status: 'canceled' } })).toBe(CARD_STATUS.FAILED);
+ });
+
+ it('counts rendered / prompted / in-flight / failed and a whole-deck percent', () => {
+ const counts = deckCompletion([
+ { prompt: 'a', imageRefs: ['1.png'] },
+ { prompt: 'b', render: { status: 'running' } },
+ { prompt: 'c', render: { status: 'failed' } },
+ { prompt: '' },
+ ]);
+ expect(counts).toEqual({ total: 4, prompted: 3, rendered: 1, inFlight: 1, failed: 1, percent: 25 });
+ expect(deckCompletion([]).percent).toBe(0);
+ });
+});
diff --git a/server/lib/deckValidation.js b/server/lib/deckValidation.js
new file mode 100644
index 0000000000..0ef6813ff6
--- /dev/null
+++ b/server/lib/deckValidation.js
@@ -0,0 +1,119 @@
+/**
+ * Zod schemas for the `/api/decks` routes. A separate leaf from
+ * `deckTemplates.js` so the client can re-export the pure roster/composition
+ * helpers without pulling zod into the bundle.
+ */
+
+import { z } from 'zod';
+import { DECK_KINDS } from './deckTemplates.js';
+import { llmRoutePinSchema } from './llmRoutePin.js';
+import { INFLUENCE_ENTRY_MAX, INFLUENCES_PER_LIST_MAX, STYLE_NOTES_MAX } from './universeBibleLimits.js';
+
+export const DECK_NAME_MAX = 120;
+export const DECK_DESCRIPTION_MAX = 2000;
+export const DECK_LAYOUT_PROMPT_MAX = 1000;
+export const DECK_CARD_PROMPT_MAX = 4000;
+export const DECK_CARD_NAME_MAX = 120;
+export const DECK_SAMPLES_MAX = 12;
+export const DECK_SAMPLE_TITLE_MAX = 120;
+export const DECK_SAMPLE_PROMPT_MAX = 4000;
+export const DECK_CARD_IMAGE_REFS_MAX = 24;
+export const DECK_CARDS_PER_REQUEST_MAX = 120;
+
+const idField = z.string().trim().min(1).max(200);
+const galleryFilename = z.string().trim().min(1).max(300);
+// Per-call provider/model/effort — the same three fields the deck's stored
+// `promptLlm` pin carries, so a route resolves them with `resolveLlmRoutePin`.
+const perCallLlm = llmRoutePinSchema.shape;
+
+const influenceEntry = z.string().trim().min(1).max(INFLUENCE_ENTRY_MAX);
+const influencesSchema = z.object({
+ embrace: z.array(influenceEntry).max(INFLUENCES_PER_LIST_MAX).optional().default([]),
+ avoid: z.array(influenceEntry).max(INFLUENCES_PER_LIST_MAX).optional().default([]),
+}).strict();
+
+const cardSizeSchema = z.object({
+ width: z.number().int().min(256).max(4096),
+ height: z.number().int().min(256).max(4096),
+}).strict();
+
+export const deckCreateSchema = z.object({
+ name: z.string().trim().min(1).max(DECK_NAME_MAX),
+ kind: z.enum(DECK_KINDS),
+ description: z.string().trim().max(DECK_DESCRIPTION_MAX).optional().default(''),
+ // Linked universe (optional). `seedStyleFromUniverse` copies its influences
+ // + style notes into the deck at creation; the link itself also feeds the
+ // casting step (universe cast/places/objects placed on cards).
+ universeId: idField.nullable().optional(),
+ seedStyleFromUniverse: z.boolean().optional().default(true),
+}).strict();
+
+export const deckUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(DECK_NAME_MAX).optional(),
+ description: z.string().trim().max(DECK_DESCRIPTION_MAX).optional(),
+ styleNotes: z.string().trim().max(STYLE_NOTES_MAX).optional(),
+ influences: influencesSchema.optional(),
+ layoutPrompt: z.string().trim().max(DECK_LAYOUT_PROMPT_MAX).optional(),
+ universeId: idField.nullable().optional(),
+ // Per-record render pin (#3231 Phase 3 shape): null clears.
+ imageMode: z.string().trim().max(40).nullable().optional(),
+ imageModelId: z.string().trim().max(64).nullable().optional(),
+ cardSize: cardSizeSchema.optional(),
+ // The LLM pin for casting + prompt writing; null clears.
+ promptLlm: llmRoutePinSchema.nullable().optional(),
+}).strict();
+
+export const deckCardUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(DECK_CARD_NAME_MAX).optional(),
+ prompt: z.string().trim().max(DECK_CARD_PROMPT_MAX).optional(),
+ negativePrompt: z.string().trim().max(DECK_CARD_PROMPT_MAX).optional(),
+ primaryImageRef: galleryFilename.nullable().optional(),
+ // Wholesale replace so the drawer can drop a stale render from the history.
+ imageRefs: z.array(galleryFilename).max(DECK_CARD_IMAGE_REFS_MAX).optional(),
+ canonRef: z.object({
+ kind: z.enum(['character', 'place', 'object']),
+ id: idField,
+ name: z.string().trim().max(200).optional().default(''),
+ }).strict().nullable().optional(),
+}).strict();
+
+export const deckAnalyzeSampleSchema = z.object({
+ image: galleryFilename,
+ title: z.string().trim().max(DECK_SAMPLE_TITLE_MAX).optional(),
+ ...perCallLlm,
+}).strict();
+
+const sampleSchema = z.object({
+ id: idField,
+ title: z.string().trim().min(1).max(DECK_SAMPLE_TITLE_MAX),
+ prompt: z.string().trim().max(DECK_SAMPLE_PROMPT_MAX).optional().default(''),
+ imageRef: galleryFilename,
+ createdAt: z.string().trim().max(40).optional(),
+}).strict();
+
+export const deckAddSampleSchema = z.object({
+ sample: sampleSchema,
+ adopt: z.object({
+ styleNotes: z.string().trim().max(STYLE_NOTES_MAX).optional().default(''),
+ influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),
+ layoutPrompt: z.string().trim().max(DECK_LAYOUT_PROMPT_MAX).optional(),
+ }).strict().optional(),
+}).strict();
+
+export const deckGeneratePromptsSchema = z.object({
+ cardIds: z.array(idField).max(DECK_CARDS_PER_REQUEST_MAX).optional(),
+ // Rewrite cards that already carry a prompt (default: only fill empties).
+ overwrite: z.boolean().optional().default(false),
+ // Skip the universe casting pass even when a universe is linked.
+ cast: z.boolean().optional().default(true),
+ ...perCallLlm,
+}).strict();
+
+export const deckRenderSchema = z.object({
+ cardIds: z.array(idField).max(DECK_CARDS_PER_REQUEST_MAX).optional(),
+ // Skip cards that already have a render (the "finish the deck" button).
+ onlyMissing: z.boolean().optional().default(false),
+ mode: z.string().trim().max(40).optional(),
+ model: z.string().trim().max(200).optional(),
+ seed: z.number().int().min(0).optional(),
+}).strict();
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 199d19a829..d4f6dc2aa0 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -472,7 +472,15 @@ describe('deferred imports stay deferred (#6156)', () => {
// handful of closures that reach these services — there is no subtree behind
// them to narrow, and deferring a compare used on every passive quota read
// would trade the whole point of the shared rule for four instantiations.
-const MAX_STATIC_INSTANTIATIONS = 103525;
+// Decks (Create → Decks) measures +393 after narrowing everything that could
+// be: the route module, the boot-time hook, the render service and the prompt
+// services all defer their heavy subtrees (DB, prompt runner, media queue,
+// image-gen dispatcher) to the request that needs them. What remains is the
+// closures of the six new suites themselves — the DB-backed route suite reaches
+// db.js, the hook suite reaches the media queue, the prompt/render suites reach
+// the modules they mock — plus the two pure leaves the lib barrel gains and the
+// schema composer's decks.js, counted by the suites that load those barrels.
+const MAX_STATIC_INSTANTIATIONS = 103918;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index 803744dc99..b278432e0c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -628,3 +628,5 @@ export * from './voiceEngines.js';
export * from './auditQuality.js';
export * from './mindToolRecipes.js';
+export * from './deckTemplates.js';
+export * from './deckValidation.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index c1cf78376e..e0774fd850 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -58,6 +58,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },
{ id: 'nav.create.game', path: '/game', label: 'Game', section: 'Create', aliases: ['game', 'games', 'game-studio'], keywords: ['managed app', 'sprite', 'atlas', 'music', 'asset bundle', 'manifest', 'feedback'] },
{ id: 'nav.create.music-video', path: '/music-video', label: 'Music Video', section: 'Create', previousPaths: ['/media/music-video', '/media/music-video/:projectId'], aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },
+ { id: 'nav.create.decks', path: '/decks', label: 'Decks', section: 'Create', aliases: ['decks', 'deck', 'card-deck', 'playing-cards', 'tarot', 'tarot-deck', 'cards'], keywords: ['playing cards', 'tarot', 'card deck', 'card design', 'suits', 'arcana', 'style guide', 'batch render', 'card art'] },
{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },
// Promoted out of the Media Gen tabs to a top-level Create page (#2930).
// The id stays `nav.media.sprites` — it's opaque and stored in palette
diff --git a/server/lib/renderTargets.js b/server/lib/renderTargets.js
index 2085763ad7..cb995365d5 100644
--- a/server/lib/renderTargets.js
+++ b/server/lib/renderTargets.js
@@ -26,6 +26,7 @@ export const RENDER_TARGET = Object.freeze({
LORA_DATASET: 'lora-dataset',
CREATIVE_AGENT: 'creative-agent',
FABLELOOM_PRODUCTION: 'fableloom-production',
+ DECK: 'deck',
});
export const RENDER_TARGETS = Object.freeze(Object.values(RENDER_TARGET));
diff --git a/server/lib/universePromptRenderers.js b/server/lib/universePromptRenderers.js
index 168901b09b..ca284cbef7 100644
--- a/server/lib/universePromptRenderers.js
+++ b/server/lib/universePromptRenderers.js
@@ -43,7 +43,7 @@ export function renderCompositesForPrompt(composites, { showLocked = false } = {
export const CANON_PROMPT_ENTRIES_PER_KIND_MAX = 40;
export const CANON_PROMPT_DESCRIPTION_MAX = 300;
-const truncDesc = (s) => {
+export const truncDesc = (s) => {
if (typeof s !== 'string') return '';
const trimmed = s.trim();
if (trimmed.length <= CANON_PROMPT_DESCRIPTION_MAX) return trimmed;
diff --git a/server/routes/decks.db.test.js b/server/routes/decks.db.test.js
new file mode 100644
index 0000000000..1e629f27f2
--- /dev/null
+++ b/server/routes/decks.db.test.js
@@ -0,0 +1,143 @@
+/** Deck designer over HTTP and PostgreSQL. Runs only against portos_test. */
+import { afterAll, describe, expect, it } from 'vitest';
+import express from 'express';
+import { randomUUID } from 'node:crypto';
+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import deckRoutes from './decks.js';
+import { attachCardRender, markCardsRenderQueued, markCardRenderTerminal } from '../services/decks.js';
+import { cardStatus } from '../lib/deckTemplates.js';
+
+const health = await checkHealth().catch((error) => ({ connected: false, error: error.message }));
+const ready = requireDbOrSkip('routes/decks.db.test', health.connected, health.error);
+if (ready) await ensureSchema();
+const ids = [];
+afterAll(async () => {
+ if (ready && ids.length) await query('DELETE FROM decks WHERE id = ANY($1::uuid[])', [ids]);
+ await close();
+});
+const app = express();
+app.use(express.json());
+app.use('/decks', deckRoutes);
+app.use(errorMiddleware);
+const get = (path = '') => request(app).get(`/decks${path}`);
+const post = (path, body) => request(app).post(`/decks${path}`).send(body);
+const patch = (path, body) => request(app).patch(`/decks${path}`).send(body);
+const del = (path) => request(app).delete(`/decks${path}`);
+
+const create = async (body) => {
+ const saved = await post('', body);
+ expect(saved.status).toBe(201);
+ ids.push(saved.body.id);
+ return saved.body;
+};
+
+describe.skipIf(!ready)('decks over HTTP and PostgreSQL', () => {
+ it('creates a tarot deck with its full roster and default layout, lists it with completion', async () => {
+ const deck = await create({ name: 'Example Deck', kind: 'tarot' });
+ expect(deck.cards).toHaveLength(79);
+ expect(deck.layoutPrompt).toMatch(/tarot card/);
+ expect(deck.completion).toMatchObject({ total: 79, prompted: 0, rendered: 0, percent: 0 });
+ const fool = deck.cards.find((c) => c.key === 'major-0');
+ expect(fool).toMatchObject({ name: '0 · The Fool', imageRefs: [] });
+ expect(cardStatus(fool)).toBe('empty');
+ const list = await get();
+ expect(list.status).toBe(200);
+ expect(list.body).toContainEqual(expect.objectContaining({ id: deck.id, kind: 'tarot', completion: expect.objectContaining({ total: 79 }) }));
+ });
+
+ it('rejects an unknown kind and a linked universe that does not exist', async () => {
+ expect((await post('', { name: 'Bad', kind: 'uno' })).status).toBe(400);
+ const missing = await post('', { name: 'Orphan', kind: 'playing', universeId: 'no-such-universe' });
+ expect(missing.status).toBe(400);
+ expect(missing.body.code).toBe('DECK_UNIVERSE_NOT_FOUND');
+ });
+
+ it('patches the style guide + pins and per-card prompts, then reflects completion', async () => {
+ const deck = await create({ name: 'Style Deck', kind: 'playing' });
+ const styled = await patch(`/${deck.id}`, {
+ styleNotes: 'Engraved, sepia, celestial.',
+ influences: { embrace: ['copperplate engraving', ' aged paper '], avoid: ['blurry'] },
+ layoutPrompt: 'Full playing card',
+ imageMode: 'codex',
+ imageModelId: 'gpt-image-2',
+ promptLlm: { providerId: 'p1', model: 'm1', effort: 'high' },
+ });
+ expect(styled.status).toBe(200);
+ expect(styled.body).toMatchObject({
+ styleNotes: 'Engraved, sepia, celestial.',
+ influences: { embrace: ['copperplate engraving', 'aged paper'], avoid: ['blurry'] },
+ layoutPrompt: 'Full playing card',
+ imageMode: 'codex',
+ imageModelId: 'gpt-image-2',
+ promptLlm: { providerId: 'p1', model: 'm1', effort: 'high' },
+ });
+ // Clearing the pin: key present with null.
+ expect((await patch(`/${deck.id}`, { imageMode: null, imageModelId: null })).body).toMatchObject({ imageMode: null, imageModelId: null });
+ expect((await patch(`/${deck.id}`, { bogus: 1 })).status).toBe(400);
+ expect((await get('/not-a-uuid')).status).toBe(400);
+
+ const ace = deck.cards.find((c) => c.key === 'spades-A');
+ const edited = await patch(`/${deck.id}/cards/${ace.id}`, { prompt: 'one great ornate spade', negativePrompt: 'text' });
+ expect(edited.status).toBe(200);
+ expect(edited.body).toMatchObject({ key: 'spades-A', prompt: 'one great ornate spade', negativePrompt: 'text' });
+ expect(cardStatus(edited.body)).toBe('prompted');
+ expect((await get(`/${deck.id}`)).body.completion).toMatchObject({ prompted: 1, rendered: 0 });
+ expect((await patch(`/${deck.id}/cards/${randomUUID()}`, { prompt: 'x' })).status).toBe(404);
+ });
+
+ it('files a completed render onto the card, ignores a stale terminal event, and lets the drawer curate the history', async () => {
+ const deck = await create({ name: 'Render Deck', kind: 'playing' });
+ const card = deck.cards.find((c) => c.key === 'hearts-Q');
+ await patch(`/${deck.id}/cards/${card.id}`, { prompt: 'a queen' });
+ await markCardsRenderQueued(deck.id, [{ cardId: card.id, render: { jobId: 'job-1', status: 'queued', queuedAt: new Date().toISOString() } }]);
+ const readCard = async () => (await get(`/${deck.id}`)).body.cards.find((c) => c.id === card.id);
+ expect(cardStatus(await readCard())).toBe('queued');
+
+ // A failure event for a superseded job must not flip the card.
+ expect(await markCardRenderTerminal(deck.id, card.id, { jobId: 'job-0', status: 'failed' })).toBeNull();
+ expect(cardStatus(await readCard())).toBe('queued');
+
+ const attached = await attachCardRender({ deckId: deck.id, cardId: card.id, filename: 'job-1.png', jobId: 'job-1' });
+ expect(attached).toMatchObject({ imageRefs: ['job-1.png'], primaryImageRef: 'job-1.png' });
+ expect(cardStatus(attached)).toBe('rendered');
+ // A queued stamp that lands AFTER the hook filed the same job must not regress it.
+ await markCardsRenderQueued(deck.id, [{ cardId: card.id, render: { jobId: 'job-1', status: 'queued' } }]);
+ expect(cardStatus(await readCard())).toBe('rendered');
+ const again = await attachCardRender({ deckId: deck.id, cardId: card.id, filename: 'job-2.png', jobId: 'job-2' });
+ expect(again).toMatchObject({ imageRefs: ['job-1.png', 'job-2.png'], primaryImageRef: 'job-2.png' });
+ expect((await get(`/${deck.id}`)).body.completion).toMatchObject({ rendered: 1, inFlight: 0 });
+
+ // Drawer: pick the older render as primary, then drop it — primary falls back.
+ expect((await patch(`/${deck.id}/cards/${card.id}`, { primaryImageRef: 'job-1.png' })).body.primaryImageRef).toBe('job-1.png');
+ const curated = await patch(`/${deck.id}/cards/${card.id}`, { imageRefs: ['job-2.png'] });
+ expect(curated.body).toMatchObject({ imageRefs: ['job-2.png'], primaryImageRef: null });
+ expect(cardStatus(curated.body)).toBe('rendered');
+ // A card that vanished returns null rather than throwing from the hook.
+ expect(await attachCardRender({ deckId: deck.id, cardId: randomUUID(), filename: 'x.png', jobId: 'j' })).toBeNull();
+ });
+
+ it('adds a sample with an adopted style guide in one write, removes it, and cascades on delete', async () => {
+ const deck = await create({ name: 'Sample Deck', kind: 'tarot' });
+ const sample = { id: 'deck-sample-1', title: 'Poster', prompt: 'a lighthouse poster', imageRef: 'upload-1.png' };
+ const adopted = await post(`/${deck.id}/samples`, {
+ sample,
+ adopt: { styleNotes: 'From the poster.', influences: { embrace: ['art deco'], avoid: [] }, layoutPrompt: 'Framed' },
+ });
+ expect(adopted.status).toBe(200);
+ expect(adopted.body).toMatchObject({ styleNotes: 'From the poster.', influences: { embrace: ['art deco'], avoid: [] }, layoutPrompt: 'Framed' });
+ expect(adopted.body.samples).toHaveLength(1);
+ expect(adopted.body.samples[0]).toMatchObject({ id: 'deck-sample-1', imageRef: 'upload-1.png' });
+ // Idempotent on id — a re-sent add doesn't duplicate.
+ expect((await post(`/${deck.id}/samples`, { sample })).body.samples).toHaveLength(1);
+ expect((await del(`/${deck.id}/samples/deck-sample-1`)).body.samples).toHaveLength(0);
+
+ expect((await del(`/${deck.id}`)).status).toBe(200);
+ expect((await get(`/${deck.id}`)).status).toBe(404);
+ const { rows } = await query('SELECT COUNT(*)::int AS n FROM deck_cards WHERE deck_id = $1', [deck.id]);
+ expect(rows[0].n).toBe(0);
+ expect((await del(`/${deck.id}`)).status).toBe(404);
+ });
+});
diff --git a/server/routes/decks.js b/server/routes/decks.js
new file mode 100644
index 0000000000..226e27f791
--- /dev/null
+++ b/server/routes/decks.js
@@ -0,0 +1,172 @@
+/**
+ * Decks routes — playing-card / tarot deck designer (Create → Decks).
+ *
+ * CRUD on the deck + its cards, the stateless sample-design analysis
+ * (vision → proposed style guide, persisted only through `/samples`), the
+ * casting + prompt-writing pass, and single/batch card rendering through the
+ * shared media queue.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import {
+ deckAddSampleSchema,
+ deckAnalyzeSampleSchema,
+ deckCardUpdateSchema,
+ deckCreateSchema,
+ deckGeneratePromptsSchema,
+ deckRenderSchema,
+ deckUpdateSchema,
+} from '../lib/deckValidation.js';
+import { resolveGalleryImageOrThrow } from './universeBuilder/shared.js';
+import { resolveLlmRoutePin } from '../lib/llmRoutePin.js';
+
+// Services load on first request, not at route-module import: the deck graph
+// reaches the DB, the prompt runner and the media queue, none of which a
+// route-only consumer needs instantiated (server/AGENTS.md "Import scoping").
+const decks = () => import('../services/decks.js');
+const styleAnalysis = () => import('../services/deckStyleAnalysis.js');
+const prompts = () => import('../services/deckPrompts.js');
+const render = () => import('../services/deckRender.js');
+
+const router = Router();
+
+// Ids are UUIDs minted by the service; validating up front turns a malformed
+// id into a 400 instead of a Postgres cast error surfacing as a 500.
+const deckParams = z.object({ id: z.uuid() });
+const cardParams = deckParams.extend({ cardId: z.uuid() });
+const sampleParams = deckParams.extend({ sampleId: z.string().trim().min(1).max(200) });
+const deckId = (req) => validateRequest(deckParams, req.params).id;
+const cardIds = (req) => validateRequest(cardParams, req.params);
+
+router.get('/', asyncHandler(async (_req, res) => {
+ const { listDecks } = await decks();
+ res.json(await listDecks());
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckCreateSchema, req.body ?? {});
+ const { createDeck } = await decks();
+ res.status(201).json(await createDeck(body));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const { getDeck } = await decks();
+ res.json(await getDeck(deckId(req)));
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckUpdateSchema, req.body ?? {});
+ const { updateDeck } = await decks();
+ res.json(await updateDeck(deckId(req), body));
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const { deleteDeck } = await decks();
+ res.json(await deleteDeck(deckId(req)));
+}));
+
+router.patch('/:id/cards/:cardId', asyncHandler(async (req, res) => {
+ const { id, cardId } = cardIds(req);
+ const body = validateRequest(deckCardUpdateSchema, req.body ?? {});
+ const { updateCard } = await decks();
+ res.json(await updateCard(id, cardId, body));
+}));
+
+// Stateless review step: analyze a gallery image against the deck's current
+// style guide and return a proposal + diff. Persistence happens through
+// POST /:id/samples once the user picks "add" or "adopt + add".
+router.post('/:id/analyze-sample', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckAnalyzeSampleSchema, req.body ?? {});
+ const [{ getDeck }, { analyzeDeckSample }] = await Promise.all([decks(), styleAnalysis()]);
+ const deck = await getDeck(deckId(req));
+ const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);
+ // Vision needs an image-capable API provider, which the deck's prompt pin
+ // (a text job) need not be — so the picker in the modal is the only source.
+ res.json(await analyzeDeckSample({
+ deck, imagePath, imageFilename, title: body.title,
+ providerId: body.providerId || undefined, model: body.model || undefined, effort: body.effort || undefined,
+ }));
+}));
+
+router.post('/:id/samples', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckAddSampleSchema, req.body ?? {});
+ const { addSample } = await decks();
+ res.json(await addSample(deckId(req), body.sample, { adopt: body.adopt }));
+}));
+
+router.delete('/:id/samples/:sampleId', asyncHandler(async (req, res) => {
+ const { id, sampleId } = validateRequest(sampleParams, req.params);
+ const { removeSample } = await decks();
+ res.json(await removeSample(id, sampleId));
+}));
+
+// Casting (universe-linked decks) + prompt writing in one user action. The
+// casting pass runs only when a universe is linked, `cast` is on, and at least
+// one targeted card is still uncast — so re-running to fill new prompts doesn't
+// re-shuffle an assignment the user already accepted.
+router.post('/:id/generate-prompts', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckGeneratePromptsSchema, req.body ?? {});
+ const [{ getDeck, applyCardGenerations }, { castDeckFromUniverse, generateDeckCardPrompts }] = await Promise.all([decks(), prompts()]);
+ const deck = await getDeck(deckId(req));
+ // Per-call choice over the deck's stored pin; a provider switch drops the
+ // pinned model/effort rather than carrying them across providers.
+ const { providerId, model, effort } = resolveLlmRoutePin(deck.promptLlm, body);
+ const llm = { providerId: providerId || undefined, model: model || undefined, effort: effort || undefined };
+ const wanted = Array.isArray(body.cardIds) && body.cardIds.length ? new Set(body.cardIds) : null;
+ let roster = deck.cards;
+ const targetIds = new Set(roster.filter((c) => (!wanted || wanted.has(c.id)) && (body.overwrite || !c.prompt)).map((c) => c.id));
+ if (!targetIds.size) {
+ throw new ServerError('Every selected card already has a prompt — enable overwrite to rewrite them.', {
+ status: 400, code: 'DECK_NO_PROMPT_TARGETS',
+ });
+ }
+
+ let universe = null;
+ let cast = null;
+ if (deck.universeId) {
+ const { getUniverse } = await import('../services/universeBuilder.js');
+ universe = await getUniverse(deck.universeId).catch(() => null);
+ if (universe && body.cast && roster.some((c) => targetIds.has(c.id) && !c.canonRef)) {
+ cast = await castDeckFromUniverse({ deck, cards: roster, universe, ...llm });
+ // Only cards not yet cast take an assignment; a user-accepted link stays.
+ const uncast = new Set(roster.filter((c) => !c.canonRef).map((c) => c.id));
+ const applied = new Map(cast.assignments.filter((a) => uncast.has(a.cardId)).map((a) => [a.cardId, a.canonRef]));
+ await applyCardGenerations(deck.id, [...applied].map(([cardId, canonRef]) => ({ cardId, canonRef })));
+ roster = roster.map((c) => (applied.has(c.id) ? { ...c, canonRef: applied.get(c.id) } : c));
+ }
+ }
+ const targets = roster.filter((c) => targetIds.has(c.id));
+
+ // Prompts persist chunk by chunk, so a chunk that fails mid-deck (a model
+ // that returns bad JSON on its third call) leaves the earlier cards written.
+ let applied = 0;
+ const generated = await generateDeckCardPrompts({
+ deck, roster, targets, universe, ...llm,
+ onChunk: async (chunk) => { applied += await applyCardGenerations(deck.id, chunk); },
+ });
+ res.json({
+ deck: await getDeck(deck.id),
+ written: applied,
+ requested: targets.length,
+ cast: cast ? cast.assignments.filter((a) => a.canonRef).length : 0,
+ llm: generated.llm,
+ });
+}));
+
+router.post('/:id/render', asyncHandler(async (req, res) => {
+ const body = validateRequest(deckRenderSchema, req.body ?? {});
+ const { renderDeckCards } = await render();
+ res.json(await renderDeckCards(deckId(req), body));
+}));
+
+router.post('/:id/cards/:cardId/render', asyncHandler(async (req, res) => {
+ const { id, cardId } = cardIds(req);
+ const body = validateRequest(deckRenderSchema.omit({ cardIds: true, onlyMissing: true }), req.body ?? {});
+ const { renderDeckCards } = await render();
+ res.json(await renderDeckCards(id, { ...body, cardIds: [cardId] }));
+}));
+
+export default router;
diff --git a/server/routes/decks.test.js b/server/routes/decks.test.js
new file mode 100644
index 0000000000..820226b358
--- /dev/null
+++ b/server/routes/decks.test.js
@@ -0,0 +1,138 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { randomUUID } from 'node:crypto';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Routing + orchestration test: the DB-backed CRUD is covered by
+// decks.db.test.js; here the services are stubbed so the casting gate, the
+// stored-pin fallback and the single-card render shape are pinned.
+vi.mock('../services/decks.js', () => ({
+ listDecks: vi.fn(async () => []),
+ getDeck: vi.fn(),
+ createDeck: vi.fn(),
+ updateDeck: vi.fn(),
+ deleteDeck: vi.fn(),
+ updateCard: vi.fn(),
+ applyCardGenerations: vi.fn(async (_id, entries) => entries.length),
+ addSample: vi.fn(),
+ removeSample: vi.fn(),
+}));
+vi.mock('../services/deckStyleAnalysis.js', () => ({ analyzeDeckSample: vi.fn() }));
+vi.mock('../services/deckPrompts.js', () => ({
+ castDeckFromUniverse: vi.fn(),
+ generateDeckCardPrompts: vi.fn(),
+}));
+vi.mock('../services/deckRender.js', () => ({ renderDeckCards: vi.fn() }));
+vi.mock('../services/universeBuilder.js', () => ({ getUniverse: vi.fn() }));
+vi.mock('./universeBuilder/shared.js', () => ({
+ resolveGalleryImageOrThrow: vi.fn((f) => ({ imageFilename: f, imagePath: `/abs/${f}` })),
+}));
+
+import * as svc from '../services/decks.js';
+import { analyzeDeckSample } from '../services/deckStyleAnalysis.js';
+import { castDeckFromUniverse, generateDeckCardPrompts } from '../services/deckPrompts.js';
+import { renderDeckCards } from '../services/deckRender.js';
+import { getUniverse } from '../services/universeBuilder.js';
+import deckRoutes from './decks.js';
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/decks', deckRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const D1 = randomUUID();
+const C0 = randomUUID();
+const C1 = randomUUID();
+const CB = randomUUID();
+const card = (id, extra = {}) => ({ id, key: id, name: id, prompt: '', canonRef: null, imageRefs: [], ...extra });
+const deck = (extra = {}) => ({
+ id: D1, name: 'Deck', kind: 'tarot', universeId: null, styleNotes: '', influences: { embrace: [], avoid: [] },
+ promptLlm: { providerId: 'pinned', model: 'pinned-model', effort: 'high' },
+ cards: [card(C0, { key: C0 }), card(C1, { key: C1, prompt: 'kept' }), card(CB, { key: 'back' })],
+ ...extra,
+});
+
+describe('deck routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ svc.getDeck.mockResolvedValue(deck());
+ generateDeckCardPrompts.mockImplementation(async ({ onChunk }) => {
+ const prompts = [{ cardId: C0, prompt: 'a fool' }];
+ await onChunk?.(prompts);
+ return { prompts, llm: { provider: 'p', model: 'm' } };
+ });
+ });
+
+ it('validates the create body and returns 201', async () => {
+ svc.createDeck.mockResolvedValueOnce({ id: 'd1' });
+ const res = await request(makeApp()).post('/api/decks').send({ name: 'X', kind: 'playing', universeId: 'u1' });
+ expect(res.status).toBe(201);
+ expect(svc.createDeck).toHaveBeenCalledWith({ name: 'X', kind: 'playing', universeId: 'u1', description: '', seedStyleFromUniverse: true });
+ expect((await request(makeApp()).post('/api/decks').send({ name: '', kind: 'playing' })).status).toBe(400);
+ });
+
+ it('analyze-sample resolves the gallery image and passes the request vision choice through', async () => {
+ analyzeDeckSample.mockResolvedValueOnce({ sample: {} });
+ const res = await request(makeApp()).post(`/api/decks/${D1}/analyze-sample`).send({ image: 'upload-1.png', providerId: 'vp', model: 'vm' });
+ expect(res.status).toBe(200);
+ expect(analyzeDeckSample).toHaveBeenCalledWith(expect.objectContaining({
+ imageFilename: 'upload-1.png', imagePath: '/abs/upload-1.png', providerId: 'vp', model: 'vm', effort: undefined,
+ }));
+ });
+
+ it('generate-prompts targets only empty cards by default and skips casting without a universe', async () => {
+ const res = await request(makeApp()).post(`/api/decks/${D1}/generate-prompts`).send({});
+ expect(res.status).toBe(200);
+ expect(castDeckFromUniverse).not.toHaveBeenCalled();
+ const call = generateDeckCardPrompts.mock.calls[0][0];
+ expect(call.targets.map((c) => c.id)).toEqual([C0, CB]);
+ expect(call.universe).toBeNull();
+ // The deck's stored pin drives the run when the request names nothing.
+ expect(call).toMatchObject({ providerId: 'pinned', model: 'pinned-model', effort: 'high' });
+ expect(svc.applyCardGenerations).toHaveBeenCalledWith(D1, [{ cardId: C0, prompt: 'a fool' }]);
+ expect(res.body).toMatchObject({ written: 1, requested: 2, cast: 0 });
+ });
+
+ it('generate-prompts casts a universe-linked deck first and applies only new assignments', async () => {
+ const linked = deck({ universeId: 'u1', cards: [card(C0, { key: C0 }), card(C1, { key: C1, canonRef: { kind: 'character', id: 'c9', name: 'Kept' } }), card(CB, { key: 'back' })] });
+ svc.getDeck.mockResolvedValue(linked);
+ getUniverse.mockResolvedValue({ id: 'u1', characters: [] });
+ castDeckFromUniverse.mockResolvedValueOnce({
+ assignments: [
+ { cardId: C0, canonRef: { kind: 'character', id: 'c1', name: 'Hero' } },
+ { cardId: C1, canonRef: { kind: 'character', id: 'c2', name: 'Other' } },
+ ],
+ llm: {},
+ });
+ const res = await request(makeApp()).post(`/api/decks/${D1}/generate-prompts`).send({ overwrite: true, providerId: 'p9' });
+ expect(res.status).toBe(200);
+ // A per-call provider switch drops the pinned model/effort (they belong to the other provider).
+ expect(castDeckFromUniverse).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'p9', model: undefined, effort: undefined, universe: { id: 'u1', characters: [] } }));
+ // The prompt pass sees the freshly cast card without a second deck read.
+ expect(generateDeckCardPrompts.mock.calls[0][0].roster.find((c) => c.id === C0).canonRef).toEqual({ kind: 'character', id: 'c1', name: 'Hero' });
+ expect(svc.getDeck).toHaveBeenCalledTimes(2);
+ // The already-cast card keeps its assignment; only the uncast one is written.
+ expect(svc.applyCardGenerations.mock.calls[0][1]).toEqual([{ cardId: C0, canonRef: { kind: 'character', id: 'c1', name: 'Hero' } }]);
+ expect(res.body.cast).toBe(2);
+ });
+
+ it('generate-prompts 400s when nothing is left to write', async () => {
+ svc.getDeck.mockResolvedValue(deck({ cards: [card(C1, { key: C1, prompt: 'kept' })] }));
+ const res = await request(makeApp()).post(`/api/decks/${D1}/generate-prompts`).send({});
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('DECK_NO_PROMPT_TARGETS');
+ expect(generateDeckCardPrompts).not.toHaveBeenCalled();
+ });
+
+ it('single-card render narrows the batch to that card', async () => {
+ renderDeckCards.mockResolvedValueOnce({ mode: 'local', jobs: [], skipped: 0 });
+ const res = await request(makeApp()).post(`/api/decks/${D1}/cards/${C0}/render`).send({ mode: 'local' });
+ expect(res.status).toBe(200);
+ expect(renderDeckCards).toHaveBeenCalledWith(D1, { mode: 'local', cardIds: [C0] });
+ expect((await request(makeApp()).post(`/api/decks/${D1}/render`).send({ onlyMissing: 'yes' })).status).toBe(400);
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 956b396b38..8a4df21742 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -2070,3 +2070,25 @@ CREATE TABLE IF NOT EXISTS mind_tool_recipe_versions (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (recipe_id, revision)
);
+
+-- Decks: playing-card / tarot design projects. Cards are per-row so a render
+-- attaches to one card; image bytes stay in data/images and are referenced by name.
+CREATE TABLE IF NOT EXISTS decks (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('playing', 'tarot')),
+ universe_id TEXT,
+ definition JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ );
+CREATE TABLE IF NOT EXISTS deck_cards (
+ id UUID PRIMARY KEY,
+ deck_id UUID NOT NULL REFERENCES decks (id) ON DELETE CASCADE,
+ position INTEGER NOT NULL,
+ key TEXT NOT NULL,
+ definition JSONB NOT NULL DEFAULT '{}'::jsonb,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (deck_id, key)
+ );
+CREATE INDEX IF NOT EXISTS idx_deck_cards_deck ON deck_cards (deck_id, position);
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 2846b0d2f4..9dd82a9f97 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -139,6 +139,7 @@ import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook
import { initMusicStudioHook } from './musicStudioHook.js';
import { initImageGenQuotaHook } from './imageGenQuota.js';
import { initSpriteReferenceImageHook } from './spriteReferenceImageHook.js';
+import { initDeckRenderHook } from './deckRenderHook.js';
import { initCreativeDirectorSceneImageHook } from './creativeDirectorSceneImageHook.js';
import { initCreativeDirectorRenderFailureHook } from './creativeDirector/renderFailureHook.js';
import { initComicPagesFilenameHook } from './pipeline/comicPagesFilenameHook.js';
@@ -626,6 +627,8 @@ const initMediaJobDependentHooks = () => {
// render into the sprite record's reference/candidates/ with a generation
// sidecar (#2896).
initSpriteReferenceImageHook();
+ // Deck card hook — files a completed card render onto its deck card row.
+ initDeckRenderHook();
// Creative Director scene-frame hook — durably files a queued first-pass
// reference-frame render onto its project scene's `sourceImageFile` on
// completion, even if no client is watching (#1867).
diff --git a/server/services/deckPrompts.js b/server/services/deckPrompts.js
new file mode 100644
index 0000000000..44fe42f677
--- /dev/null
+++ b/server/services/deckPrompts.js
@@ -0,0 +1,259 @@
+/**
+ * Deck prompt authoring — two LLM passes over a deck's card roster.
+ *
+ * 1. `castDeckFromUniverse` (only for a universe-linked deck): place the
+ * universe's cast, places and objects onto the cards that suit them (a
+ * protagonist on The Fool or the King of Hearts, the haunted lighthouse on
+ * The Tower…). One call for the whole deck so the assignment is coherent —
+ * the output is compact (card key → canon id).
+ * 2. `generateDeckCardPrompts`: write the SUBJECT prompt for each requested
+ * card, chunked so a 79-card tarot deck never asks for 79 prompts in one
+ * response. Each chunk sees the full roster (with any canon assignment) so
+ * it can keep the set consistent, but writes prompts only for its subset.
+ *
+ * Prompts describe the subject only: the deck's embrace influences + layout
+ * clause are prepended at render time by `composeCardRenderPrompt`, mirroring
+ * the universe-variation contract.
+ */
+
+import { extractJson } from '../lib/jsonExtract.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { stripPromptControlChars, buildUniverseStyleContext } from './universeBuilder/compile.js';
+import { truncDesc } from '../lib/universePromptRenderers.js';
+import { DECK_KIND, DECK_KIND_LABELS } from '../lib/deckTemplates.js';
+import { DECK_CARD_PROMPT_MAX } from '../lib/deckValidation.js';
+
+// Small enough that one bad string can't sink a long response; a 79-card
+// tarot deck is seven calls.
+export const PROMPTS_PER_CALL = 12;
+const CANON_KINDS = Object.freeze([
+ { field: 'characters', kind: 'character', header: 'CHARACTERS' },
+ { field: 'places', kind: 'place', header: 'PLACES' },
+ { field: 'objects', kind: 'object', header: 'OBJECTS' },
+]);
+
+// The prompt runner is the heaviest subtree a deck touches; load it per call.
+const promptRunner = () => import('./promptRunner.js');
+
+const safe = (v) => stripPromptControlChars(typeof v === 'string' ? v : '');
+
+const noProvider = () => ({
+ message: 'No AI provider is configured for prompt generation. Add one under Settings → Providers.',
+ code: 'NO_PROVIDER',
+ status: 503,
+});
+
+const invalidJson = (what, { lastError, lastPreview }) => new ServerError(
+ `The model returned invalid JSON for ${what}. Try a different model or rerun.`,
+ { status: 502, code: 'LLM_INVALID_JSON', context: { details: { reason: lastError?.message || 'no matching JSON object', preview: lastPreview || '' } } },
+);
+
+/** Compact `[id] name — descriptor` roster of a universe's canon, per kind. */
+export function renderCanonRoster(universe) {
+ const sections = [];
+ for (const { field, header } of CANON_KINDS) {
+ const entries = Array.isArray(universe?.[field]) ? universe[field] : [];
+ if (!entries.length) continue;
+ const lines = entries.map((e) => {
+ const desc = e.physicalDescription || e.description || e.significance || e.slugline || '';
+ const role = e.role ? ` [${safe(e.role)}]` : '';
+ return ` - [${e.id}] ${safe(e.name || e.slugline || '(unnamed)')}${role}${desc ? `: ${truncDesc(safe(desc))}` : ''}`;
+ });
+ sections.push(`${header}:\n${lines.join('\n')}`);
+ }
+ return sections.join('\n');
+}
+
+const canonIndex = (universe) => {
+ const map = new Map();
+ for (const { field, kind } of CANON_KINDS) {
+ for (const e of (Array.isArray(universe?.[field]) ? universe[field] : [])) {
+ if (e?.id) map.set(String(e.id), { kind, id: String(e.id), name: safe(e.name || e.slugline || '') });
+ }
+ }
+ return map;
+};
+
+const rosterLine = (card) => {
+ const canon = card.canonRef?.name ? ` → ${safe(card.canonRef.name)} (${card.canonRef.kind})` : '';
+ const motif = card.motif ? ` — traditional motif: ${safe(card.motif)}` : '';
+ return ` - ${card.key}: ${safe(card.name)}${canon}${motif}`;
+};
+
+const deckContext = (deck) => {
+ const embrace = Array.isArray(deck.influences?.embrace) ? deck.influences.embrace : [];
+ const lines = [
+ `DECK: "${safe(deck.name)}" (${DECK_KIND_LABELS[deck.kind] || deck.kind})`,
+ deck.description ? `CONCEPT: ${safe(deck.description)}` : '',
+ deck.styleNotes ? `ART DIRECTION: ${safe(deck.styleNotes)}` : '',
+ embrace.length ? `STYLE TOKENS (prepended automatically at render time): ${safe(embrace.join(', '))}` : '',
+ deck.layoutPrompt ? `SHARED LAYOUT (also prepended automatically): ${safe(deck.layoutPrompt)}` : '',
+ ].filter(Boolean);
+ return `# Deck\n${lines.join('\n')}\n`;
+};
+
+export function buildCastPrompt({ deck, cards, universe }) {
+ const universeBlock = buildUniverseStyleContext(universe, {
+ includePremise: true, includeEmbrace: false, escape: true, headerSuffix: 'the deck illustrates this universe',
+ });
+ const kindRules = deck.kind === DECK_KIND.TAROT
+ ? '- Major arcana take the universe\'s most significant figures, places and turning points; court cards (Page/Knight/Queen/King) take secondary characters; numbered pips may take objects or places, or stay unassigned.'
+ : '- Court cards (Jack/Queen/King) and Aces take characters; Jokers take tricksters or outsiders; numbered pips may take objects or places, or stay unassigned.';
+ return `You are casting a ${DECK_KIND_LABELS[deck.kind] || deck.kind} deck from a fictional universe's canon. Decide which canon entry, if any, each card should depict.
+${deckContext(deck)}${universeBlock}
+# Canon (assign by the bracketed id)
+${renderCanonRoster(universe) || '(no canon entries)'}
+
+# Cards
+${cards.map(rosterLine).join('\n')}
+
+# Output contract
+Return a SINGLE JSON object: { "assignments": [ { "key": "<card key>", "id": "<canon id or null>", "why": "<one short clause>" } ] } — one entry per card listed above.
+
+# Rules
+${kindRules}
+- Match a card's traditional meaning or rank to the entry's role in the story; never assign the same character to two cards unless the deck has more court slots than characters.
+- The card back ("back") is never assigned.
+- "id" must be one of the bracketed ids above, or null. Output JUST the JSON object — no markdown, no commentary.`;
+}
+
+export function buildCardPromptsPrompt({ deck, roster, targets, universe }) {
+ const universeBlock = universe
+ ? `${buildUniverseStyleContext(universe, { includePremise: true, includeEmbrace: false, escape: true, headerSuffix: 'the deck illustrates this universe' })}\n# Canon this deck draws on\n${renderCanonRoster(universe) || '(none)'}\n`
+ : '';
+ const kindRules = deck.kind === DECK_KIND.TAROT
+ ? '- Keep each card recognizable as its tarot archetype (use the traditional motif as the skeleton) while dressing it in the deck\'s world; numbered pips show that many of the suit\'s emblem arranged meaningfully.'
+ : '- Face cards show a full figure; numbered cards arrange that many suit pips into a scene or emblem; Aces are a single large ornate pip; Jokers are jesters of this world.';
+ return `You are a prompt engineer writing image-generation prompts for the cards of a ${DECK_KIND_LABELS[deck.kind] || deck.kind} deck.
+${deckContext(deck)}${universeBlock}
+# Full roster (for consistency — "→" marks a canon entry already cast on that card)
+${roster.map(rosterLine).join('\n')}
+
+# Write prompts for THESE cards only
+${targets.map((c) => ` - ${c.key}: ${safe(c.name)}${c.canonRef?.name ? ` → depict ${safe(c.canonRef.name)} (${c.canonRef.kind})` : ''}`).join('\n')}
+
+# Output contract
+Return a SINGLE JSON object: { "prompts": [ { "key": "<card key>", "prompt": "<string, max 600 chars>" } ] } — exactly one entry per card in the list above.
+
+# Rules
+- "prompt" describes the SUBJECT of the card only — figures, pose, setting, symbols, composition, the suit emblem count — as comma-separated renderable phrases. The deck's style tokens and shared layout are prepended automatically at render time, so do NOT repeat style, medium, palette, border or index/title instructions.
+${kindRules}
+- When a card is cast with a canon entry, depict that entry faithfully to its description; otherwise invent a subject that belongs in this deck's world.
+- Cards of one suit should share a visual through-line (a recurring emblem, setting or color accent) so the suit reads as a family.
+- No text instructions, no camera jargon. Never use double-quote characters inside a prompt string.
+- Output JUST the JSON object — no markdown, no commentary.`;
+}
+
+const STRICT_JSON_REMINDER = '\n\n# Your previous reply was not valid JSON. Reply with ONLY the JSON object, with every string in double quotes and no double-quote characters inside any string.';
+
+/**
+ * The runner's Tier-2 hooks (`responseSchema` + `repair`, issue #2350): on a
+ * response that misses the shape, first the deterministic extraction, then the
+ * caller's own salvage; on a request re-issue, the strict-JSON reminder. The
+ * runner owns the single re-request and the Tier-3 provider fallback.
+ */
+const jsonRepair = ({ shapePredicate, salvage }) => ({ phase, text, prompt }) => {
+ if (phase === 'request') return { prompt: `${prompt}${STRICT_JSON_REMINDER}` };
+ const { value } = extractJson(text || '', { shapePredicate });
+ const recovered = value !== undefined ? value : salvage?.(text || '');
+ return recovered ? { text: JSON.stringify(recovered) } : null;
+};
+
+/**
+ * Salvage `{ key, prompt }` pairs from a reply whose JSON is structurally
+ * broken — the observed failure is a model dropping the "prompt" key
+ * (`"key":"wands-ace":"a single…"`) or leaving a raw double quote inside a
+ * prompt. A card prompt is prose, so pairing each key with the string that
+ * follows it recovers every card the model actually wrote. Returns null when
+ * nothing pairs, so the caller falls through to the retry.
+ */
+export function salvagePromptPairs(text) {
+ if (typeof text !== 'string') return null;
+ const pairs = [];
+ const re = /"key"\s*:\s*"([^"\n]+)"\s*[,:]\s*(?:"prompt"\s*:\s*)?"((?:[^"\\]|\\.)*)"/g;
+ for (const m of text.matchAll(re)) pairs.push({ key: m[1], prompt: m[2].replace(/\\"/g, '"') });
+ return pairs.length ? { prompts: pairs } : null;
+}
+
+const runJson = async ({ provider, selectedModel, effort, prompt, source, shapePredicate, what, salvage = null }) => {
+ const { runPromptThroughProvider } = await promptRunner();
+ let result;
+ try {
+ result = await runPromptThroughProvider({
+ provider, model: selectedModel, effort: effort || undefined, prompt, source,
+ responseSchema: shapePredicate,
+ repair: jsonRepair({ shapePredicate, salvage }),
+ });
+ } catch (err) {
+ if (err?.schemaFailure) throw invalidJson(what, { lastError: err, lastPreview: '' });
+ throw err;
+ }
+ const extracted = extractJson(result.text || '', { shapePredicate });
+ if (extracted.value === undefined) throw invalidJson(what, extracted);
+ return { value: extracted.value, llm: { provider: result.provider?.id || provider.id, model: result.model || null } };
+};
+
+/**
+ * @returns {Promise<{ assignments: [{ cardId, canonRef }], llm }>}
+ */
+export async function castDeckFromUniverse({ deck, cards, universe, providerId, model, effort } = {}) {
+ const { resolveProviderAndModel, assertProvider } = await promptRunner();
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, noProvider());
+ const eligible = cards.filter((c) => c.key !== 'back');
+ const { value, llm } = await runJson({
+ provider, selectedModel, effort,
+ prompt: buildCastPrompt({ deck, cards: eligible, universe }),
+ source: 'deck-cast',
+ shapePredicate: (o) => o && Array.isArray(o.assignments),
+ what: 'deck casting',
+ });
+ const index = canonIndex(universe);
+ const byKey = new Map(eligible.map((c) => [c.key, c]));
+ const assignments = [];
+ for (const entry of value.assignments) {
+ const card = byKey.get(String(entry?.key || ''));
+ if (!card) continue;
+ const ref = entry?.id == null ? null : index.get(String(entry.id)) || null;
+ assignments.push({ cardId: card.id, canonRef: ref });
+ }
+ console.log(`🃏 deck cast "${deck.name}": ${assignments.filter((a) => a.canonRef).length}/${eligible.length} cards assigned`);
+ return { assignments, llm };
+}
+
+/**
+ * @returns {Promise<{ prompts: [{ cardId, prompt }], llm }>}
+ */
+export async function generateDeckCardPrompts({ deck, roster, targets, universe = null, providerId, model, effort, onChunk = null } = {}) {
+ const { resolveProviderAndModel, assertProvider } = await promptRunner();
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, noProvider());
+ const prompts = [];
+ let llm = null;
+ for (let i = 0; i < targets.length; i += PROMPTS_PER_CALL) {
+ const chunk = targets.slice(i, i + PROMPTS_PER_CALL);
+ const { value, llm: ran } = await runJson({
+ provider, selectedModel, effort,
+ prompt: buildCardPromptsPrompt({ deck, roster, targets: chunk, universe }),
+ source: 'deck-card-prompts',
+ shapePredicate: (o) => o && Array.isArray(o.prompts),
+ what: 'card prompts',
+ salvage: salvagePromptPairs,
+ });
+ llm = ran;
+ const byKey = new Map(chunk.map((c) => [c.key, c]));
+ const written = [];
+ for (const entry of value.prompts) {
+ const card = byKey.get(String(entry?.key || ''));
+ const prompt = typeof entry?.prompt === 'string' ? entry.prompt.trim().slice(0, DECK_CARD_PROMPT_MAX) : '';
+ if (card && prompt) written.push({ cardId: card.id, prompt });
+ }
+ prompts.push(...written);
+ // Let the caller persist each chunk as it lands.
+ if (onChunk && written.length) await onChunk(written);
+ }
+ console.log(`🃏 deck prompts "${deck.name}": ${prompts.length}/${targets.length} cards written`);
+ return { prompts, llm };
+}
+
+export const __testing = { jsonRepair };
diff --git a/server/services/deckPrompts.test.js b/server/services/deckPrompts.test.js
new file mode 100644
index 0000000000..8c1f00af45
--- /dev/null
+++ b/server/services/deckPrompts.test.js
@@ -0,0 +1,124 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const runPromptThroughProvider = vi.fn();
+vi.mock('./promptRunner.js', () => ({
+ runPromptThroughProvider,
+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'p1', type: 'api' }, selectedModel: 'm1' })),
+ assertProvider: vi.fn(),
+}));
+
+const {
+ castDeckFromUniverse, generateDeckCardPrompts, buildCardPromptsPrompt, PROMPTS_PER_CALL, salvagePromptPairs, __testing,
+} = await import('./deckPrompts.js');
+
+const deck = { name: 'Deck', kind: 'tarot', description: 'A lighthouse deck', styleNotes: 'engraved', influences: { embrace: ['sepia'], avoid: [] }, layoutPrompt: 'Full card' };
+const universe = {
+ logline: 'Keepers vs the swarm',
+ characters: [{ id: 'c1', name: 'The Keeper', role: 'protagonist', physicalDescription: 'weathered, lantern in hand' }],
+ places: [{ id: 'pl1', name: 'The Lighthouse', description: 'a tower on a crag' }],
+ objects: [{ id: 'o1', name: 'The Lens', significance: 'focuses the beam' }],
+};
+const cards = [
+ { id: 'id-0', key: 'major-0', name: '0 · The Fool', motif: 'a traveler' },
+ { id: 'id-16', key: 'major-16', name: 'XVI · The Tower', motif: 'lightning' },
+ { id: 'id-back', key: 'back', name: 'Card back' },
+];
+
+describe('castDeckFromUniverse', () => {
+ // Braces matter: a hook that RETURNS the mock hands vitest a "teardown" it
+ // then calls with no arguments.
+ beforeEach(() => { runPromptThroughProvider.mockReset(); });
+
+ it('maps canon ids onto cards, drops unknown ids/keys, and never offers the back', async () => {
+ runPromptThroughProvider.mockResolvedValueOnce({
+ text: '```json\n{"assignments":[{"key":"major-0","id":"c1"},{"key":"major-16","id":"pl1"},{"key":"back","id":"o1"},{"key":"nope","id":"c1"},{"key":"major-16","id":"ghost"}]}\n```',
+ model: 'm1', provider: { id: 'p1' },
+ });
+ const { assignments, llm } = await castDeckFromUniverse({ deck, cards, universe });
+ expect(assignments).toEqual([
+ { cardId: 'id-0', canonRef: { kind: 'character', id: 'c1', name: 'The Keeper' } },
+ { cardId: 'id-16', canonRef: { kind: 'place', id: 'pl1', name: 'The Lighthouse' } },
+ { cardId: 'id-16', canonRef: null },
+ ]);
+ expect(llm).toEqual({ provider: 'p1', model: 'm1' });
+ const prompt = runPromptThroughProvider.mock.calls[0][0];
+ expect(prompt.source).toBe('deck-cast');
+ expect(prompt.prompt).toContain('[c1] The Keeper [protagonist]');
+ expect(prompt.prompt).not.toMatch(/^\s+- back:/m);
+ });
+
+ it('rejects a response with no assignments object as LLM_INVALID_JSON', async () => {
+ runPromptThroughProvider.mockResolvedValueOnce({ text: 'Sure! Here you go.', model: 'm1', provider: { id: 'p1' } });
+ await expect(castDeckFromUniverse({ deck, cards, universe })).rejects.toMatchObject({ code: 'LLM_INVALID_JSON', status: 502 });
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('generateDeckCardPrompts', () => {
+ // Braces matter: a hook that RETURNS the mock hands vitest a "teardown" it
+ // then calls with no arguments.
+ beforeEach(() => { runPromptThroughProvider.mockReset(); });
+
+ it('chunks the targets, keeps the full roster in every call, and drops empty or unknown prompts', async () => {
+ const targets = Array.from({ length: PROMPTS_PER_CALL + 1 }, (_, i) => ({ id: `id-${i}`, key: `k-${i}`, name: `Card ${i}` }));
+ runPromptThroughProvider.mockImplementation(async ({ prompt }) => {
+ // Only the "write these" section names the chunk — the roster above it lists every card.
+ const section = prompt.split('# Write prompts for THESE cards only')[1].split('# Output contract')[0];
+ const keys = [...section.matchAll(/^ {2}- (k-\d+): Card/gm)].map((m) => m[1]);
+ // Echo a prompt for every listed target, plus noise the parser must ignore.
+ const prompts = keys.map((key) => ({ key, prompt: key === 'k-1' ? ' ' : `subject for ${key}` }));
+ prompts.push({ key: 'k-999', prompt: 'stray' });
+ return { text: JSON.stringify({ prompts }), model: 'm1', provider: { id: 'p1' } };
+ });
+ const { prompts } = await generateDeckCardPrompts({ deck, roster: targets, targets, universe: null });
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(2);
+ expect(prompts).toHaveLength(PROMPTS_PER_CALL); // k-1 blank, k-999 unknown
+ expect(prompts.find((p) => p.cardId === 'id-0')).toEqual({ cardId: 'id-0', prompt: 'subject for k-0' });
+ expect(prompts.some((p) => p.cardId === 'id-1')).toBe(false);
+ const secondCall = runPromptThroughProvider.mock.calls[1][0].prompt;
+ expect(secondCall).toContain('k-0: Card 0'); // roster stays complete for consistency
+ expect(runPromptThroughProvider.mock.calls[1][0].source).toBe('deck-card-prompts');
+ });
+
+ it('hands the runner the shape predicate + a repair that appends the strict-JSON reminder and surfaces a schema failure as LLM_INVALID_JSON', async () => {
+ const targets = [{ id: 'id-0', key: 'k-0', name: 'Card 0' }];
+ runPromptThroughProvider.mockResolvedValueOnce({ text: '{"prompts": [{"key": "k-0", "prompt": "fixed"}]}', model: 'm1', provider: { id: 'p1' } });
+ await generateDeckCardPrompts({ deck, roster: targets, targets });
+ const args = runPromptThroughProvider.mock.calls[0][0];
+ expect(args.responseSchema({ prompts: [] })).toBe(true);
+ expect(args.repair({ phase: 'request', prompt: 'P' })).toEqual({ prompt: expect.stringMatching(/^P\n\n# Your previous reply was not valid JSON/) });
+
+ const schemaErr = Object.assign(new Error('bad shape'), { schemaFailure: true });
+ runPromptThroughProvider.mockRejectedValueOnce(schemaErr);
+ await expect(generateDeckCardPrompts({ deck, roster: targets, targets })).rejects.toMatchObject({ code: 'LLM_INVALID_JSON' });
+ runPromptThroughProvider.mockRejectedValueOnce(new Error('transport down'));
+ await expect(generateDeckCardPrompts({ deck, roster: targets, targets })).rejects.toThrow('transport down');
+ });
+
+ it('the response repair extracts clean JSON first and salvages key/prompt pairs from a structurally broken reply', () => {
+ // Observed in the wild: the model dropped the "prompt" key on one entry and
+ // left a raw quote inside another — JSON.parse fails, the prose is intact.
+ const broken = '```json\n{"prompts":[{"key":"k-0","prompt":"a winged herald over the "real experts" crag"},{"key":"k-1":"a single tower thrust up like a wand"}]}\n```';
+ expect(salvagePromptPairs(broken)).toEqual({ prompts: [
+ { key: 'k-0', prompt: 'a winged herald over the ' },
+ { key: 'k-1', prompt: 'a single tower thrust up like a wand' },
+ ] });
+ expect(salvagePromptPairs('no pairs here')).toBeNull();
+ const repair = __testing.jsonRepair({ shapePredicate: (o) => o && Array.isArray(o.prompts), salvage: salvagePromptPairs });
+ expect(JSON.parse(repair({ phase: 'response', text: broken }).text).prompts.map((p) => p.key)).toEqual(['k-0', 'k-1']);
+ expect(repair({ phase: 'response', text: '```json\n{"prompts": [{"key": "k-0", "prompt": "clean"}]}\n```' })).toEqual({ text: '{"prompts":[{"key":"k-0","prompt":"clean"}]}' });
+ expect(repair({ phase: 'response', text: 'nothing usable' })).toBeNull();
+ });
+
+ it('threads the cast canon entry into the prompt and the deck style stays out of the subject', () => {
+ const text = buildCardPromptsPrompt({
+ deck,
+ roster: [{ ...cards[0], canonRef: { kind: 'character', id: 'c1', name: 'The Keeper' } }],
+ targets: [{ ...cards[0], canonRef: { kind: 'character', id: 'c1', name: 'The Keeper' } }],
+ universe,
+ });
+ expect(text).toContain('→ depict The Keeper (character)');
+ expect(text).toContain('STYLE TOKENS (prepended automatically at render time): sepia');
+ expect(text).toContain('do NOT repeat style');
+ });
+});
diff --git a/server/services/deckRender.js b/server/services/deckRender.js
new file mode 100644
index 0000000000..1b262b1f55
--- /dev/null
+++ b/server/services/deckRender.js
@@ -0,0 +1,110 @@
+/**
+ * Deck rendering — queue one image job per card through the shared media
+ * queue, tagged `deckCard` so `deckRenderHook` files the finished gallery
+ * image back onto the card even when no client is watching.
+ *
+ * The backend resolves through the render-target ladder
+ * (`RENDER_TARGET.DECK`): per-request mode → the deck's own `imageMode` /
+ * `imageModelId` pin → Settings → Image Gen "Deck card renders" default →
+ * the install-wide mode. Batch rendering against the synchronous `external`
+ * SD-API backend is rejected up front, as the universe batch renderer does.
+ */
+
+import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from '../lib/generationModes.js';
+import { RENDER_TARGET, recordRenderPin } from '../lib/renderTargets.js';
+import { composeCardRenderPrompt } from '../lib/deckTemplates.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { getDeck, markCardsRenderQueued } from './decks.js';
+
+/**
+ * Select which cards a render request covers: an explicit id list, else every
+ * card; `onlyMissing` drops cards that already have an image. Cards with no
+ * prompt are always skipped — a blank subject would render the layout clause
+ * alone, and the client shows them as "needs a prompt".
+ */
+export function selectCardsToRender(cards, { cardIds, onlyMissing = false } = {}) {
+ const wanted = Array.isArray(cardIds) && cardIds.length ? new Set(cardIds) : null;
+ return cards.filter((card) => {
+ if (wanted && !wanted.has(card.id)) return false;
+ if (!card.prompt) return false;
+ if (onlyMissing && card.imageRefs.length) return false;
+ return true;
+ });
+}
+
+/**
+ * @returns {Promise<{ mode, jobs: [{ cardId, key, jobId }], skipped: number }>}
+ */
+export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mode: requestedMode, model, seed } = {}) {
+ // The queue, settings and image-gen dispatcher load on the first render
+ // request — this module is reached by the route + hook graphs, which never
+ // need them instantiated (server/AGENTS.md "Import scoping").
+ const [
+ { enqueueJob }, { getSettings }, { resolveRenderTargetConfig }, { resolveLocalImageModel }, { resolveImageCleaners },
+ ] = await Promise.all([
+ import('./mediaJobQueue/index.js'), import('./settings.js'), import('./imageGen/cloudProviderConfig.js'),
+ import('./imageGen/prepareParams.js'), import('./imageGen/index.js'),
+ ]);
+ const deck = await getDeck(deckId);
+ const targets = selectCardsToRender(deck.cards, { cardIds, onlyMissing });
+ if (!targets.length) {
+ throw new ServerError('No cards to render — write or generate prompts first.', { status: 400, code: 'DECK_NO_RENDERABLE_CARDS' });
+ }
+
+ const settings = await getSettings();
+ const pin = recordRenderPin(deck);
+ const { mode, cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.DECK, {
+ mode: requestedMode,
+ model,
+ recordMode: pin.mode,
+ recordModel: pin.modelId,
+ fallbackMode: IMAGE_GEN_MODE.EXTERNAL,
+ });
+ if (!QUEUEABLE_IMAGE_MODES.includes(mode)) {
+ throw new ServerError(
+ 'Deck rendering requires a queueable image backend (local, codex, grok or agy) — pin one on the deck or in Settings → Image Gen',
+ { status: 400, code: 'DECK_EXTERNAL_UNSUPPORTED' },
+ );
+ }
+ if (cloud && !cloud.enabled) throw cloud.disabledError;
+ const localModel = mode === IMAGE_GEN_MODE.LOCAL
+ ? resolveLocalImageModel(settings, { modelId: model || pin.modelId || settings.imageGen?.local?.modelId || undefined })
+ : null;
+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
+
+ const jobs = [];
+ const stamps = [];
+ for (const card of targets) {
+ const { prompt, negativePrompt } = composeCardRenderPrompt(deck, card);
+ const base = {
+ prompt,
+ negativePrompt: negativePrompt || undefined,
+ width: deck.cardSize.width,
+ height: deck.cardSize.height,
+ ...(seed != null ? { seed } : {}),
+ cleanC2PA,
+ denoise,
+ // Destination tag the completion hook files the render by.
+ deckCard: { deckId: deck.id, cardId: card.id, key: card.key },
+ };
+ const params = cloud
+ ? { ...cloud.jobParams, ...base }
+ : {
+ mode,
+ pythonPath: localModel?.pythonPath || null,
+ ...(localModel?.selectedModel?.id ? { modelId: localModel.selectedModel.id } : {}),
+ ...base,
+ };
+ const { jobId } = enqueueJob({ kind: 'image', params, owner: 'decks' });
+ jobs.push({ cardId: card.id, key: card.key, jobId });
+ stamps.push({ cardId: card.id, render: {
+ jobId, status: 'queued', queuedAt: new Date().toISOString(), mode,
+ model: cloud?.modelId || localModel?.selectedModel?.id || null, error: null,
+ } });
+ }
+ // One statement for the whole batch; a job the hook already filed keeps its
+ // completed record (the stamp skips a matching jobId).
+ await markCardsRenderQueued(deck.id, stamps);
+ console.log(`🃏 deck render "${deck.name}": ${jobs.length} card(s) queued mode=${mode}`);
+ return { mode, jobs, skipped: deck.cards.length - targets.length };
+}
diff --git a/server/services/deckRender.test.js b/server/services/deckRender.test.js
new file mode 100644
index 0000000000..3679899230
--- /dev/null
+++ b/server/services/deckRender.test.js
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const enqueueJob = vi.fn(() => ({ jobId: 'job-1', position: 1, status: 'queued' }));
+const getSettings = vi.fn();
+const getDeck = vi.fn();
+const markCardsRenderQueued = vi.fn(async () => ({}));
+vi.mock('./mediaJobQueue/index.js', () => ({ enqueueJob }));
+vi.mock('./settings.js', () => ({ getSettings }));
+vi.mock('./decks.js', () => ({ getDeck, markCardsRenderQueued }));
+vi.mock('./imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));
+vi.mock('./imageGen/prepareParams.js', () => ({
+ resolveLocalImageModel: vi.fn(() => ({ pythonPath: '/py', selectedModel: { id: 'flux2-klein-4b' } })),
+}));
+const resolveRenderTargetConfig = vi.fn();
+vi.mock('./imageGen/cloudProviderConfig.js', () => ({ resolveRenderTargetConfig }));
+
+const { renderDeckCards, selectCardsToRender } = await import('./deckRender.js');
+
+const cards = [
+ { id: 'a', key: 'spades-A', name: 'Ace of Spades', prompt: 'one spade', negativePrompt: '', imageRefs: [] },
+ { id: 'b', key: 'spades-2', name: 'Two of Spades', prompt: 'two spades', negativePrompt: 'text', imageRefs: ['done.png'] },
+ { id: 'c', key: 'spades-3', name: 'Three of Spades', prompt: '', negativePrompt: '', imageRefs: [] },
+];
+const deck = {
+ id: 'd1', name: 'Deck', kind: 'playing', imageMode: null, imageModelId: null,
+ influences: { embrace: ['engraving'], avoid: ['blurry'] }, layoutPrompt: 'Full card',
+ cardSize: { width: 1024, height: 1536 }, cards,
+};
+
+describe('selectCardsToRender', () => {
+ it('always skips prompt-less cards, honors an id list, and onlyMissing drops rendered cards', () => {
+ expect(selectCardsToRender(cards).map((c) => c.id)).toEqual(['a', 'b']);
+ expect(selectCardsToRender(cards, { onlyMissing: true }).map((c) => c.id)).toEqual(['a']);
+ expect(selectCardsToRender(cards, { cardIds: ['b', 'c'] }).map((c) => c.id)).toEqual(['b']);
+ });
+});
+
+describe('renderDeckCards', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getDeck.mockResolvedValue(deck);
+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', local: { pythonPath: '/py' } } });
+ });
+
+ it('rejects a non-queueable backend before touching the queue', async () => {
+ resolveRenderTargetConfig.mockReturnValue({ mode: 'external', cloud: null });
+ await expect(renderDeckCards('d1', {})).rejects.toMatchObject({ code: 'DECK_EXTERNAL_UNSUPPORTED', status: 400 });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('queues one tagged local job per renderable card with the composed prompt and stamps the card', async () => {
+ resolveRenderTargetConfig.mockReturnValue({ mode: 'local', cloud: null });
+ const result = await renderDeckCards('d1', { onlyMissing: true, seed: 7 });
+ expect(resolveRenderTargetConfig).toHaveBeenCalledWith(expect.anything(), 'deck', expect.objectContaining({ recordMode: null, fallbackMode: 'external' }));
+ expect(result).toEqual({ mode: 'local', jobs: [{ cardId: 'a', key: 'spades-A', jobId: 'job-1' }], skipped: 2 });
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ const { kind, params, owner } = enqueueJob.mock.calls[0][0];
+ expect(kind).toBe('image');
+ expect(owner).toBe('decks');
+ expect(params).toMatchObject({
+ mode: 'local', pythonPath: '/py', modelId: 'flux2-klein-4b', width: 1024, height: 1536, seed: 7,
+ prompt: 'engraving. Full card. Ace of Spades: one spade', negativePrompt: 'blurry',
+ deckCard: { deckId: 'd1', cardId: 'a', key: 'spades-A' },
+ });
+ expect(markCardsRenderQueued).toHaveBeenCalledTimes(1);
+ expect(markCardsRenderQueued).toHaveBeenCalledWith('d1', [{ cardId: 'a', render: expect.objectContaining({ jobId: 'job-1', status: 'queued', mode: 'local', model: 'flux2-klein-4b' }) }]);
+ });
+
+ it('spreads the cloud job params under the card params and threads the resolved model', async () => {
+ resolveRenderTargetConfig.mockReturnValue({ mode: 'codex', cloud: { enabled: true, modelId: 'gpt-image-2', jobParams: { mode: 'codex', model: 'gpt-image-2', effort: 'high' } } });
+ await renderDeckCards('d1', { cardIds: ['b'] });
+ const { params } = enqueueJob.mock.calls[0][0];
+ expect(params).toMatchObject({ mode: 'codex', model: 'gpt-image-2', effort: 'high', negativePrompt: 'text, blurry', deckCard: { cardId: 'b' } });
+ expect(params.pythonPath).toBeUndefined();
+ expect(markCardsRenderQueued.mock.calls[0][1][0].render).toMatchObject({ model: 'gpt-image-2' });
+ });
+
+ it('400s when nothing is renderable instead of queueing an empty batch', async () => {
+ resolveRenderTargetConfig.mockReturnValue({ mode: 'local', cloud: null });
+ await expect(renderDeckCards('d1', { cardIds: ['c'] })).rejects.toMatchObject({ code: 'DECK_NO_RENDERABLE_CARDS' });
+ });
+});
diff --git a/server/services/deckRenderHook.js b/server/services/deckRenderHook.js
new file mode 100644
index 0000000000..0bc2254141
--- /dev/null
+++ b/server/services/deckRenderHook.js
@@ -0,0 +1,54 @@
+/**
+ * Deck card render hook — files a completed `deckCard`-tagged image job onto
+ * its card (append to `imageRefs`, promote to primary, clear the in-flight
+ * record), serialized per deck and newest-wins per card so a re-render that
+ * finished out of order can't overwrite a newer frame. Runs server-side, so a
+ * slow cloud render still lands after the user navigated away.
+ *
+ * A job that ends without a file (`failed` / `canceled`) is recorded on the
+ * card too, so the persisted status doesn't stay "queued" forever and the
+ * card grid can offer a retry after a reload.
+ *
+ * The deck service (and with it zod + the render-target leaves) is imported
+ * at completion time, not at boot: bootstrap.js reaches this module from
+ * every suite that boots the queue hooks, and none of them need the deck
+ * graph instantiated (server/AGENTS.md "Import scoping").
+ */
+
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
+
+// One shared load: a failed + canceled pair fires in the same tick, and under
+// the test runner two overlapping dynamic imports of one mocked specifier let
+// one of them escape the mock (observed 2026-09-13). A rejected load is
+// forgotten so a transient failure doesn't poison every later event.
+let decksModule = null;
+const decks = () => (decksModule ||= import('./decks.js').catch((err) => { decksModule = null; throw err; }));
+
+const hook = createMediaJobImageHook({
+ label: 'deck card',
+ initLog: '🃏 Deck card render hook initialized',
+ tagKey: 'deckCard',
+ identify: (tag, job) => (tag?.deckId && tag?.cardId
+ ? { deckId: tag.deckId, cardId: tag.cardId, key: tag.key || null, jobId: job?.id || null }
+ : null),
+ serializeKey: ({ deckId }) => deckId,
+ sceneKey: ({ deckId, cardId }) => `${deckId}:${cardId}`,
+ describe: ({ deckId, key }) => `${deckId}/${key}`,
+ attach: async ({ deckId, cardId, filename, jobId }) => {
+ const { attachCardRender } = await decks();
+ return attachCardRender({ deckId, cardId, filename, jobId });
+ },
+ onAttached: ({ deckId, key }, card) => {
+ console.log(`🃏 deck card ${deckId}/${key} ← ${card.primaryImageRef}`);
+ },
+ onTerminal: async ({ deckId, cardId, jobId }, status, job) => {
+ const { markCardRenderTerminal } = await decks();
+ return markCardRenderTerminal(deckId, cardId, { jobId, status, error: job.error || null });
+ },
+});
+
+export function initDeckRenderHook() {
+ hook.init();
+}
+
+export const __testing = hook.__testing;
diff --git a/server/services/deckRenderHook.test.js b/server/services/deckRenderHook.test.js
new file mode 100644
index 0000000000..d438e615cf
--- /dev/null
+++ b/server/services/deckRenderHook.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const attachCardRender = vi.fn(async () => ({ primaryImageRef: 'job-1.png' }));
+const markCardRenderTerminal = vi.fn(async () => null);
+vi.mock('./decks.js', () => ({ attachCardRender, markCardRenderTerminal }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const hook = await import('./deckRenderHook.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+const tick = () => new Promise((r) => setTimeout(r, 20));
+
+const job = (params, { id = 'job-1', filename = 'job-1.png', queuedAt = '2026-01-01T00:00:00.000Z' } = {}) => ({
+ id, kind: 'image', params, queuedAt, result: { filename },
+});
+const tag = { deckId: 'd1', cardId: 'c1', key: 'major-0' };
+
+describe('deckRenderHook', () => {
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initDeckRenderHook();
+ attachCardRender.mockClear();
+ markCardRenderTerminal.mockClear();
+ });
+ afterEach(() => hook.__testing.reset());
+
+ it('files a completed deckCard-tagged image onto its card and ignores untagged jobs', async () => {
+ mediaJobEvents.emit('completed', job({ prompt: 'x' }));
+ mediaJobEvents.emit('completed', job({ deckCard: tag }));
+ await waitFor(() => attachCardRender.mock.calls.length > 0);
+ expect(attachCardRender).toHaveBeenCalledTimes(1);
+ expect(attachCardRender).toHaveBeenCalledWith({ deckId: 'd1', cardId: 'c1', filename: 'job-1.png', jobId: 'job-1' });
+ });
+
+ it('drops an older render that finishes after a newer one for the same card', async () => {
+ mediaJobEvents.emit('completed', job({ deckCard: tag }, { id: 'new', filename: 'new.png', queuedAt: '2026-01-02T00:00:00.000Z' }));
+ await waitFor(() => attachCardRender.mock.calls.length === 1);
+ mediaJobEvents.emit('completed', job({ deckCard: tag }, { id: 'old', filename: 'old.png', queuedAt: '2026-01-01T00:00:00.000Z' }));
+ await tick();
+ expect(attachCardRender).toHaveBeenCalledTimes(1);
+ expect(attachCardRender.mock.calls[0][0].filename).toBe('new.png');
+ });
+
+ it('records a failed or canceled job on the card it was for', async () => {
+ mediaJobEvents.emit('failed', { ...job({ deckCard: tag }), error: 'boom' });
+ mediaJobEvents.emit('canceled', job({ deckCard: tag }, { id: 'job-2' }));
+ await waitFor(() => markCardRenderTerminal.mock.calls.length === 2);
+ expect(markCardRenderTerminal).toHaveBeenNthCalledWith(1, 'd1', 'c1', { jobId: 'job-1', status: 'failed', error: 'boom' });
+ expect(markCardRenderTerminal).toHaveBeenNthCalledWith(2, 'd1', 'c1', { jobId: 'job-2', status: 'canceled', error: null });
+ });
+
+ it('is idempotent across a double init', async () => {
+ hook.initDeckRenderHook();
+ mediaJobEvents.emit('completed', job({ deckCard: tag }));
+ await waitFor(() => attachCardRender.mock.calls.length > 0);
+ await tick();
+ expect(attachCardRender).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/deckStyleAnalysis.js b/server/services/deckStyleAnalysis.js
new file mode 100644
index 0000000000..9eaa1c0268
--- /dev/null
+++ b/server/services/deckStyleAnalysis.js
@@ -0,0 +1,145 @@
+/**
+ * Deck sample analysis — turn one sample design (a poster, another card, a
+ * painting) into a style guide proposal for a card deck.
+ *
+ * Stateless, like the universe art-style reference step
+ * (`universeStyleReference.js`): the vision model sees the gallery image plus
+ * the deck's CURRENT style guide and proposes a complete replacement
+ * (`styleNotes`, `influences`, a kind-specific `layoutPrompt`) along with a
+ * recreation prompt for the sample itself. The client reviews the diff and
+ * persists through `addSample` — nothing is written here.
+ *
+ * Vision is an API-provider capability (the runner only base64-inlines images
+ * on that path), so an API provider is resolved up front and a silent CLI/TUI
+ * fallback that dropped the image is rejected rather than reported as
+ * image-grounded output.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { trimTo } from '../lib/textUtils.js';
+import { DECK_KIND_LABELS, DEFAULT_LAYOUT_PROMPT } from '../lib/deckTemplates.js';
+import { DECK_LAYOUT_PROMPT_MAX, DECK_SAMPLE_PROMPT_MAX, DECK_SAMPLE_TITLE_MAX } from '../lib/deckValidation.js';
+import { STYLE_NOTES_MAX } from '../lib/universeBibleLimits.js';
+import { universeVisualStyleTokens } from '../lib/universeVisualStyle.js';
+
+export function buildDeckSamplePrompt({ deck, title }) {
+ const kindLabel = DECK_KIND_LABELS[deck.kind] || deck.kind;
+ const context = JSON.stringify({
+ deckName: deck.name,
+ deckKind: kindLabel,
+ suppliedTitle: trimTo(title, DECK_SAMPLE_TITLE_MAX) || null,
+ currentStyleNotes: trimTo(deck.styleNotes, STYLE_NOTES_MAX),
+ currentInfluences: universeVisualStyleTokens(deck),
+ currentLayoutPrompt: trimTo(deck.layoutPrompt, DECK_LAYOUT_PROMPT_MAX) || DEFAULT_LAYOUT_PROMPT[deck.kind],
+ });
+ return `Analyze the attached image as a SAMPLE DESIGN for a ${kindLabel} deck called "${deck.name}". Every card in the deck must read as one physical object printed in this visual language.
+
+Concentrate on renderable visual style: medium and finish (engraving, gouache, risograph, foil, letterpress…), line and brush treatment, palette (name the dominant colors and the paper/ground tone), lighting, texture, ornament and border language, typographic feel, era and mood. Also decide how a single CARD in this style should be laid out — border/frame treatment, where indices or titles sit, how much of the face the central illustration fills. Do not invent story facts or named characters, and do not attribute the style to a copyrighted living artist.
+
+Current deck context:
+${context}
+
+Return JSON only:
+{
+ "title": "short descriptive sample title (generate only when suppliedTitle is null)",
+ "prompt": "detailed image-generation prompt that would recreate this sample image",
+ "styleNotes": "complete replacement for currentStyleNotes: 2–4 sentences of art direction for the whole deck",
+ "influences": {
+ "embrace": ["complete ordered list of 8–18 comma-free style tokens an image model should lean into"],
+ "avoid": ["complete ordered list of 4–12 tokens for the negative prompt"]
+ },
+ "layoutPrompt": "one sentence describing the shared card layout in this style (border, index/title placement, illustration framing) — keep it usable as a prefix on every card prompt",
+ "rationale": "one concise explanation of the proposed changes"
+}
+
+Preserve useful current guidance that does not conflict with the sample. An empty array is a valid intentional recommendation.`;
+}
+
+/**
+ * @returns {Promise<{ sample, proposed, diff, rationale, llm }>}
+ */
+export async function analyzeDeckSample({ deck, imagePath, imageFilename, title, providerId, model, effort } = {}) {
+ if (!deck?.id || !imagePath || !imageFilename) {
+ throw new ServerError('A deck and a gallery image are required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // Provider resolution + the runner load on the first analysis, not at import.
+ const [{ parseLLMJSON, resolveAPIProvider }, { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider }] = await Promise.all([
+ import('./aiProvider.js'), import('./promptRunner.js'),
+ ]);
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message: 'Analyzing a sample design needs an API-based provider with a vision-capable model. Configure one under Settings → Providers.',
+ code: 'NO_API_PROVIDER',
+ status: 503,
+ });
+ const result = await runPromptThroughProvider({
+ provider,
+ prompt: buildDeckSamplePrompt({ deck, title }),
+ source: 'deck-sample-analysis',
+ model: model || undefined,
+ effort: effort || undefined,
+ screenshots: [imagePath],
+ });
+ const ranProvider = assertVisionRunUsedImages(result, provider);
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text || '');
+ } catch (error) {
+ throw new ServerError(`The vision model returned invalid style analysis: ${error.message}`, {
+ status: 502,
+ code: 'VISION_BAD_JSON',
+ });
+ }
+
+ const samplePrompt = trimTo(parsed?.prompt, DECK_SAMPLE_PROMPT_MAX);
+ if (!samplePrompt) {
+ throw new ServerError('The vision model returned no recreation prompt — try a different model or a clearer image.', {
+ status: 502,
+ code: 'VISION_EMPTY',
+ });
+ }
+ // Lazy: the universe style-reference module drags the universe barrel, which
+ // only this call path needs.
+ const { buildStyleReferenceDiff } = await import('./universeStyleReference.js');
+ const current = {
+ styleNotes: trimTo(deck.styleNotes, STYLE_NOTES_MAX),
+ influences: universeVisualStyleTokens(deck),
+ layoutPrompt: trimTo(deck.layoutPrompt, DECK_LAYOUT_PROMPT_MAX),
+ };
+ // Absent vs present: a list the model omitted keeps the current one; a list
+ // it returned (even empty) is its intentional recommendation.
+ const parsedInfluences = parsed?.influences && typeof parsed.influences === 'object' ? parsed.influences : {};
+ const proposedTokens = universeVisualStyleTokens({ influences: parsedInfluences });
+ const proposed = {
+ styleNotes: typeof parsed?.styleNotes === 'string' ? trimTo(parsed.styleNotes, STYLE_NOTES_MAX) : current.styleNotes,
+ influences: {
+ embrace: Array.isArray(parsedInfluences.embrace) ? proposedTokens.embrace : current.influences.embrace,
+ avoid: Array.isArray(parsedInfluences.avoid) ? proposedTokens.avoid : current.influences.avoid,
+ },
+ layoutPrompt: trimTo(parsed?.layoutPrompt, DECK_LAYOUT_PROMPT_MAX) || current.layoutPrompt,
+ };
+
+ return {
+ sample: {
+ id: `deck-sample-${randomUUID()}`,
+ title: trimTo(title, DECK_SAMPLE_TITLE_MAX) || trimTo(parsed?.title, DECK_SAMPLE_TITLE_MAX) || 'Sample design',
+ prompt: samplePrompt,
+ imageRef: imageFilename,
+ createdAt: new Date().toISOString(),
+ },
+ proposed,
+ diff: {
+ ...buildStyleReferenceDiff(current, proposed),
+ layoutPrompt: {
+ before: current.layoutPrompt,
+ after: proposed.layoutPrompt,
+ changed: current.layoutPrompt !== proposed.layoutPrompt,
+ },
+ },
+ rationale: trimTo(parsed?.rationale, 1000),
+ llm: { provider: ranProvider.id || provider.id, model: result.model || null },
+ };
+}
+
+export const __testing = { buildDeckSamplePrompt };
diff --git a/server/services/decks.js b/server/services/decks.js
new file mode 100644
index 0000000000..75b2967e6c
--- /dev/null
+++ b/server/services/decks.js
@@ -0,0 +1,351 @@
+/**
+ * Decks — db-primary card-deck design projects (playing cards and tarot).
+ *
+ * A deck row holds the style guide (notes + embrace/avoid influences), the
+ * shared layout clause, sample references (gallery images the vision step
+ * analyzed), per-record render/LLM pins and an optional universe link. Each
+ * card is its own `deck_cards` row so a completed render attaches to exactly
+ * one card, serialized by the completion hook per deck. Rendered bytes stay in
+ * the shared gallery (`data/images/`) and are referenced by filename, the same
+ * way universe canon entries carry `imageRefs`.
+ *
+ * Machine-local: decks never federate (root AGENTS.md privacy rule) — a deck
+ * that references a universe carries only that universe's id.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { query, withTransaction, ensureSchema } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { trimTo } from '../lib/textUtils.js';
+import { sanitizeLlmRoutePin } from '../lib/llmRoutePin.js';
+import { universeVisualStyleTokens } from '../lib/universeVisualStyle.js';
+import { DECK_CARD_SIZE, DEFAULT_LAYOUT_PROMPT, deckCardRoster, deckCompletion } from '../lib/deckTemplates.js';
+import { DECK_CARD_IMAGE_REFS_MAX, DECK_SAMPLES_MAX } from '../lib/deckValidation.js';
+import { recordRenderPin } from '../lib/renderTargets.js';
+
+const notFound = (what = 'Deck') => new ServerError(`${what} not found`, {
+ status: 404, code: what === 'Deck' ? 'DECK_NOT_FOUND' : 'DECK_CARD_NOT_FOUND',
+});
+
+const filenames = (values) => (Array.isArray(values) ? values : []).map((v) => trimTo(v)).filter(Boolean);
+
+// ── Projections ──────────────────────────────────────────────────────────────
+
+const projectDeck = (row) => {
+ const d = row.definition && typeof row.definition === 'object' ? row.definition : {};
+ const pin = recordRenderPin(d);
+ return {
+ id: row.id,
+ name: row.name,
+ kind: row.kind,
+ universeId: row.universe_id || null,
+ description: trimTo(d.description),
+ styleNotes: trimTo(d.styleNotes),
+ influences: universeVisualStyleTokens(d),
+ layoutPrompt: trimTo(d.layoutPrompt) || DEFAULT_LAYOUT_PROMPT[row.kind] || '',
+ samples: Array.isArray(d.samples) ? d.samples : [],
+ imageMode: pin.mode,
+ imageModelId: pin.modelId,
+ cardSize: d.cardSize?.width && d.cardSize?.height ? d.cardSize : { ...DECK_CARD_SIZE },
+ promptLlm: sanitizeLlmRoutePin(d.promptLlm),
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+};
+
+const projectCard = (row) => {
+ const d = row.definition && typeof row.definition === 'object' ? row.definition : {};
+ return {
+ id: row.id,
+ deckId: row.deck_id,
+ key: row.key,
+ position: row.position,
+ name: trimTo(d.name),
+ group: trimTo(d.group),
+ groupLabel: trimTo(d.groupLabel),
+ rank: d.rank ?? null,
+ motif: trimTo(d.motif) || null,
+ prompt: trimTo(d.prompt),
+ negativePrompt: trimTo(d.negativePrompt),
+ canonRef: d.canonRef && typeof d.canonRef === 'object' ? d.canonRef : null,
+ imageRefs: filenames(d.imageRefs),
+ primaryImageRef: trimTo(d.primaryImageRef) || null,
+ render: d.render && typeof d.render === 'object' ? d.render : null,
+ updatedAt: row.updated_at,
+ };
+};
+
+// ── Reads ────────────────────────────────────────────────────────────────────
+
+const loadCards = async (client, deckId) => {
+ const { rows } = await client.query('SELECT * FROM deck_cards WHERE deck_id = $1 ORDER BY position', [deckId]);
+ return rows.map(projectCard);
+};
+
+export async function listDecks() {
+ await ensureSchema();
+ const { rows } = await query('SELECT * FROM decks ORDER BY updated_at DESC, id');
+ // Completion reads three card fields; project just those instead of every
+ // card's prompt/history so the index page doesn't pull the whole deck.
+ const { rows: cardRows } = await query(`SELECT deck_id, jsonb_build_object(
+ 'prompt', left(definition->>'prompt', 1), 'imageRefs', COALESCE(definition->'imageRefs', '[]'::jsonb), 'render', definition->'render'
+ ) AS definition FROM deck_cards`);
+ const byDeck = Map.groupBy(cardRows, (r) => r.deck_id);
+ return rows.map((row) => ({
+ ...projectDeck(row),
+ completion: deckCompletion((byDeck.get(row.id) || []).map((r) => r.definition)),
+ }));
+}
+
+export async function getDeck(id) {
+ await ensureSchema();
+ const { rows } = await query('SELECT * FROM decks WHERE id = $1', [id]);
+ if (!rows[0]) throw notFound();
+ const cards = await loadCards({ query }, id);
+ return { ...projectDeck(rows[0]), cards, completion: deckCompletion(cards) };
+}
+
+// ── Write helpers ────────────────────────────────────────────────────────────
+
+/**
+ * Read-mutate-write one deck's definition inside a transaction. `mutate(d, row)`
+ * edits the definition copy and may return `{ name, universeId }` column
+ * overrides. Resolves with the fresh deck.
+ */
+async function patchDeck(id, mutate) {
+ await ensureSchema();
+ await withTransaction(async (client) => {
+ const { rows } = await client.query('SELECT * FROM decks WHERE id = $1', [id]);
+ if (!rows[0]) throw notFound();
+ const d = { ...(rows[0].definition || {}) };
+ const columns = (await mutate(d, rows[0])) || {};
+ await client.query(
+ 'UPDATE decks SET name = $2, universe_id = $3, definition = $4, updated_at = NOW() WHERE id = $1',
+ [id, columns.name ?? rows[0].name, columns.universeId === undefined ? rows[0].universe_id : columns.universeId, d],
+ );
+ });
+ return getDeck(id);
+}
+
+/**
+ * Read-mutate-write one card's definition. `mutate(d)` edits the copy and
+ * returns false to skip the write. Resolves with the projected card, or null
+ * when the card is gone / the write was skipped and `missingOk` is set (the
+ * completion hook's contract: never throw on a card that vanished).
+ */
+async function patchCard(deckId, cardId, mutate, { missingOk = false, touch = true } = {}) {
+ await ensureSchema();
+ return withTransaction(async (client) => {
+ const { rows } = await client.query('SELECT * FROM deck_cards WHERE deck_id = $1 AND id = $2', [deckId, cardId]);
+ if (!rows[0]) {
+ if (missingOk) return null;
+ throw notFound('Card');
+ }
+ const d = { ...(rows[0].definition || {}) };
+ if (mutate(d) === false) return null;
+ const { rows: written } = await client.query(
+ 'UPDATE deck_cards SET definition = $2, updated_at = NOW() WHERE id = $1 RETURNING *', [cardId, d],
+ );
+ if (touch) await client.query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);
+ return projectCard(written[0]);
+ });
+}
+
+// ── Deck CRUD ────────────────────────────────────────────────────────────────
+
+/**
+ * Create a deck and mint its full card roster. When a universe is linked and
+ * `seedStyleFromUniverse` is on, the universe's influences + style notes seed
+ * the deck's style guide (the deck then evolves independently — a sample
+ * analysis or manual edit never writes back to the universe).
+ */
+export async function createDeck({ name, kind, description = '', universeId = null, seedStyleFromUniverse = true } = {}) {
+ await ensureSchema();
+ let seeded = { styleNotes: '', influences: { embrace: [], avoid: [] } };
+ if (universeId) {
+ // Lazy: the universe barrel is heavy and only a linked deck needs it.
+ const { getUniverse } = await import('./universeBuilder.js');
+ const universe = await getUniverse(universeId).catch(() => null);
+ if (!universe) {
+ throw new ServerError(`Universe not found: ${universeId}`, { status: 400, code: 'DECK_UNIVERSE_NOT_FOUND' });
+ }
+ if (seedStyleFromUniverse) {
+ seeded = { styleNotes: trimTo(universe.styleNotes), influences: universeVisualStyleTokens(universe) };
+ }
+ }
+ const id = randomUUID();
+ const definition = {
+ description: trimTo(description),
+ ...seeded,
+ layoutPrompt: DEFAULT_LAYOUT_PROMPT[kind],
+ samples: [],
+ cardSize: { ...DECK_CARD_SIZE },
+ };
+ const roster = deckCardRoster(kind);
+ await withTransaction(async (client) => {
+ await client.query(
+ 'INSERT INTO decks (id, name, kind, universe_id, definition) VALUES ($1, $2, $3, $4, $5)',
+ [id, trimTo(name), kind, universeId || null, definition],
+ );
+ await client.query(
+ `INSERT INTO deck_cards (id, deck_id, position, key, definition)
+ SELECT v.id, $1, v.position, v.key, v.definition
+ FROM unnest($2::uuid[], $3::int[], $4::text[], $5::jsonb[]) AS v(id, position, key, definition)`,
+ [
+ id,
+ roster.map(() => randomUUID()),
+ roster.map((_, i) => i),
+ roster.map((c) => c.key),
+ roster.map((c) => ({
+ name: c.name, group: c.group, groupLabel: c.groupLabel, rank: c.rank, motif: c.motif,
+ prompt: '', negativePrompt: '', imageRefs: [],
+ })),
+ ],
+ );
+ });
+ console.log(`🃏 deck created "${trimTo(name)}" kind=${kind} cards=${roster.length}${universeId ? ` universe=${universeId}` : ''}`);
+ return getDeck(id);
+}
+
+/**
+ * Patch deck-level fields. Absent keys preserve; a present key applies (so
+ * `universeId: null` unlinks and `imageMode: null` clears the pin — the
+ * absent-vs-empty rule from root AGENTS.md).
+ */
+export function updateDeck(id, patch = {}) {
+ return patchDeck(id, (d) => {
+ if (patch.description !== undefined) d.description = trimTo(patch.description);
+ if (patch.styleNotes !== undefined) d.styleNotes = trimTo(patch.styleNotes);
+ if (patch.influences !== undefined) d.influences = universeVisualStyleTokens({ influences: patch.influences });
+ if (patch.layoutPrompt !== undefined) d.layoutPrompt = trimTo(patch.layoutPrompt);
+ if (patch.imageMode !== undefined) d.imageMode = patch.imageMode || null;
+ if (patch.imageModelId !== undefined) d.imageModelId = patch.imageModelId || null;
+ if (patch.cardSize !== undefined) d.cardSize = { width: patch.cardSize.width, height: patch.cardSize.height };
+ if (patch.promptLlm !== undefined) d.promptLlm = sanitizeLlmRoutePin(patch.promptLlm);
+ return {
+ ...(patch.name !== undefined ? { name: trimTo(patch.name) } : {}),
+ ...(patch.universeId !== undefined ? { universeId: patch.universeId || null } : {}),
+ };
+ });
+}
+
+export async function deleteDeck(id) {
+ await ensureSchema();
+ const { rowCount } = await query('DELETE FROM decks WHERE id = $1', [id]);
+ if (!rowCount) throw notFound();
+ console.log(`🃏 deck deleted ${id}`);
+ return { ok: true };
+}
+
+// ── Cards ────────────────────────────────────────────────────────────────────
+
+/** Patch one card's authored fields (prompt, negative, name, refs, canon link). */
+export function updateCard(deckId, cardId, patch = {}) {
+ return patchCard(deckId, cardId, (d) => {
+ if (patch.name !== undefined) d.name = trimTo(patch.name);
+ if (patch.prompt !== undefined) { d.prompt = trimTo(patch.prompt); d.promptSource = 'edited'; }
+ if (patch.negativePrompt !== undefined) d.negativePrompt = trimTo(patch.negativePrompt);
+ if (patch.canonRef !== undefined) d.canonRef = patch.canonRef || null;
+ if (patch.imageRefs !== undefined) d.imageRefs = filenames(patch.imageRefs).slice(-DECK_CARD_IMAGE_REFS_MAX);
+ if (patch.primaryImageRef !== undefined) d.primaryImageRef = patch.primaryImageRef || null;
+ // A primary that no longer exists in the history falls back to the latest.
+ if (d.primaryImageRef && !filenames(d.imageRefs).includes(d.primaryImageRef)) d.primaryImageRef = null;
+ });
+}
+
+/**
+ * Bulk-apply generated prompts / canon assignments. `entries` is
+ * `[{ cardId, prompt?, canonRef? }]`; a card whose id is unknown is skipped
+ * (the deck may have been edited between generation and apply).
+ */
+export async function applyCardGenerations(deckId, entries = []) {
+ let applied = 0;
+ for (const entry of entries) {
+ const card = await patchCard(deckId, entry.cardId, (d) => {
+ if (entry.prompt !== undefined) { d.prompt = trimTo(entry.prompt); d.promptSource = 'generated'; }
+ if (entry.canonRef !== undefined) d.canonRef = entry.canonRef || null;
+ }, { missingOk: true, touch: false });
+ if (card) applied += 1;
+ }
+ if (applied) await query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);
+ return applied;
+}
+
+/**
+ * Stamp freshly queued renders onto their cards in one statement:
+ * `entries` is `[{ cardId, render }]`. A card the completion hook already
+ * filed for the SAME job (a backend that finished before the stamp landed)
+ * keeps its completed record — the queued stamp must not regress it.
+ */
+export async function markCardsRenderQueued(deckId, entries = []) {
+ if (!entries.length) return;
+ await ensureSchema();
+ const stampedAt = new Date().toISOString();
+ await query(
+ `UPDATE deck_cards c
+ SET definition = c.definition || jsonb_build_object('render', v.render), updated_at = NOW()
+ FROM unnest($2::uuid[], $3::jsonb[]) AS v(id, render)
+ WHERE c.deck_id = $1 AND c.id = v.id
+ AND COALESCE(c.definition->'render'->>'jobId', '') <> v.render->>'jobId'`,
+ [deckId, entries.map((e) => e.cardId), entries.map((e) => ({ ...e.render, updatedAt: stampedAt }))],
+ );
+}
+
+/**
+ * Terminal state for a render that never produced a file. Only the job the
+ * card is currently waiting on may flip it — a stale failure event for a
+ * superseded job must not mark a newer queued render as failed.
+ */
+export function markCardRenderTerminal(deckId, cardId, { jobId, status, error = null }) {
+ return patchCard(deckId, cardId, (d) => {
+ if (!d.render || d.render.jobId !== jobId) return false;
+ d.render = { ...d.render, status, error: error || null, updatedAt: new Date().toISOString() };
+ }, { missingOk: true, touch: false });
+}
+
+/**
+ * Attach a completed render to its card (called by the completion hook):
+ * append the gallery filename, promote it to primary, clear the in-flight
+ * record. Returns the card, or null when the card no longer exists.
+ */
+export function attachCardRender({ deckId, cardId, filename, jobId }) {
+ return patchCard(deckId, cardId, (d) => {
+ d.imageRefs = [...filenames(d.imageRefs).filter((f) => f !== filename), filename].slice(-DECK_CARD_IMAGE_REFS_MAX);
+ d.primaryImageRef = filename;
+ d.render = { ...(d.render || {}), jobId, status: 'completed', error: null, filename, updatedAt: new Date().toISOString() };
+ }, { missingOk: true });
+}
+
+// ── Samples (style references) ───────────────────────────────────────────────
+
+/**
+ * Persist an analyzed sample; with `adopt`, apply the proposed style guide in
+ * the same transaction so the pair can't half-land. Idempotent on sample id.
+ */
+export function addSample(id, sample, { adopt } = {}) {
+ return patchDeck(id, (d) => {
+ const samples = (Array.isArray(d.samples) ? d.samples : []).filter((s) => s?.id !== sample.id);
+ samples.push({
+ id: sample.id,
+ title: trimTo(sample.title),
+ prompt: trimTo(sample.prompt),
+ imageRef: sample.imageRef,
+ createdAt: sample.createdAt || new Date().toISOString(),
+ });
+ if (samples.length > DECK_SAMPLES_MAX) {
+ throw new ServerError(`A deck holds at most ${DECK_SAMPLES_MAX} samples`, { status: 400, code: 'DECK_SAMPLES_MAX' });
+ }
+ d.samples = samples;
+ if (adopt) {
+ d.styleNotes = trimTo(adopt.styleNotes);
+ d.influences = universeVisualStyleTokens(adopt);
+ if (trimTo(adopt.layoutPrompt)) d.layoutPrompt = trimTo(adopt.layoutPrompt);
+ }
+ });
+}
+
+export function removeSample(id, sampleId) {
+ return patchDeck(id, (d) => {
+ d.samples = (Array.isArray(d.samples) ? d.samples : []).filter((s) => s?.id !== sampleId);
+ });
+}
diff --git a/server/services/mediaJobImageHook.js b/server/services/mediaJobImageHook.js
index 3cfdd37a89..1ac397b36e 100644
--- a/server/services/mediaJobImageHook.js
+++ b/server/services/mediaJobImageHook.js
@@ -44,6 +44,12 @@
* - `onAttached(ctx, result)` — emit the domain event + success log. Only
* called when `attach` resolved to a non-null result that
* was not dropped by the guard.
+ * - `onTerminal(ctx, status, job)` — OPTIONAL; when present the hook also
+ * subscribes to `failed` / `canceled` and calls it for
+ * every tagged job that ended without a result, decoded
+ * through the same `identify` (no `extractResult`, since
+ * there is nothing to extract). Async; a rejection is
+ * logged, never thrown.
*
* The canceled→client-spinner bridge that #1791 also adds is intentionally NOT
* here: every client spinner correlates by media-job id (`generationId`), not by
@@ -72,6 +78,7 @@ export function createMediaJobImageHook(config) {
sceneKey = null,
attach,
onAttached,
+ onTerminal = null,
// Optional: ctx → a short per-record routing string appended to the failure
// log (e.g. `workId/sceneId`), so a "render didn't attach" line is traceable
// to a specific record the way each hand-written hook's log used to be.
@@ -95,23 +102,31 @@ export function createMediaJobImageHook(config) {
const guard = createNewestWinsGuard();
let completedHandler = null;
+ let terminalHandlers = null;
+
+ // The tag → identity half of `decode`, shared with the terminal path (a
+ // failed job carries no result to extract).
+ function identity(job) {
+ if (!job || job.kind !== kind) return null;
+ const tag = job.params?.[tagKey];
+ if (!tag) return null;
+ const id = identify(tag, job);
+ return id ? { ...id, job, tag } : null;
+ }
// Decode the job into the hook's identity context, or null to ignore it, so
// the kind/tag/result guards live in one place (the result fields are pulled
// by the configurable `extractResult`).
function decode(job) {
- if (!job || job.kind !== kind) return null;
- const tag = job.params?.[tagKey];
- if (!tag) return null;
- const identity = identify(tag, job);
- if (!identity) return null;
+ const ctx = identity(job);
+ if (!ctx) return null;
const fields = extractResult(job);
if (!fields) return null;
// Normalize queuedAt once here so the guard below AND any consumer's attach
// (e.g. catalog's portrait guard) read the same `ctx.queuedAt` instead of
// re-deriving it.
const queuedAt = typeof job.queuedAt === 'string' ? job.queuedAt : null;
- return { ...identity, job, tag, ...fields, queuedAt };
+ return { ...ctx, ...fields, queuedAt };
}
function init() {
@@ -154,6 +169,19 @@ export function createMediaJobImageHook(config) {
};
mediaJobEvents.on('completed', completedHandler);
+ if (onTerminal) {
+ const forStatus = (status) => (job) => {
+ const ctx = identity(job);
+ if (!ctx) return;
+ // Outside the request lifecycle: a rejection here has no error middleware.
+ Promise.resolve()
+ .then(() => onTerminal(ctx, status, job))
+ .catch((err) => console.log(`⚠️ ${label} ${status} bookkeeping failed${describe ? ` → ${describe(ctx)}` : ''}: ${err?.message || err}`));
+ };
+ terminalHandlers = { failed: forStatus('failed'), canceled: forStatus('canceled') };
+ mediaJobEvents.on('failed', terminalHandlers.failed);
+ mediaJobEvents.on('canceled', terminalHandlers.canceled);
+ }
console.log(initLog);
}
@@ -165,6 +193,11 @@ export function createMediaJobImageHook(config) {
mediaJobEvents.off('completed', completedHandler);
completedHandler = null;
}
+ if (terminalHandlers) {
+ mediaJobEvents.off('failed', terminalHandlers.failed);
+ mediaJobEvents.off('canceled', terminalHandlers.canceled);
+ terminalHandlers = null;
+ }
serialize.clear();
guard.clear();
},
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 69986e5dfc..60f497b8d9 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -18,7 +18,7 @@ const PARAM_ALLOWLIST = new Set([
'chunks', 'chunkPrompts', 'contextFrames', 'loras',
'cfgScale', 'guidance', 'quantize',
'runId', 'runtime', 'datasetId', 'characterId', 'characterName',
- 'triggerWord', 'rank', 'baseModelId', 'spriteRef', 'spriteWalk',
+ 'triggerWord', 'rank', 'baseModelId', 'spriteRef', 'spriteWalk', 'deckCard',
]);
const MUSIC_STUDIO_KEYS = new Set([
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index eb8185a46e..1007be772f 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -43,6 +43,7 @@ export const DB_TEST_INCLUDE = [
'services/musicVideo/projectsDB.test.js',
'routes/catalog.test.js',
'routes/mindToolRecipes.db.test.js',
+ 'routes/decks.db.test.js',
'scripts/run-db-migrations.test.js',
];