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: Story Builder characters step generates styled preview images
Adam Eivy90af9fa9bc1f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5f9e0e023b..6522226635 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,7 +8,7 @@ TBD## Added-- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage. An **AI provider/model picker** at the top of the builder (and the import tab) drives every operation — idea expand, aesthetic, arc, reader map, character refine, and the import analysis — persisted on the session so one selection applies throughout.+- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage. An **AI provider/model picker** at the top of the builder (and the import tab) drives every operation — idea expand, aesthetic, arc, reader map, character refine, and the import analysis — persisted on the session so one selection applies throughout. The **characters step generates a styled preview image per character** (world style fused with the character descriptor, via the same render path as the Universe Builder) and shows it alongside each character so you can eyeball that the world and character styles read correctly together.- **Reader Map** on a series arc (`series.arc.readerMap`): a distinct audience-experience roadmap — hooks, payoffs, emotional beats, and cliffhangers across the arc — built on top of the Vonnegut story shape, separate from the protagonist arc. Generated and refined via the new Story Builder reader-map step (also preserved by arc regeneration).## Changeddiff --git a/client/src/components/universe/EntryThumbSlot.jsx b/client/src/components/universe/EntryThumbSlot.jsxindex 0c61b3c304..76f1cc4224 100644--- a/client/src/components/universe/EntryThumbSlot.jsx+++ b/client/src/components/universe/EntryThumbSlot.jsx@@ -29,6 +29,10 @@ export default function EntryThumbSlot({primaryImageRef = null,onRender = null,onPreview = null,+ // Fired with the rendered filename when an in-flight job completes (forwarded+ // to MediaJobThumb's onFilename) so callers can persist the new ref + clear+ // the in-flight job without their own job subscription.+ onComplete = null,canRender = true,alt = 'Render',// `'lg'` renders the empty-state box at 64x96 with a bigger Sparkles@@ -50,6 +54,7 @@ export default function EntryThumbSlot({label={alt}size={size === 'lg' ? 'sm' : 'xs'}onPreview={onPreview}+ onFilename={onComplete}/>);}diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex f975b81848..d86341dccf 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -1,6 +1,11 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';import { filterSelectableModels } from '../utils/providers';+import { composeStyledPrompt } from '../lib/composeStyledPrompt';+import { universeStylePreset } from '../lib/universeStylePreset';+import { descriptorForCanonEntry } from '../lib/canonPrompt';+import { pipelineImageCfgToRenderOpts, readPipelineImageSettings, PIPELINE_IMAGE_DEFAULTS } from '../lib/pipelineImageDefaults';+import EntryThumbSlot from '../components/universe/EntryThumbSlot';import {Sparkles, Lock, Unlock, Check, ChevronRight, ChevronLeft, AlertTriangle,Plus, RefreshCw, Loader2, ExternalLink, Wand2,@@ -13,7 +18,7 @@ import {generateStoryStep, refineStoryStep, setStoryIssueLock,getUniverse, getPipelineSeries, listPipelineIssues,analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,- getProviders,+ getProviders, getSettings, generateImage, updateUniverse,} from '../services/api';// Mirror Importer.jsx's commit picker — only these arc fields are sent on commit.@@ -487,32 +492,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange);}if (stepId === 'characters') {- const cast = universe?.characters || [];- return (- <div className="space-y-3">- {cast.length === 0 && (- <p className="text-gray-600 italic text-sm">- No characters yet. Add them in the <Link to={universe?.id ? `/universes/${universe.id}` : '/universes'} className="text-port-accent">Universe Builder</Link> or after generating the arc.- </p>- )}- {cast.map((c) => (- <div key={c.id} className="bg-port-bg border border-port-border rounded p-2 flex items-start justify-between gap-2">- <div>- <div className="font-medium text-sm">{c.name} {c.locked && <Lock className="w-3 h-3 inline text-port-success" />}</div>- <div className="text-xs text-gray-400">{c.physicalDescription || (Array.isArray(c.descriptor) ? c.descriptor.map((d) => d.value).join(', ') : '')}</div>- </div>- {!locked && (- <button- onClick={() => runRefine('', c.id)} disabled={busy}- className="text-xs inline-flex items-center gap-1 border border-port-border rounded px-2 py-1 hover:border-port-accent disabled:opacity-50"- >- <Wand2 className="w-3 h-3" /> Refine- </button>- )}- </div>- ))}- </div>- );+ return <StepCharacters session={session} universe={universe} locked={locked} onChanged={onChanged} />;}if (stepId === 'issues') {return <IssuesPanel session={session} series={series} issues={issues} onChanged={onChanged} />;@@ -538,6 +518,98 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChangereturn null;}+// Characters step — review the cast and generate a styled preview image per+// character so the world style + character style can be eyeballed together.+// Reuses the Universe Builder's exact render path: composeStyledPrompt ++// universeStylePreset → generateImage → EntryThumbSlot (spinner → image), and+// persists the resulting filename onto the universe canon entry's imageRefs.+function StepCharacters({ session, universe, locked, onChanged }) {+ const cast = universe?.characters || [];+ const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);+ const [renderingJobs, setRenderingJobs] = useState({});+ const [refiningId, setRefiningId] = useState(null);++ useEffect(() => {+ getSettings({ silent: true })+ .then((s) => setImageCfg(readPipelineImageSettings(s)))+ .catch(() => {});+ }, []);++ const renderChar = async (c) => {+ const description = descriptorForCanonEntry('characters', c);+ if (!description.trim()) { toast.error(`Add a description for ${c.name} before generating a preview`); return; }+ const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const styled = composeStyledPrompt(+ `${c.name}: ${description}`,+ baseOpts.negativePrompt || '',+ universe ? universeStylePreset(universe) : null,+ );+ const queued = await generateImage(+ { ...baseOpts, prompt: styled.prompt, negativePrompt: styled.negativePrompt || undefined },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Render failed'); return null; });+ if (!queued?.jobId) return;+ setRenderingJobs((p) => ({ ...p, [c.id]: queued.jobId }));+ };++ // Section-local renders don't carry a universeRun tag, so the server's+ // imageRef append hook never fires — persist the filename ourselves (mirrors+ // UniverseCanonSection.handleRefCompleted).+ const onCharRendered = async (charId, filename) => {+ setRenderingJobs((p) => { if (!p[charId]) return p; const n = { ...p }; delete n[charId]; return n; });+ if (!filename || !universe?.id) return;+ const list = (universe.characters || []).map((e) =>+ e.id === charId ? { ...e, imageRefs: [...(e.imageRefs || []), filename] } : e);+ await updateUniverse(universe.id, { characters: list }, { silent: true }).catch(() => {});+ onChanged();+ };++ const refineChar = async (entryId) => {+ setRefiningId(entryId);+ const res = await refineStoryStep(session.id, 'characters', { entryId }, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Refine failed'); return null; });+ setRefiningId(null);+ if (res) { toast.success(res.changes?.length ? `Refined — ${res.changes.length} change(s)` : 'Refined'); onChanged(); }+ };++ return (+ <div className="space-y-3">+ {cast.length === 0 && (+ <p className="text-gray-600 italic text-sm">+ No characters yet. Add them in the <Link to={universe?.id ? `/universes/${universe.id}` : '/universes'} className="text-port-accent">Universe Builder</Link> or after generating the arc.+ </p>+ )}+ {cast.length > 0 && (+ <p className="text-xs text-gray-500">Generate a preview for each character to check the world style and character read correctly together.</p>+ )}+ {cast.map((c) => (+ <div key={c.id} className="bg-port-bg border border-port-border rounded p-2 flex items-start gap-3">+ <EntryThumbSlot+ imageRefs={c.imageRefs}+ inFlightJobId={renderingJobs[c.id] || null}+ onRender={() => renderChar(c)}+ onComplete={(fn) => onCharRendered(c.id, fn)}+ canRender={!locked && Boolean(universe?.id)}+ alt={c.name}+ />+ <div className="flex-1 min-w-0">+ <div className="font-medium text-sm">{c.name} {c.locked && <Lock className="w-3 h-3 inline text-port-success" />}</div>+ <div className="text-xs text-gray-400">{c.physicalDescription || (Array.isArray(c.descriptor) ? c.descriptor.map((d) => d.value).join(', ') : '')}</div>+ </div>+ {!locked && (+ <button+ onClick={() => refineChar(c.id)} disabled={refiningId === c.id}+ className="text-xs inline-flex items-center gap-1 border border-port-border rounded px-2 py-1 hover:border-port-accent disabled:opacity-50 shrink-0"+ >+ {refiningId === c.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Wand2 className="w-3 h-3" />} Refine+ </button>+ )}+ </div>+ ))}+ </div>+ );+}+function IssuesPanel({ session, series, issues, onChanged }) {const locks = session.steps?.issues?.issueLocks || {};const [busyId, setBusyId] = useState(null);diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxindex d58963f89b..67a4ce79aa 100644--- a/client/src/pages/StoryBuilder.test.jsx+++ b/client/src/pages/StoryBuilder.test.jsx@@ -36,7 +36,9 @@ const api = vi.hoisted(() => ({retryImporterIssues: vi.fn(),IMPORTER_CONTENT_TYPES: ['short-story', 'novel', 'screenplay', 'comic-script'],getProviders: vi.fn(),- updateStorySession: vi.fn(),+ getSettings: vi.fn(),+ generateImage: vi.fn(),+ updateUniverse: vi.fn(),}));vi.mock('../services/api', () => api);@@ -57,6 +59,9 @@ beforeEach(() => {api.listStorySessions.mockResolvedValue([]);api.getProviders.mockResolvedValue({ providers: [{ id: 'p1', name: 'Claude', enabled: true, models: ['opus', 'sonnet'] }] });api.updateStorySession.mockResolvedValue({});+ api.getSettings.mockResolvedValue({});+ api.generateImage.mockResolvedValue({ jobId: 'job-1' });+ api.updateUniverse.mockResolvedValue({});// Benign default so a post-import navigation that mounts the detail view// (which calls getStorySession) doesn't reject; the detail tests override it.api.getStorySession.mockResolvedValue({@@ -216,6 +221,27 @@ describe('StoryBuilder — detail stepper', () => {await waitFor(() => expect(api.setStoryCurrentStep).toHaveBeenCalledWith('stb-1', 'universeAesthetic', expect.anything()));});+ it('characters step: renders a per-character preview slot and generates a styled preview image', async () => {+ const { fireEvent } = await import('@testing-library/react');+ api.getStorySession.mockResolvedValue({+ id: 'stb-1', title: 'X', currentStep: 'characters', universeId: 'u1', seriesId: 's1',+ steps: mkSteps({ idea: { locked: true }, universeAesthetic: { locked: true }, plotArc: { locked: true }, readerMap: { locked: true } }),+ staleSteps: [], llm: { provider: '', model: '' },+ });+ api.getUniverse.mockResolvedValue({+ id: 'u1', name: 'Giant', influences: { embrace: ['noir'], avoid: [] }, styleNotes: 'inky',+ characters: [{ id: 'ch1', name: 'Kessa', physicalDescription: 'tall, scarred', imageRefs: [] }],+ });+ renderAt('/story-builder/stb-1/characters');+ await waitFor(() => expect(screen.getByText('Kessa')).toBeTruthy());+ fireEvent.click(screen.getByTitle('Render image for this item'));+ await waitFor(() => expect(api.generateImage).toHaveBeenCalled());+ // The prompt fuses the character descriptor with the universe style.+ const arg = api.generateImage.mock.calls[0][0];+ expect(arg.prompt).toContain('Kessa');+ expect(arg.prompt.toLowerCase()).toContain('noir');+ });+it('persists the provider/model picker choice to session.llm', async () => {const { fireEvent } = await import('@testing-library/react');api.getStorySession.mockResolvedValue({diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 528cfaac68..d23fafc3de 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -134,9 +134,10 @@ export const provisionTailnetCert = () => request('/instances/provision-cert', {// Image Generationexport const getImageGenStatus = (mode) => request(`/image-gen/status${mode ? `?mode=${encodeURIComponent(mode)}` : ''}`);-export const generateImage = (data) => request('/image-gen/generate', {+export const generateImage = (data, options = {}) => request('/image-gen/generate', {method: 'POST',- body: JSON.stringify(data)+ body: JSON.stringify(data),+ ...options,});// Curated style presets — code-static on the server, so cache the in-flight// promise and reuse it for the lifetime of the page. Eliminates the repeat