Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: generate N image-gen prompts from a panel/scene fragment (#904)
Adam Eivy408ad9e59b91
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 606eb815de..9542a33648 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- **CyberCity buildings now have real lit-room windows you can look into.** Online towers in the 3D city (CyberCity) render parallax interior-mapped window panes via the [three-fenestra](https://github.com/codedgar/three-fenestra) shader — a `MeshStandardMaterial` that fakes furnished 3D rooms behind flat glass, so as the camera moves you see *into* lit (and unlit) rooms rather than a flat emissive texture. Each building is a single instanced draw call: a deterministic per-pane seed drives the room-cell pick and per-window lit/unlit + warm/cool lighting entirely on the GPU, with the cool tone pulled toward the building's neon accent so windows stay in-family with the scene. The effect is night-only (by day a tower reads as a sunlit solid) and gated to the **high** quality preset and above, so medium/low machines keep the lighter flat-texture facade. (`client/src/components/city/BuildingWindows.jsx`, `client/src/utils/cityInteriorWindows.js`, `client/src/components/city/{Building,Borough}.jsx`)+- **[issue-904] Generate N alternative image-gen prompts from one script fragment.** Comic panels and storyboard scenes already had an *"AI: refine"* button that rewrites a description in place into a single richer image-gen prompt. A new **"AI: N prompts"** action sits alongside it and instead generates several *candidate* prompts from the same fragment — non-destructively. A count picker (1–6) in each stage's toolbar controls how many; the candidates render in a list under the row where you can **Copy** any to the clipboard (to paste into Image Gen) or **Use** one to apply it to the description. Sampling variance across the independent LLM calls yields genuinely different takes on the same beat. Partial failure is tolerated — a few provider hiccups still return the survivors; only an all-failed batch errors. Reuses the existing `pipeline-comic-panel-image-prompt` / `pipeline-storyboard-image-prompt` stage templates (no prompt change, so no migration). New `POST .../panels/:i/image-prompts` and `.../scenes/:i/image-prompts` routes. (`server/services/pipeline/{visualStages,refineHelpers}.js`, `client/src/components/pipeline/{ImagePromptCandidates.jsx,stages/{ComicPagesStage,StoryboardsStage}.jsx}`, #904)+- **Tribe — a relationship manager for rings, care cadence, focus lists, and touchpoints.** A new **Tribe** page (Brain → Tribe, also reachable via ⌘K / voice) lets you organize the people in your life into Dunbar-style rings (Support / Core / Tribe / Village), each with a default check-in cadence; log touchpoints (manual or sourced from a calendar event), track per-person energy/next-move/notes, and link people to Brain memories. People, touchpoints, and memory links live in Postgres (`tribe_people`, `tribe_touchpoints`, `tribe_memory_links`) so they can be joined to Brain memories and carry calendar event references for future scheduling work — provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` (with audit triggers on people/touchpoints), and exercised by route + service tests. The page reconciles live against a `tribe:changed` socket broadcast (covers other tabs/devices) and falls back to a one-shot import of any legacy `localStorage` contacts on first load. New `/api/tribe` routes + service; relationship data is currently machine-local (the tables carry no sync columns). (`server/routes/tribe.js`, `server/services/tribe.js`, `server/lib/db.js`, `server/scripts/init-db.sql`, `client/src/pages/Tribe.jsx`, `client/src/services/apiTribe.js`, #1436)- **[issue-901] Legacy Export — download your whole identity as a portable bundle (server foundation).** A new `POST /api/legacy-export` endpoint gathers your identity across every PortOS domain — digital-twin prompt, autobiography, brain notes, memories, goals + milestones, key decisions, and a health summary — into a single self-contained `.zip` of human-readable Markdown plus machine-readable JSON and a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS running** (plain files, no database), opens with a privacy banner, and degrades gracefully when a domain is empty. Secrets accidentally pasted into notes are redacted before anything leaves the box. `GET /api/legacy-export/preview` reports which sections are present and the estimated size without building the file. This is the server core of the Knowledge Legacy export; PDF rendering and a one-click UI are tracked as follow-ups. (#901)diff --git a/client/src/components/pipeline/ImagePromptCandidates.jsx b/client/src/components/pipeline/ImagePromptCandidates.jsxnew file mode 100644index 0000000000..3c5dbafac5--- /dev/null+++ b/client/src/components/pipeline/ImagePromptCandidates.jsx@@ -0,0 +1,91 @@+/**+ * ImagePromptCandidates — renders the N non-destructive image-gen prompt+ * candidates returned by the panel/scene `image-prompts` endpoints (issue+ * #904). Each candidate can be copied to the clipboard or applied to the+ * source description; applying is the only mutating action and it routes+ * through the caller's `onApply` so the stage owns persistence.+ *+ * Reused by ComicPagesStage (per-panel) and StoryboardsStage (per-scene).+ */+import { Copy, Check, ClipboardCheck, X, Layers } from 'lucide-react';+import { copyToClipboard } from '../../lib/clipboard';+import { IMAGE_PROMPT_COUNT_MAX } from './stages/VisualGenSettings';++// Toolbar control for "how many image-prompt candidates to generate" (issue+// #904). Owns the clamp so both stage toolbars stay in range without+// re-implementing the same min/max/trunc each. `id` must be unique per stage+// (htmlFor pairing).+export function PromptCountInput({ id, value, onChange }) {+ return (+ <label className="inline-flex items-center gap-1.5 text-xs text-gray-400" htmlFor={id}>+ <Layers size={12} />+ Prompts+ <input+ id={id}+ type="number"+ min={1}+ max={IMAGE_PROMPT_COUNT_MAX}+ value={value}+ onChange={(e) => {+ const n = Number(e.target.value);+ if (Number.isFinite(n)) onChange(Math.min(Math.max(Math.trunc(n), 1), IMAGE_PROMPT_COUNT_MAX));+ }}+ title={`How many alternative image-gen prompts the "AI: prompts" button generates (1–${IMAGE_PROMPT_COUNT_MAX})`}+ className="w-12 px-1 py-1 bg-port-bg border border-port-border rounded text-white text-xs text-center"+ />+ </label>+ );+}++export default function ImagePromptCandidates({ candidates, onApply, onDismiss, applyingIndex = null }) {+ if (!Array.isArray(candidates) || candidates.length === 0) return null;+ return (+ <div className="mt-2 p-2 bg-port-bg/60 border border-port-border rounded space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-[10px] uppercase tracking-wider text-gray-500">+ {candidates.length} image-prompt candidate{candidates.length === 1 ? '' : 's'}+ </span>+ {onDismiss ? (+ <button+ type="button"+ onClick={onDismiss}+ className="text-gray-500 hover:text-gray-300 p-0.5"+ aria-label="Dismiss candidates"+ >+ <X size={12} />+ </button>+ ) : null}+ </div>+ <ul className="space-y-2">+ {candidates.map((candidate, i) => (+ <li key={candidate.runId || i} className="flex items-start gap-2 p-2 bg-port-card border border-port-border/60 rounded">+ <span className="text-[10px] text-gray-500 font-mono pt-0.5 w-5 shrink-0">{i + 1}</span>+ <p className="flex-1 text-xs text-gray-200 whitespace-pre-wrap break-words">{candidate.prompt}</p>+ <div className="flex flex-col gap-1 shrink-0">+ <button+ type="button"+ onClick={() => copyToClipboard(candidate.prompt, 'Prompt copied')}+ title="Copy this prompt to the clipboard"+ className="inline-flex items-center justify-center gap-1 px-2 py-1 rounded bg-port-card border border-port-border text-gray-300 text-[11px] hover:border-port-accent/50 hover:text-white"+ >+ <Copy size={11} /> Copy+ </button>+ {onApply ? (+ <button+ type="button"+ onClick={() => onApply(candidate.prompt, i)}+ disabled={applyingIndex !== null}+ title="Replace the description with this prompt"+ className="inline-flex items-center justify-center gap-1 px-2 py-1 rounded bg-port-accent text-white text-[11px] hover:bg-port-accent/90 disabled:opacity-50"+ >+ {applyingIndex === i ? <ClipboardCheck size={11} /> : <Check size={11} />}+ Use+ </button>+ ) : null}+ </div>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/client/src/components/pipeline/ImagePromptCandidates.test.jsx b/client/src/components/pipeline/ImagePromptCandidates.test.jsxnew file mode 100644index 0000000000..4f3401415c--- /dev/null+++ b/client/src/components/pipeline/ImagePromptCandidates.test.jsx@@ -0,0 +1,60 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const copyToClipboardMock = vi.fn(async () => true);+vi.mock('../../lib/clipboard', () => ({+ copyToClipboard: (...a) => copyToClipboardMock(...a),+}));++import ImagePromptCandidates from './ImagePromptCandidates';++const CANDIDATES = [+ { prompt: 'first candidate prompt', changes: [], runId: 'r1' },+ { prompt: 'second candidate prompt', changes: [], runId: 'r2' },+];++beforeEach(() => {+ copyToClipboardMock.mockClear();+});++describe('ImagePromptCandidates', () => {+ it('renders nothing for an empty list', () => {+ const { container } = render(<ImagePromptCandidates candidates={[]} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('renders each candidate prompt and a count header', () => {+ render(<ImagePromptCandidates candidates={CANDIDATES} />);+ expect(screen.getByText('first candidate prompt')).toBeInTheDocument();+ expect(screen.getByText('second candidate prompt')).toBeInTheDocument();+ expect(screen.getByText(/2 image-prompt candidates/i)).toBeInTheDocument();+ });++ it('copies a candidate prompt to the clipboard', async () => {+ render(<ImagePromptCandidates candidates={CANDIDATES} />);+ const copyButtons = screen.getAllByRole('button', { name: /copy/i });+ await userEvent.click(copyButtons[1]);+ expect(copyToClipboardMock).toHaveBeenCalledWith('second candidate prompt', expect.any(String));+ });++ it('calls onApply with the prompt and index when "Use" is clicked', async () => {+ const onApply = vi.fn();+ render(<ImagePromptCandidates candidates={CANDIDATES} onApply={onApply} />);+ const useButtons = screen.getAllByRole('button', { name: /use/i });+ await userEvent.click(useButtons[0]);+ expect(onApply).toHaveBeenCalledWith('first candidate prompt', 0);+ });++ it('omits the Use button when onApply is not provided', () => {+ render(<ImagePromptCandidates candidates={CANDIDATES} />);+ expect(screen.queryByRole('button', { name: /use/i })).not.toBeInTheDocument();+ });++ it('calls onDismiss when the dismiss control is clicked', async () => {+ const onDismiss = vi.fn();+ render(<ImagePromptCandidates candidates={CANDIDATES} onDismiss={onDismiss} />);+ await userEvent.click(screen.getByRole('button', { name: /dismiss candidates/i }));+ expect(onDismiss).toHaveBeenCalled();+ });+});diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsxindex 39be0c07b0..bef2e857b1 100644--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx@@ -1,16 +1,18 @@import { useRef, useState } from 'react';-import { Plus, Trash2, Sparkles, Loader2, Wand2, WandSparkles, ImagePlus } from 'lucide-react';+import { Plus, Trash2, Sparkles, Loader2, Wand2, WandSparkles, ImagePlus, Layers } from 'lucide-react';import toast from '../../ui/Toast';import { useArmedAction } from '../../../hooks/useArmedAction';import {generatePipelineVisualImage,generatePipelineComicPage,refinePipelineComicPanelPrompt,+ generatePipelineComicPanelImagePrompts,updatePipelineIssue,extractPipelineComicPages,} from '../../../services/api';import MediaJobThumb from '../MediaJobThumb';-import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';+import ImagePromptCandidates, { PromptCountInput } from '../ImagePromptCandidates';+import { genConfigToImageOptions, genConfigToRefineOptions, IMAGE_PROMPT_COUNT_DEFAULT } from './VisualGenSettings';// NOTE: `ComicPagesStage` is currently unreachable in the running app —// `PipelineIssue.jsx` redirects /comicPages URLs to /comicScript, where@@ -25,6 +27,12 @@ export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = fconst genConfig = stage.genConfig || null;const [savingIdx, setSavingIdx] = useState(null);const [refiningKey, setRefiningKey] = useState(null);+ // Non-destructive N-candidate image-prompt fan-out (issue #904), keyed by+ // `${pi}:${ni}` so each panel tracks its own in-flight + candidate state.+ const [promptingKey, setPromptingKey] = useState(null);+ const [panelCandidates, setPanelCandidates] = useState({});+ const [promptCount, setPromptCount] = useState(IMAGE_PROMPT_COUNT_DEFAULT);+ const [applyingCandidate, setApplyingCandidate] = useState(null);// Per-page in-flight state. Codex can render multiple pages in parallel, so// tracking a single index would flip the spinner off the wrong button when// the first request finished while a second was still pending.@@ -152,6 +160,50 @@ export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = ftoast.success(`Refined panel ${pi + 1}.${ni + 1}${summary}`);};+ // Generate N non-destructive image-prompt candidates for a panel (issue+ // #904). Never overwrites the description — the user copies or applies one.+ const handleGenerateImagePrompts = async (pi, ni) => {+ const panel = pages[pi]?.panels?.[ni];+ if (!panel?.description?.trim()) {+ toast.error('Add a description first');+ return;+ }+ const key = `${pi}:${ni}`;+ setPromptingKey(key);+ const result = await generatePipelineComicPanelImagePrompts(+ issue.id, pi, ni, { count: promptCount, ...genConfigToRefineOptions(genConfig) },+ ).catch((err) => {+ toast.error(err.message || 'Prompt generation failed');+ return null;+ });+ setPromptingKey(null);+ if (!result) return;+ setPanelCandidates((prev) => ({ ...prev, [key]: result.candidates }));+ toast.success(`Generated ${result.candidates.length} prompt${result.candidates.length === 1 ? '' : 's'} for panel ${pi + 1}.${ni + 1}`);+ };++ const handleApplyCandidate = async (pi, ni, prompt, candidateIndex) => {+ const key = `${pi}:${ni}`;+ setApplyingCandidate(`${key}:${candidateIndex}`);+ const next = pages.map((p, i) => i === pi+ ? { ...p, panels: (p.panels || []).map((q, j) => j === ni ? { ...q, description: prompt } : q) }+ : p);+ await persist(next);+ setApplyingCandidate(null);+ setPanelCandidates((prev) => {+ const rest = { ...prev };+ delete rest[key];+ return rest;+ });+ toast.success(`Applied prompt to panel ${pi + 1}.${ni + 1}`);+ };++ const dismissCandidates = (pi, ni) => setPanelCandidates((prev) => {+ const rest = { ...prev };+ delete rest[`${pi}:${ni}`];+ return rest;+ });+const handleGeneratePanel = async (pi, ni) => {const panel = pages[pi].panels[ni];if (!panel.description?.trim()) {@@ -196,6 +248,7 @@ export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = f{extracting ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}{extractArmed ? 'Click again to replace' : 'From comic script'}</button>+ <PromptCountInput id="comic-prompt-count" value={promptCount} onChange={setPromptCount} /><buttontype="button"onClick={addPage}@@ -247,53 +300,73 @@ export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = f</div><ul className="space-y-2">{(page.panels || []).map((panel, ni) => (- <li key={ni} className="flex items-start gap-2">- <span className="text-xs text-gray-600 mt-2 w-8 shrink-0">P{ni + 1}</span>- <textarea- value={panel.description || ''}- onChange={(e) => updatePanel(pi, ni, { description: e.target.value })}- onBlur={() => persist(pagesRef.current)}- placeholder="Panel subject: wide shot, foundry crucible, dusk light, Lina silhouetted against the glow."- rows={2}- className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"- maxLength={8000}- />- <div className="flex flex-col gap-1 items-stretch w-32">- <button- type="button"- onClick={() => handleRefinePanel(pi, ni)}- disabled={refiningKey !== null || actionsGated}- title={actionsGated ? 'Saving settings…' : 'Elaborate this panel description into a richer image-gen prompt (LLM call — replaces the current text)'}- className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"- >- {refiningKey === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}- AI: refine- </button>+ <li key={ni} className="space-y-2">+ <div className="flex items-start gap-2">+ <span className="text-xs text-gray-600 mt-2 w-8 shrink-0">P{ni + 1}</span>+ <textarea+ value={panel.description || ''}+ onChange={(e) => updatePanel(pi, ni, { description: e.target.value })}+ onBlur={() => persist(pagesRef.current)}+ placeholder="Panel subject: wide shot, foundry crucible, dusk light, Lina silhouetted against the glow."+ rows={2}+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ maxLength={8000}+ />+ <div className="flex flex-col gap-1 items-stretch w-32">+ <button+ type="button"+ onClick={() => handleRefinePanel(pi, ni)}+ disabled={refiningKey !== null || actionsGated}+ title={actionsGated ? 'Saving settings…' : 'Elaborate this panel description into a richer image-gen prompt (LLM call — replaces the current text)'}+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {refiningKey === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}+ AI: refine+ </button>+ <button+ type="button"+ onClick={() => handleGenerateImagePrompts(pi, ni)}+ disabled={promptingKey !== null || actionsGated}+ title={actionsGated ? 'Saving settings…' : `Generate ${promptCount} alternative image-gen prompts without changing the description`}+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {promptingKey === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}+ AI: {promptCount} prompts+ </button>+ <button+ type="button"+ onClick={() => handleGeneratePanel(pi, ni)}+ disabled={savingIdx === `${pi}:${ni}` || actionsGated}+ title={actionsGated ? 'Saving settings…' : undefined}+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"+ >+ {savingIdx === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}+ Image+ </button>+ {panel.imageJobId ? (+ <>+ <MediaJobThumb jobId={panel.imageJobId} label={`Panel ${ni + 1}`} size="sm" />+ <span className="text-[10px] text-gray-500 font-mono break-all">job {panel.imageJobId.slice(0, 8)}</span>+ </>+ ) : null}+ </div><buttontype="button"- onClick={() => handleGeneratePanel(pi, ni)}- disabled={savingIdx === `${pi}:${ni}` || actionsGated}- title={actionsGated ? 'Saving settings…' : undefined}- className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"+ onClick={() => removePanel(pi, ni)}+ className="text-gray-500 hover:text-port-error p-2"+ aria-label="Remove panel">- {savingIdx === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}- Image+ <Trash2 size={14} /></button>- {panel.imageJobId ? (- <>- <MediaJobThumb jobId={panel.imageJobId} label={`Panel ${ni + 1}`} size="sm" />- <span className="text-[10px] text-gray-500 font-mono break-all">job {panel.imageJobId.slice(0, 8)}</span>- </>- ) : null}</div>- <button- type="button"- onClick={() => removePanel(pi, ni)}- className="text-gray-500 hover:text-port-error p-2"- aria-label="Remove panel"- >- <Trash2 size={14} />- </button>+ {panelCandidates[`${pi}:${ni}`] ? (+ <ImagePromptCandidates+ candidates={panelCandidates[`${pi}:${ni}`]}+ applyingIndex={applyingCandidate?.startsWith(`${pi}:${ni}:`) ? Number(applyingCandidate.split(':')[2]) : null}+ onApply={(prompt, ci) => handleApplyCandidate(pi, ni, prompt, ci)}+ onDismiss={() => dismissCandidates(pi, ni)}+ />+ ) : null}</li>))}</ul>diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex d17bd96b77..f2195e51bd 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -17,20 +17,22 @@*/import { useEffect, useMemo, useRef, useState } from 'react';-import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles, Shirt } from 'lucide-react';+import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles, Shirt, Layers } from 'lucide-react';import toast from '../../ui/Toast';import {generatePipelineVisualImage,generatePipelineSceneVideo,generatePipelineShotStartFrame,refinePipelineSceneImagePrompt,+ generatePipelineSceneImagePrompts,updatePipelineIssue,extractPipelineStoryboardScenes,} from '../../../services/api';import useUniverse from '../../../hooks/useUniverse';import { matchCharactersInText } from '../../../lib/scenePrompt';import MediaJobThumb from '../MediaJobThumb';-import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';+import ImagePromptCandidates, { PromptCountInput } from '../ImagePromptCandidates';+import { genConfigToImageOptions, genConfigToRefineOptions, IMAGE_PROMPT_COUNT_DEFAULT } from './VisualGenSettings';export default function StoryboardsStage({ issue, series, onStageUpdate, actionsGated = false }) {const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };@@ -40,6 +42,13 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actionsconst [savingIdx, setSavingIdx] = useState(null);const [renderingVideoIdx, setRenderingVideoIdx] = useState(null);const [refiningIdx, setRefiningIdx] = useState(null);+ // Non-destructive N-candidate image-prompt fan-out (issue #904). Tracks the+ // scene currently generating, the candidates keyed by scene index, the+ // user-chosen count, and which candidate is being applied.+ const [promptingIdx, setPromptingIdx] = useState(null);+ const [sceneCandidates, setSceneCandidates] = useState({});+ const [promptCount, setPromptCount] = useState(IMAGE_PROMPT_COUNT_DEFAULT);+ const [applyingCandidate, setApplyingCandidate] = useState(null);// Active per-shot renders keyed by `${sceneIdx}:${shotIdx}` so multiple// shots can render concurrently with independent spinners. A single ref// would race when the user starts a second render before the first settles.@@ -242,6 +251,48 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actionstoast.success(`Refined scene ${i + 1}${summary}`);};+ // Generate N non-destructive image-prompt candidates for the scene (issue+ // #904). Unlike "AI: refine", this never overwrites the description — the+ // user copies one or clicks "Use" to apply it explicitly.+ const handleGenerateImagePrompts = async (i) => {+ const scene = scenes[i];+ if (!scene.description?.trim()) {+ toast.error('Add a description first');+ return;+ }+ setPromptingIdx(i);+ const result = await generatePipelineSceneImagePrompts(+ issue.id, i, { count: promptCount, ...genConfigToRefineOptions(genConfig) },+ ).catch((err) => {+ toast.error(err.message || 'Prompt generation failed');+ return null;+ });+ setPromptingIdx(null);+ if (!result) return;+ setSceneCandidates((prev) => ({ ...prev, [i]: result.candidates }));+ toast.success(`Generated ${result.candidates.length} prompt${result.candidates.length === 1 ? '' : 's'} for scene ${i + 1}`);+ };++ // Apply one candidate prompt to the scene description (the only mutating+ // path — copy stays clipboard-only). Persists via the shared write queue.+ const handleApplyCandidate = async (i, prompt, candidateIndex) => {+ setApplyingCandidate(`${i}:${candidateIndex}`);+ await persist(scenes.map((s, j) => j === i ? { ...s, description: prompt } : s));+ setApplyingCandidate(null);+ setSceneCandidates((prev) => {+ const next = { ...prev };+ delete next[i];+ return next;+ });+ toast.success(`Applied prompt to scene ${i + 1}`);+ };++ const dismissCandidates = (i) => setSceneCandidates((prev) => {+ const next = { ...prev };+ delete next[i];+ return next;+ });+// Render this one scene as a video clip — independent of the full// episode-video stitch. Server persists sceneVideoJobId on the scene.const handleGenerateVideo = async (i) => {@@ -304,6 +355,7 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions: <Wand2 size={14} />}{extractingFrom === 'arm:prose' ? 'Click again to replace' : 'From prose'}</button>+ <PromptCountInput id="storyboard-prompt-count" value={promptCount} onChange={setPromptCount} /><buttontype="button"onClick={addScene}@@ -359,6 +411,16 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions{refiningIdx === i ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}AI: refine</button>+ <button+ type="button"+ onClick={() => handleGenerateImagePrompts(i)}+ disabled={promptingIdx !== null || actionsGated}+ title={actionsGated ? 'Saving settings…' : `Generate ${promptCount} alternative image-gen prompts without changing the description`}+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {promptingIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}+ AI: {promptCount} prompts+ </button><buttontype="button"onClick={() => handleGenerate(i)}@@ -393,6 +455,14 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions) : null}</div></div>+ {sceneCandidates[i] ? (+ <ImagePromptCandidates+ candidates={sceneCandidates[i]}+ applyingIndex={applyingCandidate?.startsWith(`${i}:`) ? Number(applyingCandidate.split(':')[1]) : null}+ onApply={(prompt, ci) => handleApplyCandidate(i, prompt, ci)}+ onDismiss={() => dismissCandidates(i)}+ />+ ) : null}{wardrobeChars.length > 0 ? (<WardrobePickercharacters={wardrobeChars}diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsxindex afef1a0ee1..e52a7cb0b1 100644--- a/client/src/components/pipeline/stages/VisualGenSettings.jsx+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx@@ -23,6 +23,12 @@ import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../../../lib/imageGenBaimport BackendChipStrip from '../../media/BackendChipStrip';import ProviderModelSelector from '../../ProviderModelSelector';+// Non-destructive image-prompt fan-out (issue #904). MAX mirrors the+// server's IMAGE_PROMPT_CANDIDATE_MAX in refineHelpers.js — keep the two in+// sync so the client never requests a count the server would reject.+export const IMAGE_PROMPT_COUNT_DEFAULT = 3;+export const IMAGE_PROMPT_COUNT_MAX = 6;+const DEFAULT_CONFIG = Object.freeze({imageMode: 'auto',imageModelId: null,diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 00519a5d13..42a1bdaebb 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -345,6 +345,24 @@ export const refinePipelineSceneImagePrompt = (issueId, sceneIndex, opts = {}) =body: JSON.stringify(opts),});+// Non-destructive N-candidate variant of the panel refine: returns+// `count` alternative image-gen prompts WITHOUT mutating the panel+// description (issue #904). Resolves to { candidates, requested, pageIndex,+// panelIndex } where each candidate is { prompt, changes, runId, ... }.+export const generatePipelineComicPanelImagePrompts = (issueId, pageIndex, panelIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/pages/${encodeURIComponent(pageIndex)}/panels/${encodeURIComponent(panelIndex)}/image-prompts`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });++// Non-destructive N-candidate variant for a storyboard scene (issue #904).+// Resolves to { candidates, requested, sceneIndex }.+export const generatePipelineSceneImagePrompts = (issueId, sceneIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/scenes/${encodeURIComponent(sceneIndex)}/image-prompts`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });+// ---- Seasons (Phase 2 of Story Arc Planning) ----export const listPipelineSeasons = (seriesId) =>request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons`);diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex 52c42fd211..c4e4d8ccac 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -25,8 +25,11 @@ import {enqueueStoryboardShotStartFrame,refineComicPanelPrompt,refineStoryboardScenePrompt,+ generateComicPanelImagePrompts,+ generateStoryboardSceneImagePrompts,buildRenderSlot,} from '../../services/pipeline/visualStages.js';+import { IMAGE_PROMPT_CANDIDATE_MAX } from '../../services/pipeline/refineHelpers.js';import {extractCanonFromProse, summarizeCanonExtraction,describeCanonFromProse, summarizeDescribeGaps,@@ -250,6 +253,14 @@ const promptRefineSchema = z.object({model: z.string().trim().max(200).optional(),});+// Same picker plus a `count` for the non-destructive N-candidate fan-out+// (issue #904). `count` is clamped server-side to IMAGE_PROMPT_CANDIDATE_MAX,+// but bound it here too so an out-of-range value is a clean 400 rather than a+// silently-clamped surprise.+const imagePromptsSchema = promptRefineSchema.extend({+ count: z.number().int().min(1).max(IMAGE_PROMPT_CANDIDATE_MAX).optional().default(3),+});+// Source for scene extraction: which text stage to read from (`prose` →// granular paragraph-grain breakdown via `writers-room-script`; `teleplay`// → slugline-grain parse via `pipeline-extract-scenes`). `force` overrides@@ -824,6 +835,22 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/panels/:panelIndex/r}),);+// Non-destructive N-candidate variant: generate `count` alternative image-gen+// prompts for one comic panel without touching the panel description. The+// client lists them and lets the user copy or apply one (issue #904).+router.post('/issues/:id/stages/comicPages/pages/:pageIndex/panels/:panelIndex/image-prompts',+ asyncHandler(async (req, res) => {+ const body = validateRequest(imagePromptsSchema, req.body ?? {});+ const result = await generateComicPanelImagePrompts(+ req.params.id,+ Number(req.params.pageIndex),+ Number(req.params.panelIndex),+ body,+ ).catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }),+);+// AI-driven prompt refinement for a single storyboard scene. Mirror of the// comic-panel refine but uses pipeline-storyboard-image-prompt.router.post('/issues/:id/stages/storyboards/scenes/:index/refine-prompt',@@ -838,6 +865,19 @@ router.post('/issues/:id/stages/storyboards/scenes/:index/refine-prompt',}),);+// Non-destructive N-candidate variant for a storyboard scene (issue #904).+router.post('/issues/:id/stages/storyboards/scenes/:index/image-prompts',+ asyncHandler(async (req, res) => {+ const body = validateRequest(imagePromptsSchema, req.body ?? {});+ const result = await generateStoryboardSceneImagePrompts(+ req.params.id,+ Number(req.params.index),+ body,+ ).catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }),+);+// Render the start-frame image for a single shot inside a storyboard scene.// Shot-level granularity sits parallel to the existing scene-level image// render: a scene either has shots[] (per-shot images) or doesn't (per-scenediff --git a/server/services/pipeline/refineHelpers.js b/server/services/pipeline/refineHelpers.jsindex e671c1a4f3..f47a0cb142 100644--- a/server/services/pipeline/refineHelpers.js+++ b/server/services/pipeline/refineHelpers.js@@ -44,6 +44,50 @@ export function trimChanges(raw, limit = 12) {: [];}+// Upper bound on how many image-prompt candidates a single fan-out request+// may ask for. Each candidate is an independent LLM call, so the cap keeps a+// runaway `count` from spawning dozens of provider hits in one click.+export const IMAGE_PROMPT_CANDIDATE_MAX = 6;++// Fan-out wrapper around `runPromptRefine`: run the same refine template N+// times in parallel and collect the distinct candidate prompts. Sampling+// variance across the independent calls yields N different image-gen prompts+// from one script fragment (issue #904). Partial failure is tolerated — a few+// provider hiccups still return the survivors; only an all-failed batch throws+// (surfacing the first underlying error so the caller sees the real cause).+export async function runImagePromptCandidates({+ count,+ templateName,+ variables,+ options = {},+ source,+ logTag,+}) {+ const n = Math.min(Math.max(Math.trunc(Number(count) || 1), 1), IMAGE_PROMPT_CANDIDATE_MAX);+ const settled = await Promise.allSettled(+ Array.from({ length: n }, () => runPromptRefine({ templateName, variables, options, source })),+ );+ const candidates = [];+ let firstError = null;+ for (const r of settled) {+ if (r.status === 'fulfilled') {+ const { refined, changes, runId, providerId, model } = r.value;+ candidates.push({ prompt: refined, changes, runId, providerId, model });+ } else if (!firstError) {+ firstError = r.reason;+ }+ }+ if (!candidates.length) {+ throw firstError || new ServerError('LLM returned no image-prompt candidates', {+ status: 502, code: 'PIPELINE_IMAGE_PROMPTS_EMPTY',+ });+ }+ if (logTag) {+ console.log(`✨ ${logTag} candidates=${candidates.length}/${n}`);+ }+ return { candidates, requested: n };+}+// Single-field refine wrapper for the comic-panel / storyboard-scene /// character-physicalDescription paths. `resultField` keeps the helper// prompt-agnostic; `changes` are trimmed + capped on the way out.diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 07fbcd8382..0c1d7ee797 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -42,7 +42,7 @@ import { getDefaultVideoModelId, getVideoModels, getImageModels } from '../../liimport { loraCompatKey } from '../../lib/runners.js';import { resolveCharacterLoras } from '../characterLoraResolver.js';import { runStagedLLM } from '../../lib/stageRunner.js';-import { runPromptRefine } from './refineHelpers.js';+import { runPromptRefine, runImagePromptCandidates } from './refineHelpers.js';import { pickCanon } from './seriesCanon.js';import { STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';@@ -1141,12 +1141,11 @@ async function loadRefineContext(issueId) {}-/**- * Run the `pipeline-comic-panel-image-prompt` template against the current- * panel + surrounding context, then persist the refined description on the- * panel. Returns { panel, page, issue, stage, runId, changes, providerId }.- */-export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, options = {}) {+// Validate the page/panel indices, lock, and non-empty description, then+// build the `pipeline-comic-panel-image-prompt` template variables. Shared by+// the 1:1 refine (replaces the description) and the N-candidate fan-out+// (non-destructive) so both feed the LLM identical context.+async function loadComicPanelPromptContext(issueId, pageIndex, panelIndex) {const pi = Number(pageIndex);const ni = Number(panelIndex);if (!Number.isInteger(pi) || pi < 0 || !Number.isInteger(ni) || ni < 0) {@@ -1192,25 +1191,38 @@ export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, opt.join(' / '): '';+ const variables = {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ pageNumber: pi + 1,+ panelNumber: ni + 1,+ panelCount: panels.length,+ description: (panel.description || '').slice(0, 4000),+ caption: (panel.caption || '').slice(0, 1000),+ hasCaption: !!(panel.caption || '').trim(),+ dialogue,+ hasDialogue: !!dialogue,+ sfx: (panel.sfx || '').slice(0, 500),+ hasSfx: !!(panel.sfx || '').trim(),+ hasNeighbors: !!(prev || next),+ previousPanel: neighborText(prev),+ nextPanel: neighborText(next),+ };+ return { issue, pi, ni, pages, page, panels, panel, variables };+}++/**+ * Run the `pipeline-comic-panel-image-prompt` template against the current+ * panel + surrounding context, then persist the refined description on the+ * panel. Returns { panel, page, issue, stage, runId, changes, providerId }.+ */+export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, options = {}) {+ const { pi, ni, pages, page, panels, panel, variables } =+ await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);+const { refined, changes, runId, providerId } = await runPromptRefine({templateName: 'pipeline-comic-panel-image-prompt',- variables: {- series: seriesBibleCtx(series),- issue: issueCtx(issue),- pageNumber: pi + 1,- panelNumber: ni + 1,- panelCount: panels.length,- description: (panel.description || '').slice(0, 4000),- caption: (panel.caption || '').slice(0, 1000),- hasCaption: !!(panel.caption || '').trim(),- dialogue,- hasDialogue: !!dialogue,- sfx: (panel.sfx || '').slice(0, 500),- hasSfx: !!(panel.sfx || '').trim(),- hasNeighbors: !!(prev || next),- previousPanel: neighborText(prev),- nextPanel: neighborText(next),- },+ variables,options,source: 'pipeline-comic-panel-prompt-refine',logTag: `Pipeline comic panel refine — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,@@ -1226,11 +1238,28 @@ export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, opt}/**- * Run the `pipeline-storyboard-image-prompt` template against the current- * storyboard scene + surrounding context, then persist the refined- * description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.+ * Generate N candidate image-gen prompts for a single comic panel WITHOUT+ * mutating the panel (issue #904). The user copies one or applies it to the+ * description via the existing refine/edit paths. Returns+ * { candidates, requested, pageIndex, panelIndex }.*/-export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {+export async function generateComicPanelImagePrompts(issueId, pageIndex, panelIndex, { count, ...options } = {}) {+ const { pi, ni, variables } = await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);+ const { candidates, requested } = await runImagePromptCandidates({+ count,+ templateName: 'pipeline-comic-panel-image-prompt',+ variables,+ options,+ source: 'pipeline-comic-panel-image-prompts',+ logTag: `Pipeline comic panel image-prompts — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,+ });+ return { candidates, requested, pageIndex: pi, panelIndex: ni };+}++// Validate the scene index, lock, and non-empty description, then build the+// `pipeline-storyboard-image-prompt` template variables. Shared by the 1:1+// refine and the N-candidate fan-out so both feed the LLM identical context.+async function loadStoryboardScenePromptContext(issueId, sceneIndex) {const idx = Number(sceneIndex);if (!Number.isInteger(idx) || idx < 0) {throw new ServerError('sceneIndex must be a non-negative integer', {@@ -1256,21 +1285,32 @@ export async function refineStoryboardScenePrompt(issueId, sceneIndex, options =const prev = scenes[idx - 1];const next = scenes[idx + 1];+ const variables = {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ sceneNumber: idx + 1,+ sceneCount: scenes.length,+ slugline: (scene.slugline || '').slice(0, 200),+ hasSlugline: !!(scene.slugline || '').trim(),+ description: (scene.description || '').slice(0, 4000),+ hasNeighbors: !!(prev || next),+ previousScene: neighborText(prev),+ nextScene: neighborText(next),+ };+ return { issue, idx, scenes, scene, variables };+}++/**+ * Run the `pipeline-storyboard-image-prompt` template against the current+ * storyboard scene + surrounding context, then persist the refined+ * description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.+ */+export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {+ const { idx, scenes, scene, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);const { refined, changes, runId, providerId } = await runPromptRefine({templateName: 'pipeline-storyboard-image-prompt',- variables: {- series: seriesBibleCtx(series),- issue: issueCtx(issue),- sceneNumber: idx + 1,- sceneCount: scenes.length,- slugline: (scene.slugline || '').slice(0, 200),- hasSlugline: !!(scene.slugline || '').trim(),- description: (scene.description || '').slice(0, 4000),- hasNeighbors: !!(prev || next),- previousScene: neighborText(prev),- nextScene: neighborText(next),- },+ variables,options,source: 'pipeline-storyboard-prompt-refine',logTag: `Pipeline scene refine — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,@@ -1283,3 +1323,21 @@ export async function refineStoryboardScenePrompt(issueId, sceneIndex, options =});return { scene: scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };}++/**+ * Generate N candidate image-gen prompts for a single storyboard scene+ * WITHOUT mutating the scene (issue #904). Returns+ * { candidates, requested, sceneIndex }.+ */+export async function generateStoryboardSceneImagePrompts(issueId, sceneIndex, { count, ...options } = {}) {+ const { idx, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);+ const { candidates, requested } = await runImagePromptCandidates({+ count,+ templateName: 'pipeline-storyboard-image-prompt',+ variables,+ options,+ source: 'pipeline-storyboard-image-prompts',+ logTag: `Pipeline scene image-prompts — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,+ });+ return { candidates, requested, sceneIndex: idx };+}diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 67b8f60948..e9c7b83fb8 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -58,12 +58,13 @@ vi.mock('../universeBuilder.js', () => ({const enqueueJobMock = vi.fn(() => ({ jobId: 'job-fake-1234' }));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJobMock(...a) }));-const runStagedLLMMock = vi.fn(async () => ({+const DEFAULT_RUN_STAGED_LLM = async () => ({content: { prompt: 'refined prompt body', changes: ['tightened the framing'] },runId: 'run-abc12345',providerId: 'codex',model: 'gpt-4o',-}));+});+const runStagedLLMMock = vi.fn(DEFAULT_RUN_STAGED_LLM);vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLMMock(...a) }));vi.mock('../../lib/mediaModels.js', () => ({@@ -91,6 +92,8 @@ const {enqueueStoryboardShotStartFrame,refineComicPanelPrompt,refineStoryboardScenePrompt,+ generateComicPanelImagePrompts,+ generateStoryboardSceneImagePrompts,assertCharacterAppearancesResolve,enqueueVisualImage,} = await import('./visualStages.js');@@ -104,7 +107,11 @@ beforeEach(() => {updateStageMock.mockClear();assertStageUnlockedMock.mockClear();enqueueJobMock.mockClear();- runStagedLLMMock.mockClear();+ // Restore the default implementation — several #904 tests install a+ // per-test mockImplementation/mockRejectedValue that would otherwise leak+ // into the next test (mockClear resets calls, not the implementation).+ runStagedLLMMock.mockReset();+ runStagedLLMMock.mockImplementation(DEFAULT_RUN_STAGED_LLM);});const SERIES = {@@ -541,6 +548,61 @@ describe('refineComicPanelPrompt', () => {});});+describe('generateComicPanelImagePrompts', () => {+ it('reuses the panel validation (404 on a missing panel)', async () => {+ await expect(generateComicPanelImagePrompts('iss-test', 0, 99, { count: 2 }))+ .rejects.toThrow(/panel.*out of range|PIPELINE_COMIC_PANEL_NOT_FOUND/);+ });++ it('runs the template `count` times and returns that many candidates without persisting', async () => {+ let n = 0;+ runStagedLLMMock.mockImplementation(async () => {+ n += 1;+ return { content: { prompt: `candidate ${n}`, changes: [`c${n}`] }, runId: `run-${n}`, providerId: 'codex', model: 'gpt-4o' };+ });+ const result = await generateComicPanelImagePrompts('iss-test', 0, 0, { count: 3 });+ expect(runStagedLLMMock).toHaveBeenCalledTimes(3);+ expect(result.requested).toBe(3);+ expect(result.candidates).toHaveLength(3);+ expect(result.candidates.map((c) => c.prompt)).toEqual(['candidate 1', 'candidate 2', 'candidate 3']);+ expect(result).toMatchObject({ pageIndex: 0, panelIndex: 0 });+ // Non-destructive: must NOT write the stage back.+ expect(updateStageMock).not.toHaveBeenCalled();+ });++ it('tolerates partial failure — returns survivors when some calls reject', async () => {+ let n = 0;+ runStagedLLMMock.mockImplementation(async () => {+ n += 1;+ if (n === 2) throw new Error('provider hiccup');+ return { content: { prompt: `ok ${n}`, changes: [] }, runId: `run-${n}`, providerId: 'codex', model: 'm' };+ });+ const result = await generateComicPanelImagePrompts('iss-test', 0, 0, { count: 3 });+ expect(result.requested).toBe(3);+ expect(result.candidates).toHaveLength(2);+ });++ it('throws when every candidate call fails', async () => {+ runStagedLLMMock.mockRejectedValue(new Error('all down'));+ await expect(generateComicPanelImagePrompts('iss-test', 0, 0, { count: 2 })).rejects.toThrow(/all down/);+ });++ it('clamps an oversized count to the candidate cap', async () => {+ runStagedLLMMock.mockResolvedValue({+ content: { prompt: 'x', changes: [] }, runId: 'r', providerId: 'p', model: 'm',+ });+ const result = await generateComicPanelImagePrompts('iss-test', 0, 0, { count: 99 });+ expect(result.requested).toBe(6);+ expect(runStagedLLMMock).toHaveBeenCalledTimes(6);+ });++ it('defaults to a single candidate when count is omitted', async () => {+ const result = await generateComicPanelImagePrompts('iss-test', 0, 0);+ expect(result.requested).toBe(1);+ expect(runStagedLLMMock).toHaveBeenCalledTimes(1);+ });+});+describe('composeComicCoverPrompt', () => {const SERIES_NAMED = { name: 'Bone Walker', styleNotes: 'gritty ink-wash' };@@ -867,6 +929,31 @@ describe('refineStoryboardScenePrompt', () => {});});+describe('generateStoryboardSceneImagePrompts', () => {+ it('reuses the scene validation (404 on a missing scene)', async () => {+ await expect(generateStoryboardSceneImagePrompts('iss-test', 99, { count: 2 }))+ .rejects.toThrow(/out of range|PIPELINE_SCENE_NOT_FOUND/);+ });++ it('runs the storyboard template `count` times and returns candidates without persisting', async () => {+ let n = 0;+ runStagedLLMMock.mockImplementation(async () => {+ n += 1;+ return { content: { prompt: `scene candidate ${n}`, changes: [] }, runId: `run-${n}`, providerId: 'codex', model: 'm' };+ });+ const result = await generateStoryboardSceneImagePrompts('iss-test', 1, { count: 2 });+ expect(runStagedLLMMock).toHaveBeenCalledTimes(2);+ expect(runStagedLLMMock).toHaveBeenCalledWith(+ 'pipeline-storyboard-image-prompt',+ expect.objectContaining({ sceneNumber: 2 }),+ expect.objectContaining({ returnsJson: true }),+ );+ expect(result).toMatchObject({ sceneIndex: 1, requested: 2 });+ expect(result.candidates).toHaveLength(2);+ expect(updateStageMock).not.toHaveBeenCalled();+ });+});+describe('assertCharacterAppearancesResolve', () => {const characters = [{ id: 'char-aria', name: 'Aria', wardrobes: [{ id: 'wd-coat', name: 'Trench coat' }] },