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
add a Write brief button that drafts the animation brief from the universe's bible and cast
[._.]/ Adam Eivy05316b79260a
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex ddaaa752d9..6e05f8a15c 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, Sparkles, Wand2, X } from 'lucide-react';+import { Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';import { Link, useSearchParams } from 'react-router';import PageHeader from '../components/PageHeader';import ProviderModelSelector from '../components/ProviderModelSelector';@@ -9,6 +9,7 @@ import { useAutoRefetch } from '../hooks/useAutoRefetch';import toast from '../components/ui/Toast';import {buildCodeAnimationPrompt,+ generateCodeAnimationBrief,getCodeAnimationJob,getCodeAnimationOptions,listMoodBoardNames,@@ -29,6 +30,7 @@ const BOARD_NONE = 'none';const DEFAULT_DRAFT = {title: '',+ seedIdea: '',concept: '',onScreenText: '',styleNotes: '',@@ -49,10 +51,17 @@ const loadDraft = () => {return { ...DEFAULT_DRAFT, ...stored, format: { ...DEFAULT_DRAFT.format, ...(stored.format || {}) } };};-// The draft → the server's brief shape. An absent moodBoardId follows the-// universe's linked board; '' means none.+// The mood-board choice as the server reads it: an ABSENT moodBoardId follows+// the universe's linked board, '' means none.+function moodBoardSelection(draft) {+ if (draft.moodBoardChoice === BOARD_NONE) return { moodBoardId: '' };+ if (draft.moodBoardChoice !== BOARD_FOLLOW_UNIVERSE) return { moodBoardId: draft.moodBoardChoice };+ return {};+}++// The draft → the server's brief shape.function toBrief(draft) {- const brief = {+ return {title: draft.title,concept: draft.concept,onScreenText: draft.onScreenText,@@ -67,10 +76,24 @@ function toBrief(draft) {audio: draft.audio? { filename: draft.audio.filename, label: draft.audio.label, durationSeconds: draft.audio.durationSeconds ?? null, notes: draft.audio.notes }: null,+ ...moodBoardSelection(draft),+ };+}+// The draft → the brief-writer's input: art direction plus whatever the artist+// has typed so far, which the model builds on rather than discards.+function toBriefIdeaInput(draft) {+ return {+ universeId: draft.universeId || null,+ ...moodBoardSelection(draft),+ seedIdea: draft.seedIdea,+ current: {+ title: draft.title,+ concept: draft.concept,+ onScreenText: draft.onScreenText,+ styleNotes: draft.styleNotes,+ },+ format: draft.format,};- if (draft.moodBoardChoice === BOARD_NONE) brief.moodBoardId = '';- else if (draft.moodBoardChoice !== BOARD_FOLLOW_UNIVERSE) brief.moodBoardId = draft.moodBoardChoice;- return brief;}const readAudioDuration = (file) => new Promise((resolve) => {@@ -112,6 +135,7 @@ export default function CodeAnimation() {const [draft, setDraft] = useState(loadDraft);const [uploading, setUploading] = useState(false);const [building, setBuilding] = useState(false);+ const [writingBrief, setWritingBrief] = useState(false);// The last built prompt, tagged with the brief it was built from.const [built, setBuilt] = useState(null);const [starting, setStarting] = useState(false);@@ -153,6 +177,10 @@ export default function CodeAnimation() {const audioAccept = (options?.audioExtensions || ['mp3', 'wav', 'ogg', 'm4a']).map((ext) => `.${ext}`).join(',');const generating = job?.id === jobId && job.status === 'running';const canBuild = draft.concept.trim().length > 0 && !building && !uploading;+ // The writer needs a world or some words to be faithful to — it is not a+ // blank-slate idea generator.+ const briefSeeds = !!(draft.universeId || draft.seedIdea.trim() || draft.concept.trim() || draft.title.trim());+ const canWriteBrief = briefSeeds && !writingBrief;// Poll the generation job named in the URL until it settles. The ref drops a// response for a job the user has since replaced.@@ -208,6 +236,31 @@ export default function CodeAnimation() {if (saved) update({ audio: { filename: saved.filename, label: file.name, durationSeconds, notes: '', url: saved.path } });};+ // Ask a model to write the brief from the universe's bible and canon cast,+ // the way a series or story is generated from a universe. The result lands in+ // the form as an editable draft — nothing is generated from it until the user+ // builds the prompt.+ const handleWriteBrief = async () => {+ if (!canWriteBrief) return;+ setWritingBrief(true);+ const result = await generateCodeAnimationBrief({+ ...toBriefIdeaInput(draft),+ providerId: selectedProviderId || undefined,+ model: selectedModel || undefined,+ effort: effort || undefined,+ }, { silent: true }).catch((error) => {+ toast.error(error.message || 'Failed to write the brief');+ return null;+ });+ setWritingBrief(false);+ if (!result?.brief) return;+ const { title, concept, onScreenText, styleNotes } = result.brief;+ // Style refinements live in the Style section, not the brief — only replace+ // the artist's own notes when the writer actually asked for a refinement.+ update({ title, concept, onScreenText, ...(styleNotes ? { styleNotes } : {}) });+ toast.success('Brief written — edit it before building the prompt');+ };+const handleBuild = async () => {if (!canBuild) return;setBuilding(true);@@ -304,7 +357,24 @@ export default function CodeAnimation() {</section><section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-brief-heading">- <h2 id="ca-brief-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><Sparkles className="h-4 w-4 text-port-accent" /> Brief</h2>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 id="ca-brief-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><Sparkles className="h-4 w-4 text-port-accent" /> Brief</h2>+ <button type="button" onClick={handleWriteBrief} disabled={!canWriteBrief} className={buttonSecondary} title={briefSeeds ? undefined : 'Pick a universe or write a starting idea first'}>+ {writingBrief ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <PenLine className="h-4 w-4" />}+ Write brief+ </button>+ </div>+ <div>+ <label htmlFor="ca-seed" className={labelClass}>+ Starting idea <span className="text-gray-600">(optional; what the brief writer starts from)</span>+ </label>+ <textarea id="ca-seed" rows={2} value={draft.seedIdea} maxLength={options?.briefLimits?.seedIdeaMax} onChange={(event) => update({ seedIdea: event.target.value })} placeholder="A chase through the lower market that ends in silence" className={`${inputClass} resize-y`} />+ <p className="mt-1 text-xs text-gray-500">+ {draft.universeId+ ? 'Write brief casts the film from this universe\u2019s characters, places, and tone.'+ : 'Pick a universe above to have the brief cast from its characters and places.'}+ </p>+ </div><div><label htmlFor="ca-title" className={labelClass}>Title <span className="text-gray-600">(optional)</span></label><input id="ca-title" value={draft.title} maxLength={200} onChange={(event) => update({ title: event.target.value })} placeholder="The Lantern Keeper" className={inputClass} />diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsxindex e17cce4cbf..8a698f6790 100644--- a/client/src/pages/CodeAnimation.test.jsx+++ b/client/src/pages/CodeAnimation.test.jsx@@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router';vi.mock('../services/api', () => ({buildCodeAnimationPrompt: vi.fn(),+ generateCodeAnimationBrief: vi.fn(),getCodeAnimationJob: vi.fn(),getCodeAnimationOptions: vi.fn(),listMoodBoardNames: vi.fn(),@@ -29,6 +30,7 @@ vi.mock('../hooks/useProviderModels', () => ({import CodeAnimation from './CodeAnimation';import {buildCodeAnimationPrompt,+ generateCodeAnimationBrief,getCodeAnimationOptions,listMoodBoardNames,listUniverseNames,@@ -40,6 +42,7 @@ const OPTIONS = {resolutions: ['720p', '1080p'],renderers: ['auto', 'canvas2d'],limits: { durationMin: 3, durationMax: 180, fpsOptions: [24, 30, 60], referenceImagesMax: 8 },+ briefLimits: { seedIdeaMax: 2000 },messages: { ready: 'r', record: 'rec', recorded: 'done', progress: 'p', error: 'e' },audioGlobal: 'ANIMATION_AUDIO_URL',audioExtensions: ['mp3', 'wav'],@@ -92,6 +95,56 @@ describe('Code Animation page', () => {expect(screen.getByText(/brief changed since this prompt was built/i)).toBeInTheDocument();});+ it('writes the brief from the universe and drops it into the form', async () => {+ const user = userEvent.setup();+ generateCodeAnimationBrief.mockResolvedValue({+ brief: {+ title: 'The Brass Wick',+ concept: 'Mira climbs the flooded arcade as the lamps go out.',+ onScreenText: '0:02 "One light remains"',+ styleNotes: 'colder blues at the climax',+ },+ moodBoardId: 'b1',+ llm: { provider: 'api-1', model: null, runId: 'run-b' },+ });+ await renderPage();+ const write = screen.getByRole('button', { name: /write brief/i });+ // Nothing to be faithful to yet — no universe, no spark, no words.+ expect(write).toBeDisabled();++ await user.selectOptions(screen.getByLabelText(/universe \(sets the art style\)/i), 'u1');+ await user.type(screen.getByLabelText(/starting idea/i), 'a chase that ends in silence');+ await user.click(write);++ await waitFor(() => expect(generateCodeAnimationBrief).toHaveBeenCalledTimes(1));+ expect(generateCodeAnimationBrief.mock.calls[0][0]).toMatchObject({+ universeId: 'u1',+ seedIdea: 'a chase that ends in silence',+ providerId: 'api-1',+ current: { title: '', concept: '' },+ });+ expect(await screen.findByLabelText(/what happens/i)).toHaveValue('Mira climbs the flooded arcade as the lamps go out.');+ expect(screen.getByLabelText(/^title/i)).toHaveValue('The Brass Wick');+ expect(screen.getByLabelText(/on-screen text/i)).toHaveValue('0:02 "One light remains"');+ expect(screen.getByLabelText(/style refinements/i)).toHaveValue('colder blues at the climax');+ });++ it('keeps the artist\'s own style refinements when the writer asks for none', async () => {+ const user = userEvent.setup();+ generateCodeAnimationBrief.mockResolvedValue({+ brief: { title: '', concept: 'Fireflies gather over the water.', onScreenText: '', styleNotes: '' },+ moodBoardId: null,+ llm: { provider: 'api-1', model: null, runId: null },+ });+ await renderPage();+ await user.type(screen.getByLabelText(/style refinements/i), 'more fog');+ await user.type(screen.getByLabelText(/starting idea/i), 'fireflies');+ await user.click(screen.getByRole('button', { name: /write brief/i }));+ await waitFor(() => expect(generateCodeAnimationBrief).toHaveBeenCalled());+ expect(await screen.findByLabelText(/what happens/i)).toHaveValue('Fireflies gather over the water.');+ expect(screen.getByLabelText(/style refinements/i)).toHaveValue('more fog');+ });+it('sends an explicit empty board when the user opts out of a mood board', async () => {const user = userEvent.setup();await renderPage();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 658cdf10f8..46ae12f591 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -114,7 +114,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). || `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |-| `apiCodeAnimation.js` | Code Animation: host-contract options, universe-styled LLM prompt building for a procedurally coded animation film, and provider generation jobs (start + poll for the HTML). |+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled LLM prompt building for a procedurally coded animation film, and provider generation jobs (start + poll for the HTML). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. || `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. || `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 791a6c4279..0a694839e7 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -7,6 +7,13 @@ import { request } from './apiCore.js';export const getCodeAnimationOptions = (options) => request('/code-animation/options', options);+// Ask a model to WRITE the brief from the chosen universe's bible and canon cast.+export const generateCodeAnimationBrief = (input, options) => request('/code-animation/brief', {+ method: 'POST',+ body: JSON.stringify(input),+ ...options,+});+export const buildCodeAnimationPrompt = (brief, options) => request('/code-animation/prompt', {method: 'POST',body: JSON.stringify(brief),diff --git a/docs/API.md b/docs/API.mdindex fe90d3fff6..3111b8f153 100644--- a/docs/API.md+++ b/docs/API.md@@ -763,7 +763,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/games` | Game projects || `/api/sprites` | Sprite catalog / export || `/api/threejs-models` | Procedural Three.js models |-| `/api/code-animation` | Code Animation: universe-styled prompt for an LLM-coded animation film, plus provider generation jobs (start + poll for the HTML) |+| `/api/code-animation` | Code Animation: LLM-written briefs from a universe, universe-styled prompt for an LLM-coded animation film, plus provider generation jobs (start + poll for the HTML) || `/api/image-to-3d` | Image-to-3D conversion || `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models || `/api/privacy` | PII vault / trusted-org / broker opt-out |diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex c51ead25e6..5621261456 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -3,6 +3,7 @@* animation film (and optionally run it to get the HTML).** GET /api/code-animation/options formats, limits, host contract+ * POST /api/code-animation/brief write a brief from the universe → { brief }* POST /api/code-animation/prompt resolve configurations → { prompt, attachments, frame }* POST /api/code-animation/generate start a provider run → 202 job* GET /api/code-animation/generate/:id poll a job (html once completed)@@ -16,6 +17,7 @@ import { EFFORT_LEVELS } from '../lib/providerModels.js';import { emptyToNull } from '../lib/zodCompat.js';import {buildCodeAnimationRequest,+ generateCodeAnimationBrief,getCodeAnimationJob,getCodeAnimationOptions,startCodeAnimationGeneration,@@ -26,6 +28,7 @@ import {CODE_ANIMATION_RENDERERS,CODE_ANIMATION_RESOLUTIONS,} from '../services/codeAnimation/prompt.js';+import { CODE_ANIMATION_BRIEF_LIMITS } from '../services/codeAnimation/brief.js';const router = Router();const L = CODE_ANIMATION_LIMITS;@@ -35,18 +38,20 @@ const uploadFilenameSchema = z.string().trim().min(1).max(256).regex(/^[^/\\]+$/, 'filename must be an upload basename');const optionalId = z.preprocess(emptyToNull, z.string().trim().min(1).max(128).nullable().optional());+const formatSchema = z.object({+ durationSeconds: z.number().int().min(L.durationMin).max(L.durationMax).default(20),+ aspectRatio: z.enum(Object.keys(CODE_ANIMATION_ASPECT_RATIOS)).default('16:9'),+ resolution: z.enum(Object.keys(CODE_ANIMATION_RESOLUTIONS)).default('1080p'),+ fps: z.number().int().refine((fps) => L.fpsOptions.includes(fps), 'Unsupported frame rate').default(30),+});+const briefSchema = z.object({title: z.string().trim().max(200).default(''),concept: z.string().trim().min(1, 'Describe what happens in the animation').max(L.conceptMax),onScreenText: z.string().trim().max(L.textMax).default(''),// Refinements on top of the universe style — the universe is the art direction.styleNotes: z.string().trim().max(L.styleNotesMax).default(''),- format: z.object({- durationSeconds: z.number().int().min(L.durationMin).max(L.durationMax).default(20),- aspectRatio: z.enum(Object.keys(CODE_ANIMATION_ASPECT_RATIOS)).default('16:9'),- resolution: z.enum(Object.keys(CODE_ANIMATION_RESOLUTIONS)).default('1080p'),- fps: z.number().int().refine((fps) => L.fpsOptions.includes(fps), 'Unsupported frame rate').default(30),- }).prefault({}),+ format: formatSchema.prefault({}),renderer: z.enum(CODE_ANIMATION_RENDERERS).default('auto'),interactive: z.boolean().default(false),soundtrack: z.enum(['none', 'procedural']).default('none'),@@ -73,10 +78,39 @@ const generateSchema = briefSchema.extend({effort: z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional()),}).strict();+// Writing the brief needs only the art-direction selections plus whatever the+// artist has typed so far — never the uploads or audio, which condition the+// picture, not the story.+const briefIdeaSchema = z.object({+ universeId: optionalId,+ moodBoardId: optionalId,+ seedIdea: z.string().trim().max(CODE_ANIMATION_BRIEF_LIMITS.seedIdeaMax).default(''),+ current: z.object({+ title: z.string().trim().max(200).default(''),+ concept: z.string().trim().max(L.conceptMax).default(''),+ onScreenText: z.string().trim().max(L.textMax).default(''),+ styleNotes: z.string().trim().max(L.styleNotesMax).default(''),+ }).prefault({}),+ format: formatSchema.prefault({}),+ providerId: z.string().trim().max(128).optional(),+ model: z.string().trim().max(256).optional(),+ effort: z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional()),+}).strict();+router.get('/options', (_req, res) => {res.json(getCodeAnimationOptions());});+router.post('/brief', asyncHandler(async (req, res) => {+ const input = validateRequest(briefIdeaSchema, req.body ?? {});+ // With no world and no words the model has nothing to be faithful to, and a+ // blank-slate brief is not what this button is for.+ if (!input.universeId && !input.seedIdea && !input.current.concept && !input.current.title) {+ throw new ServerError('Pick a universe or describe a starting idea to write a brief from', { status: 400, code: 'BRIEF_INPUT_REQUIRED' });+ }+ res.json(await generateCodeAnimationBrief(input));+}));+router.post('/prompt', asyncHandler(async (req, res) => {const input = validateRequest(briefSchema, req.body ?? {});const { prompt, frame, attachments, audioUrl, moodBoardId } = await buildCodeAnimationRequest(input);diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 906ca684eb..3f84c0fadf 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -3,7 +3,7 @@ import express from 'express';import { mkdirSync, writeFileSync } from 'fs';import { join } from 'path';import { request } from '../lib/testHelper.js';-import { errorMiddleware } from '../lib/errorHandler.js';+import { errorMiddleware, ServerError } from '../lib/errorHandler.js';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';vi.mock('../lib/paths.js', async (importOriginal) =>@@ -11,13 +11,17 @@ vi.mock('../lib/paths.js', async (importOriginal) =>vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverse: vi.fn() }));vi.mock('../services/moodBoard/db.js', () => ({ getBoard: vi.fn() }));vi.mock('../services/providers.js', () => ({ getProviderById: vi.fn() }));-vi.mock('../services/promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));+vi.mock('../services/promptRunner.js', () => ({+ runPromptThroughProvider: vi.fn(),+ resolveProviderAndModel: vi.fn(),+ assertProvider: vi.fn(),+}));import { PATHS } from '../lib/paths.js';import { getUniverse } from '../services/universeBuilder/crud.js';import { getBoard } from '../services/moodBoard/db.js';import { getProviderById } from '../services/providers.js';-import { runPromptThroughProvider } from '../services/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../services/promptRunner.js';import routes from './codeAnimation.js';const makeApp = () => {@@ -35,6 +39,11 @@ const UNIVERSE = {styleNotes: 'quiet and melancholic',styleReferences: [{ id: 'ref-1', title: 'Night markets', prompt: 'paper lanterns', imageRefs: ['style-ref.png'] }],moodBoardId: 'board-1',+ logline: 'A drowned city keeps its lamps lit',+ premise: 'Lamplighters trade memory for oil',+ characters: [{ id: 'chr-1', name: 'Mira', role: 'lamplighter', physicalDescription: 'tall, oil-stained coat' }],+ places: [{ id: 'set-1', name: 'The Lower Market', description: 'flooded arcade of stalls' }],+ objects: [{ id: 'obj-1', name: 'The Brass Wick', significance: 'never gutters' }],};const BOARD = {id: 'board-1',@@ -64,6 +73,65 @@ beforeEach(() => {vi.clearAllMocks();getUniverse.mockResolvedValue(UNIVERSE);getBoard.mockResolvedValue(BOARD);+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'api-1', type: 'api' }, selectedModel: 'example-model' });+});++describe('POST /api/code-animation/brief', () => {+ const briefResponse = (body) => ({ runId: 'run-b', text: `\`\`\`json\n${JSON.stringify(body)}\n\`\`\`` });++ it('writes the brief from the universe bible and canon cast', async () => {+ runPromptThroughProvider.mockResolvedValue(briefResponse({+ title: 'The Brass Wick',+ concept: 'Mira climbs the flooded arcade as the lamps go out one by one.',+ onScreenText: '0:02 "One light remains"',+ styleNotes: 'colder blues at the climax',+ }));+ const res = await request(makeApp()).post('/api/code-animation/brief').send({+ universeId: 'universe-1',+ seedIdea: 'a chase that ends in silence',+ });+ expect(res.status).toBe(200);+ expect(res.body.brief).toEqual({+ title: 'The Brass Wick',+ concept: 'Mira climbs the flooded arcade as the lamps go out one by one.',+ onScreenText: '0:02 "One light remains"',+ styleNotes: 'colder blues at the climax',+ });+ expect(res.body.moodBoardId).toBe('board-1');+ expect(res.body.llm).toEqual({ provider: 'api-1', model: 'example-model', runId: 'run-b' });+ const call = runPromptThroughProvider.mock.calls[0][0];+ expect(call.source).toBe('code-animation-brief');+ expect(call.cwd).toBe(PATHS.data);+ expect(call.prompt).toContain('a chase that ends in silence');+ expect(call.prompt).toContain('- Mira — role: lamplighter');+ expect(call.prompt).toContain('Mood board: "Dusk"');+ // The brief is text — no reference images are attached or named.+ expect(call.screenshots).toBeUndefined();+ expect(call.prompt).not.toContain('Reference images');+ });++ it('502s a response that holds no brief', async () => {+ runPromptThroughProvider.mockResolvedValue({ text: 'I would rather not.' });+ const res = await request(makeApp()).post('/api/code-animation/brief').send({ universeId: 'universe-1' });+ expect(res.status).toBe(502);+ expect(res.body.code).toBe('LLM_INVALID_JSON');+ });++ it('refuses a request with no universe and nothing written', async () => {+ const res = await request(makeApp()).post('/api/code-animation/brief').send({ seedIdea: '' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('BRIEF_INPUT_REQUIRED');+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('surfaces a missing provider as a 400 instead of running', async () => {+ resolveProviderAndModel.mockResolvedValue({ provider: null, selectedModel: null });+ assertProvider.mockImplementation(() => { throw new ServerError('No AI provider available to write the brief', { status: 400, code: 'PROVIDER_UNAVAILABLE' }); });+ const res = await request(makeApp()).post('/api/code-animation/brief').send({ seedIdea: 'a lantern' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('PROVIDER_UNAVAILABLE');+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });});describe('POST /api/code-animation/prompt', () => {@@ -90,6 +158,10 @@ describe('POST /api/code-animation/prompt', () => {{ label: 'canon sheet', origin: 'mood-board', url: '/data/image-refs/sheet.png' },]);expect(res.body.audioUrl).toBe('/api/uploads/abc12345-theme.mp3');+ // The coding prompt is art direction — the universe's bible and cast are+ // the brief writer's material and stay out of it.+ expect(res.body.prompt).not.toContain('Mira');+ expect(res.body.prompt).not.toContain('A drowned city keeps its lamps lit');expect(JSON.stringify(res.body)).not.toContain(PATHS.data);});diff --git a/server/services/codeAnimation/brief.js b/server/services/codeAnimation/brief.jsnew file mode 100644index 0000000000..78e0bfc617--- /dev/null+++ b/server/services/codeAnimation/brief.js@@ -0,0 +1,192 @@+/**+ * Code Animation brief writer (pure).+ *+ * The sibling of `prompt.js`: where that one asks a model to CODE the film,+ * this one asks a model to WRITE the film — a title, what happens, the+ * on-screen text beats, and any style refinement — from the universe the user+ * picked, exactly as the series/story surfaces do. The universe's narrative+ * bible (logline, premise, style notes) and its canon cast/places/objects are+ * the source material, so a generated brief stars the world's own characters+ * in its own locations instead of inventing a parallel one.+ *+ * Text prompt, not an image prompt: free-text `styleNotes` belongs here (see+ * `lib/universeVisualStyle.js` for why the image side excludes it).+ *+ * Deterministic string assembly over already-resolved inputs — loading the+ * universe and board happens in `index.js`.+ */++import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';+import { extractJson } from '../../lib/jsonExtract.js';+import { ServerError } from '../../lib/errorHandler.js';+import { CODE_ANIMATION_LIMITS, moodBoardSection } from './prompt.js';++export const CODE_ANIMATION_BRIEF_LIMITS = Object.freeze({+ seedIdeaMax: 2_000,+ charactersMax: 10,+ placesMax: 6,+ objectsMax: 6,+ fieldMax: 600,+});++const B = CODE_ANIMATION_BRIEF_LIMITS;++// The canon fields a 20-second animated film can actually act on: who someone+// is, what they look like, what they want. Deliberately narrower than the+// bible's full prompt-field set (`lib/storyBible.js#PROMPT_FIELDS`) — psychology+// sliders, wardrobes, and relationship graphs would swamp the prompt without+// changing a single frame.+const CANON_FIELDS = Object.freeze({+ characters: ['role', 'physicalDescription', 'visualNotes', 'personality', 'motivations', 'coreTheme'],+ places: ['description', 'palette', 'timeOfDay', 'recurringDetails'],+ objects: ['description', 'significance'],+});++const stringField = (value) => {+ if (Array.isArray(value)) return trimTo(value.filter(isNonBlankStr).join(', '), B.fieldMax);+ return isNonBlankStr(value) ? trimTo(value, B.fieldMax) : '';+};++/**+ * Project one canon kind down to the named-entity lines the brief writer reads.+ * Entries with nothing but a name still make the list — the writer needs to+ * know the world HAS them.+ */+export function projectCanonForBrief(entries, kind, cap) {+ const fields = CANON_FIELDS[kind] || [];+ return (Array.isArray(entries) ? entries : [])+ .filter((entry) => isNonBlankStr(entry?.name))+ .slice(0, cap)+ .map((entry) => {+ const projected = { name: trimTo(entry.name, 120) };+ for (const field of fields) {+ const value = stringField(entry[field]);+ if (value) projected[field] = value;+ }+ return projected;+ });+}++const canonBlock = (heading, rows) => {+ if (!rows.length) return '';+ const lines = rows.map((row) => {+ const { name, ...rest } = row;+ const detail = Object.entries(rest).map(([key, value]) => `${key}: ${value}`).join('; ');+ return detail ? `- ${name} — ${detail}` : `- ${name}`;+ });+ return `${heading}\n${lines.join('\n')}`;+};++function universeSection(universe) {+ if (!universe) return '';+ const lines = [`The film is set in the universe "${universe.name}". Everything you write must be canon to it.`];+ if (isNonBlankStr(universe.logline)) lines.push(`Logline: ${universe.logline}`);+ if (isNonBlankStr(universe.premise)) lines.push(`Premise: ${universe.premise}`);+ if (universe.embrace?.length) lines.push(`Visual style to embrace: ${universe.embrace.join(', ')}`);+ if (universe.avoid?.length) lines.push(`Visual style to avoid: ${universe.avoid.join(', ')}`);+ if (isNonBlankStr(universe.styleNotes)) lines.push(`Tone, staging, and pacing notes: ${universe.styleNotes}`);+ if (universe.styleReferences?.length) {+ lines.push('Style references curated for this universe:');+ lines.push(universe.styleReferences.map((ref) => `- ${ref.title ? `${ref.title}: ` : ''}${ref.prompt}`).join('\n'));+ }+ return lines.join('\n');+}++function castSection(universe) {+ const blocks = [+ canonBlock('CHARACTERS (cast the film from these — use their names):', universe?.characters || []),+ canonBlock('PLACES (stage the film in these):', universe?.places || []),+ canonBlock('OBJECTS that matter in this world:', universe?.objects || []),+ ].filter(Boolean);+ if (!blocks.length) {+ return universe+ ? 'This universe has no canon characters, places, or objects recorded yet — invent ones that fit its logline and tone, and keep the cast small.'+ : '';+ }+ return `${blocks.join('\n\n')}\n\nPrefer the canon above over inventing new entities. A character you use must behave, speak, and look as their entry describes.`;+}++function currentSection(current) {+ const rows = [+ ['Title', current.title],+ ['What happens', current.concept],+ ['On-screen text', current.onScreenText],+ ['Style refinements', current.styleNotes],+ ].filter(([, value]) => isNonBlankStr(value));+ if (!rows.length) return '';+ return `WHAT THE ARTIST HAS WRITTEN SO FAR — build on this rather than discarding it; keep what already works and fill in or sharpen the rest:\n${rows.map(([label, value]) => `${label}: ${value}`).join('\n')}`;+}++/**+ * Build the prompt that asks a model to write an animation brief.+ *+ * @param {object} input+ * @param {object|null} [input.universe] - `{ name, logline, premise, embrace, avoid, styleNotes, styleReferences, characters, places, objects }`+ * @param {object|null} [input.moodBoard] - `collectBoardStyleContext` output+ * @param {string} [input.seedIdea] - the artist's starting spark, if any+ * @param {{ durationSeconds: number, aspectRatio: string }} input.format+ * @param {{ title: string, concept: string, onScreenText: string, styleNotes: string }} [input.current]+ * @returns {string}+ */+export function buildCodeAnimationBriefPrompt({+ universe = null,+ moodBoard = null,+ seedIdea = '',+ format,+ current = {},+}) {+ const { durationSeconds, aspectRatio } = format;+ const sections = [+ `You are a short-film director and writer. Write the brief for a ${durationSeconds}-second ${aspectRatio} animated film that will be drawn entirely in code — procedural shapes, strokes, particles, and typography, with no photographic or hand-drawn assets. Write something a creative coder can actually stage: silhouettes, light, motion, and a handful of clear beats rather than dialogue, facial acting, or crowds.`,+ ];+ if (isNonBlankStr(seedIdea)) {+ sections.push(`THE ARTIST'S SPARK — this is the film they want; honor it:\n${trimTo(seedIdea, B.seedIdeaMax)}`);+ }+ const universeText = universeSection(universe);+ if (universeText) sections.push(`UNIVERSE:\n${universeText}`);+ const castText = castSection(universe);+ if (castText) sections.push(castText);+ const boardText = moodBoardSection(moodBoard);+ if (boardText) sections.push(boardText);+ const currentText = currentSection(current);+ if (currentText) sections.push(currentText);+ if (!universe && !isNonBlankStr(seedIdea) && !currentText) {+ sections.push('No universe or starting idea was given — invent a striking, self-contained concept with a distinctive look.');+ }+ sections.push(`WRITE:+- title: a short evocative title (max 80 characters).+- concept: what happens, as a beat-by-beat account across the full ${durationSeconds} seconds (establish → develop → climax → resolve). Name the characters and places you are using, say what the camera does, and describe what the audience sees. 120–350 words, prose, no headings or markdown.+- onScreenText: the on-screen typography and narration beats, one per line, each led by its timestamp (e.g. \`0:02 "Every night, one light remains"\`). Use at most a handful, and leave it as an empty string if the film is better with no text at all.+- styleNotes: one or two sentences of refinement ON TOP OF the universe's established style — a palette shift, a grain, a camera behavior this particular film wants. Do NOT restate the universe's style; leave it an empty string if nothing needs refining.`);+ sections.push(`OUTPUT: Return ONLY a JSON object, in a single \`\`\`json fenced code block, with exactly these keys:+{"title": "...", "concept": "...", "onScreenText": "...", "styleNotes": "..."}+Every value is a plain string (use \\n for line breaks). No commentary before or after it, and do not create or edit any files.`);+ return sections.join('\n\n');+}++const briefShape = (value) => !!value && typeof value === 'object' && typeof value.concept === 'string';++const briefField = (value, max) => (typeof value === 'string' ? trimTo(value.trim(), max) : '');++/**+ * Parse a written brief out of a model response, clamped to the same limits the+ * brief form enforces. Throws a typed 502 when the response holds no usable+ * JSON object.+ */+export function extractBriefIdea(raw) {+ const { value, lastError, lastPreview } = extractJson(raw, { shapePredicate: briefShape });+ const concept = briefField(value?.concept, CODE_ANIMATION_LIMITS.conceptMax);+ if (!concept) {+ throw new ServerError('The model did not return a usable brief. Try a different model or rerun.', {+ status: 502,+ code: 'LLM_INVALID_JSON',+ context: { details: { reason: lastError?.message || 'no brief object found', preview: lastPreview || '' } },+ });+ }+ return {+ title: briefField(value.title, 200),+ concept,+ onScreenText: briefField(value.onScreenText, CODE_ANIMATION_LIMITS.textMax),+ styleNotes: briefField(value.styleNotes, CODE_ANIMATION_LIMITS.styleNotesMax),+ };+}diff --git a/server/services/codeAnimation/brief.test.js b/server/services/codeAnimation/brief.test.jsnew file mode 100644index 0000000000..4418848071--- /dev/null+++ b/server/services/codeAnimation/brief.test.js@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';+import {+ buildCodeAnimationBriefPrompt,+ extractBriefIdea,+ projectCanonForBrief,+} from './brief.js';+import { CODE_ANIMATION_LIMITS } from './prompt.js';++const FORMAT = { durationSeconds: 20, aspectRatio: '16:9' };++const UNIVERSE = {+ name: 'Example Universe',+ logline: 'A drowned city keeps its lamps lit',+ premise: 'Lamplighters trade memory for oil',+ embrace: ['ink wash', 'muted indigo'],+ avoid: ['photorealism'],+ styleNotes: 'quiet, melancholic, slow camera',+ styleReferences: [{ title: 'Night markets', prompt: 'paper lanterns over water' }],+ characters: [{ name: 'Mira', role: 'lamplighter', physicalDescription: 'tall, oil-stained coat' }],+ places: [{ name: 'The Lower Market', description: 'flooded arcade of stalls' }],+ objects: [{ name: 'The Brass Wick', significance: 'the last lamp that never gutters' }],+};++describe('projectCanonForBrief', () => {+ it('keeps the named entities and the fields a film can stage, and caps the list', () => {+ const rows = projectCanonForBrief([+ { name: 'Mira', role: 'lamplighter', motivations: ['keep the lamps lit', 'find her brother'], sliders: { warmth: 3 }, id: 'chr-1' },+ { name: ' ', role: 'nobody' },+ { name: 'Corin' },+ { name: 'Vale' },+ ], 'characters', 2);+ expect(rows).toEqual([+ { name: 'Mira', role: 'lamplighter', motivations: 'keep the lamps lit, find her brother' },+ { name: 'Corin' },+ ]);+ });++ it('is empty for a universe with no canon of that kind', () => {+ expect(projectCanonForBrief(undefined, 'places', 6)).toEqual([]);+ });+});++describe('buildCodeAnimationBriefPrompt', () => {+ it('grounds the brief in the universe bible, its cast, and the artist\'s spark', () => {+ const prompt = buildCodeAnimationBriefPrompt({+ universe: UNIVERSE,+ moodBoard: { name: 'Dusk', description: 'amber evenings', items: [{ caption: 'harbor glow' }] },+ seedIdea: 'a chase that ends in silence',+ format: FORMAT,+ current: { title: 'The Brass Wick', concept: '', onScreenText: '', styleNotes: '' },+ });+ expect(prompt).toContain('20-second 16:9 animated film');+ expect(prompt).toContain('a chase that ends in silence');+ expect(prompt).toContain('The film is set in the universe "Example Universe"');+ expect(prompt).toContain('Logline: A drowned city keeps its lamps lit');+ expect(prompt).toContain('- Mira — role: lamplighter; physicalDescription: tall, oil-stained coat');+ expect(prompt).toContain('- The Lower Market — description: flooded arcade of stalls');+ expect(prompt).toContain('- The Brass Wick — significance: the last lamp that never gutters');+ expect(prompt).toContain('Mood board: "Dusk"');+ expect(prompt).toContain('Title: The Brass Wick');+ expect(prompt).toContain('"title": "..."');+ });++ it('tells the model to invent a cast when the universe has no canon yet', () => {+ const prompt = buildCodeAnimationBriefPrompt({+ universe: { name: 'Bare World', embrace: [], avoid: [] },+ format: FORMAT,+ });+ expect(prompt).toContain('no canon characters, places, or objects recorded yet');+ expect(prompt).not.toContain('CHARACTERS (');+ });++ it('falls back to a blank-slate instruction with nothing to go on', () => {+ const prompt = buildCodeAnimationBriefPrompt({ format: FORMAT });+ expect(prompt).toContain('invent a striking, self-contained concept');+ });+});++describe('extractBriefIdea', () => {+ const response = (body) => `Here you go:\n\`\`\`json\n${JSON.stringify(body)}\n\`\`\``;++ it('parses a fenced brief and keeps an intentionally empty field empty', () => {+ expect(extractBriefIdea(response({+ title: 'The Brass Wick',+ concept: 'Mira climbs the flooded arcade…',+ onScreenText: '',+ styleNotes: 'colder blues at the climax',+ }))).toEqual({+ title: 'The Brass Wick',+ concept: 'Mira climbs the flooded arcade…',+ onScreenText: '',+ styleNotes: 'colder blues at the climax',+ });+ });++ it('clamps every field to the limit the brief form enforces', () => {+ const parsed = extractBriefIdea(response({+ title: 'T'.repeat(500),+ concept: 'C'.repeat(CODE_ANIMATION_LIMITS.conceptMax + 100),+ onScreenText: 'O'.repeat(CODE_ANIMATION_LIMITS.textMax + 100),+ styleNotes: 'S'.repeat(CODE_ANIMATION_LIMITS.styleNotesMax + 100),+ }));+ expect(parsed.title.length).toBe(200);+ expect(parsed.concept.length).toBe(CODE_ANIMATION_LIMITS.conceptMax);+ expect(parsed.onScreenText.length).toBe(CODE_ANIMATION_LIMITS.textMax);+ expect(parsed.styleNotes.length).toBe(CODE_ANIMATION_LIMITS.styleNotesMax);+ });++ it('rejects a response with no usable concept', () => {+ expect(() => extractBriefIdea('I could not write that.')).toThrow(/did not return a usable brief/);+ expect(() => extractBriefIdea(response({ concept: ' ' }))).toThrow(/did not return a usable brief/);+ });+});diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.jsindex 9966c66010..2ee36627c0 100644--- a/server/services/codeAnimation/index.js+++ b/server/services/codeAnimation/index.js@@ -31,6 +31,12 @@ import {CODE_ANIMATION_RENDERERS,CODE_ANIMATION_RESOLUTIONS,} from './prompt.js';+import {+ buildCodeAnimationBriefPrompt,+ extractBriefIdea,+ projectCanonForBrief,+ CODE_ANIMATION_BRIEF_LIMITS,+} from './brief.js';const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp', 'gif'];const resolveUploadImage = makePathResolver(() => PATHS.uploads, { extensions: IMAGE_EXTENSIONS });@@ -46,6 +52,7 @@ export function getCodeAnimationOptions() {resolutions: Object.keys(CODE_ANIMATION_RESOLUTIONS),renderers: CODE_ANIMATION_RENDERERS,limits: CODE_ANIMATION_LIMITS,+ briefLimits: CODE_ANIMATION_BRIEF_LIMITS,messages: CODE_ANIMATION_MESSAGES,audioGlobal: CODE_ANIMATION_AUDIO_GLOBAL,audioExtensions: UPLOAD_AUDIO_EXTENSIONS,@@ -77,7 +84,20 @@ function fillReferences(candidates, slots) {return images;}-async function resolveUniverse(universeId, { imageSlots }) {+// The narrative half of a universe — its bible text and canon cast. Only the+// brief writer reads it: the coding prompt is art direction, and a logline or a+// character's motivations would just crowd out the runtime contract.+function universeNarrative(universe) {+ return {+ logline: trimTo(universe.logline, 2_000),+ premise: trimTo(universe.premise, 4_000),+ characters: projectCanonForBrief(universe.characters, 'characters', CODE_ANIMATION_BRIEF_LIMITS.charactersMax),+ places: projectCanonForBrief(universe.places, 'places', CODE_ANIMATION_BRIEF_LIMITS.placesMax),+ objects: projectCanonForBrief(universe.objects, 'objects', CODE_ANIMATION_BRIEF_LIMITS.objectsMax),+ };+}++async function resolveUniverse(universeId, { imageSlots, narrative = false }) {if (!universeId) return null;const { getUniverse } = await import('../universeBuilder/crud.js');const universe = await getUniverse(universeId).catch((error) => {@@ -107,6 +127,7 @@ async function resolveUniverse(universeId, { imageSlots }) {styleReferences,moodBoardId: isNonBlankStr(universe.moodBoardId) ? universe.moodBoardId : null,images,+ ...(narrative ? universeNarrative(universe) : {}),};}@@ -209,6 +230,47 @@ export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {};}+/**+ * Write the brief itself: ask a model for a title / concept / on-screen text /+ * style refinement grounded in the universe's bible and canon cast, the same+ * way a series or story is generated from a universe. Synchronous — a few+ * hundred words comes back inside one request, unlike the HTML generation.+ *+ * Returns `{ brief, moodBoardId, llm }`; the client drops `brief` straight into+ * the form so the user can edit it before building the animation prompt.+ */+export async function generateCodeAnimationBrief(input) {+ const { assertProvider, resolveProviderAndModel, runPromptThroughProvider } = await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId: input.providerId, model: input.model });+ assertProvider(provider, { message: 'No AI provider available to write the brief', code: 'PROVIDER_UNAVAILABLE', status: 400 });+ // No image slots: the brief is text, and the style images are already the+ // coding prompt's job.+ const universe = await resolveUniverse(input.universeId, { imageSlots: 0, narrative: true });+ const moodBoardId = input.moodBoardId === undefined ? universe?.moodBoardId : input.moodBoardId;+ const { board } = await resolveMoodBoard(moodBoardId, { imageSlots: 0 });+ const prompt = buildCodeAnimationBriefPrompt({+ universe,+ moodBoard: board,+ seedIdea: input.seedIdea,+ format: input.format,+ current: input.current,+ });+ console.log(`📝 Code animation brief writing on ${provider.id}/${selectedModel || 'default'}${universe ? ` for universe "${universe.name}"` : ''}`);+ const { text, runId } = await runPromptThroughProvider({+ provider,+ model: selectedModel || undefined,+ effort: input.effort || undefined,+ prompt,+ source: 'code-animation-brief',+ // Same containment as the HTML generation: a CLI/TUI agent only needs to+ // print a JSON document, never to touch the PortOS checkout.+ cwd: PATHS.data,+ });+ const brief = extractBriefIdea(text);+ console.log(`✅ Code animation brief written — runId=${runId || 'n/a'} concept=${brief.concept.length} chars`);+ return { brief, moodBoardId: moodBoardId || null, llm: { provider: provider.id, model: selectedModel || null, runId: runId || null } };+}+// Drop settled jobs past their TTL, then the oldest settled ones past the cap.// A running job is never evicted — its result would have nowhere to land.function pruneJobs() {diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex fb36a3f57f..bc935b43e0 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -115,7 +115,8 @@ function artDirectionSection({ universe, styleNotes, hasMoodBoard }) {return lines.join('\n');}-function moodBoardSection(board) {+/** The board's style context as prompt text (`''` when there is no board). */+export function moodBoardSection(board) {if (!board) return '';const lines = [`Mood board: "${board.name || 'Untitled board'}" — distill its through-line (palette, texture, lighting, rhythm, mood), not any single item.`];if (isNonBlankStr(board.description)) lines.push(`Board description: ${board.description}`);