Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: share the universe/mood-board style picker and prompt renderers

[._.]/ Adam Eivy615b70c5f770
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsx
index c906907baf..d4b6332031 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx
@@ -14,17 +14,15 @@
import { useEffect, useMemo, useState } from 'react';
import ProviderModelSelector from '../ProviderModelSelector';
import { isProcessProvider } from '../../utils/providers';
-import {
- getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines,
- listMoodBoardNames, listUniverseNames, listUniverseStyles,
-} from '../../services/api';
+import { getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines } from '../../services/api';
+import UniverseMoodBoardPicker, { useStyleSourceLists } from '../media/UniverseMoodBoardPicker';
import { deriveAvailableBackends } from '../../lib/imageGenBackends';
import CronSchedulePicker from '../CronSchedulePicker';
import useUserTimezone from '../../hooks/useUserTimezone.js';
import {
inputCls, labelCls,
ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,
- backendFieldsForAbility, RENDER_BACKEND_AUTO, BOARD_FOLLOW_UNIVERSE, BOARD_NONE,
+ backendFieldsForAbility, RENDER_BACKEND_AUTO,
COMMISSION_NAME_MAX, COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,
} from './commissionForm.js';
@@ -216,36 +214,7 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
// art-direction base the Creative Director works from; the Style notes above
// refine it.
function StyleSourceSection({ styleSource, patchForm }) {
- const [universes, setUniverses] = useState([]);
- const [universeStyles, setUniverseStyles] = useState({});
- const [boards, setBoards] = useState([]);
-
- useEffect(() => {
- let cancelled = false;
- listUniverseNames({ silent: true })
- .then((rows) => { if (!cancelled) setUniverses(Array.isArray(rows) ? rows : []); })
- .catch(() => {});
- listUniverseStyles({ silent: true })
- .then((rows) => {
- if (!cancelled) setUniverseStyles(Object.fromEntries((Array.isArray(rows) ? rows : []).map((row) => [row.id, row])));
- })
- .catch(() => {});
- listMoodBoardNames({ silent: true })
- .then((rows) => { if (!cancelled) setBoards(Array.isArray(rows) ? rows : []); })
- .catch(() => {});
- return () => { cancelled = true; };
- }, []);
-
- const { universeId, moodBoardChoice } = styleSource;
- const activeStyle = universeId ? universeStyles[universeId] : null;
- const embrace = activeStyle?.influences?.embrace || [];
- const avoid = activeStyle?.influences?.avoid || [];
- // Keep a stored choice selectable even before the lists load (or after the
- // record it names was deleted), so the select never silently shows another value.
- const universeKnown = !universeId || universes.some((u) => u.id === universeId);
- const boardKnown = moodBoardChoice === BOARD_FOLLOW_UNIVERSE || moodBoardChoice === BOARD_NONE
- || boards.some((b) => b.id === moodBoardChoice);
-
+ const lists = useStyleSourceLists();
return (
<section className="space-y-3 border-t border-port-border pt-4">
<h3 className="text-sm font-semibold text-gray-200">Style source</h3>
@@ -253,56 +222,16 @@ function StyleSourceSection({ styleSource, patchForm }) {
Pick a universe or mood board and each run loads its style tags and reference images as the
Creative Director&apos;s art-direction base. Style notes above refine it.
</p>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div>
- <label className={labelCls} htmlFor="commission-universe">Universe</label>
- <select
- id="commission-universe"
- className={inputCls}
- value={universeId}
- onChange={(e) => patchForm(['styleSource', 'universeId'], e.target.value)}
- >
- <option value="">No universe</option>
- {!universeKnown && <option value={universeId}>{universeId}</option>}
- {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
- </select>
- </div>
- <div>
- <label className={labelCls} htmlFor="commission-mood-board">Mood board</label>
- <select
- id="commission-mood-board"
- className={inputCls}
- value={moodBoardChoice}
- onChange={(e) => patchForm(['styleSource', 'moodBoardChoice'], e.target.value)}
- >
- <option value={BOARD_FOLLOW_UNIVERSE}>Universe&apos;s linked board</option>
- <option value={BOARD_NONE}>No mood board</option>
- {!boardKnown && <option value={moodBoardChoice}>{moodBoardChoice}</option>}
- {boards.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
- </select>
- </div>
- </div>
- {(embrace.length > 0 || avoid.length > 0) && (
- <div className="flex flex-wrap gap-1 text-[11px]" aria-label="Universe style tags">
- {embrace.slice(0, 12).map((token) => (
- <span key={`e-${token}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-port-accent">{token}</span>
- ))}
- {avoid.slice(0, 6).map((token) => (
- <span key={`a-${token}`} className="rounded bg-port-error/15 px-1.5 py-0.5 text-port-error line-through">{token}</span>
- ))}
- </div>
- )}
- {universeId && universeKnown && universes.length > 0 && !activeStyle && (
- <p className="text-xs text-gray-500">
- This universe has no style tags yet — only its notes, style references, and images will be used.{' '}
- <a href={`/universes/${encodeURIComponent(universeId)}`} className="text-port-accent hover:underline">Edit its style guide</a>
- </p>
- )}
- {boards.length === 0 && (
- <p className="text-xs text-gray-500">
- No mood boards yet. <a href="/mood-boards" className="text-port-accent hover:underline">Create a mood board</a> to collect style references.
- </p>
- )}
+ <UniverseMoodBoardPicker
+ lists={lists}
+ idPrefix="commission"
+ labelClass={labelCls}
+ inputClass={inputCls}
+ universeId={styleSource.universeId}
+ moodBoardChoice={styleSource.moodBoardChoice}
+ onUniverseChange={(value) => patchForm(['styleSource', 'universeId'], value)}
+ onBoardChoiceChange={(value) => patchForm(['styleSource', 'moodBoardChoice'], value)}
+ />
</section>
);
}
diff --git a/client/src/components/creative-commission/CommissionConfigForm.test.jsx b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
index b3a13b3805..72dc9448d6 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.test.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import CommissionConfigForm from './CommissionConfigForm.jsx';
import { patchFormState, toForm } from './commissionForm.js';
@@ -13,6 +14,9 @@ vi.mock('../../services/api', () => api);
vi.mock('../../services/apiLocalLlm', () => ({ getToolUseModels: vi.fn(async () => ({ providers: [] })) }));
+// The style-source picker links to universe / mood-board pages.
+const render = (ui) => rtlRender(<MemoryRouter>{ui}</MemoryRouter>);
+
function Harness({ assignment } = {}) {
const [form, setForm] = useState(toForm({
assignment,
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index ac208cb417..7fd6935938 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -8,6 +8,7 @@
*/
import { describeRecurrence } from '../../utils/cronHelpers.js';
+import { BOARD_FOLLOW_UNIVERSE, BOARD_NONE } from '../../lib/styleSourceChoice.js';
// The brief field caps are the server's own (server/lib/creativeBriefLimits.js),
// used here as the inputs' `maxLength`.
@@ -231,12 +232,11 @@ export function generationToPayload(ability, generation) {
return out;
}
-// Mood-board choice sentinels for the style-source picker (form-only values —
-// never real board ids). The wire contract is the server's
-// (services/creativeCommissions/styleSource.js): a null moodBoardId follows the
-// universe's linked board, '' means no board, any other string names one.
-export const BOARD_FOLLOW_UNIVERSE = '__universe__';
-export const BOARD_NONE = '__none__';
+// The style-source picker's board choice, mapped onto the server's wire
+// contract (services/creativeCommissions/styleSource.js): a null moodBoardId
+// follows the universe's linked board, '' means no board, any other string
+// names one.
+export { BOARD_FOLLOW_UNIVERSE, BOARD_NONE };
function boardChoiceFromRecord(moodBoardId) {
if (moodBoardId == null) return BOARD_FOLLOW_UNIVERSE;
diff --git a/client/src/components/media/UniverseMoodBoardPicker.jsx b/client/src/components/media/UniverseMoodBoardPicker.jsx
new file mode 100644
index 0000000000..1511841a4f
--- /dev/null
+++ b/client/src/components/media/UniverseMoodBoardPicker.jsx
@@ -0,0 +1,96 @@
+import { useEffect, useState } from 'react';
+import { Link } from 'react-router';
+import { listMoodBoardNames, listUniverseNames, listUniverseStyles } from '../../services/api';
+import { BOARD_FOLLOW_UNIVERSE, BOARD_NONE } from '../../lib/styleSourceChoice.js';
+
+export { BOARD_FOLLOW_UNIVERSE, BOARD_NONE };
+
+const rowsOf = (rows) => (Array.isArray(rows) ? rows : []);
+
+/** Load the universes, their style tokens (keyed by id), and the mood boards once. */
+export function useStyleSourceLists() {
+ const [lists, setLists] = useState({ universes: [], universeStyles: {}, boards: [], loaded: false });
+ useEffect(() => {
+ let active = true;
+ Promise.all([
+ listUniverseNames({ silent: true }).catch(() => []),
+ listUniverseStyles({ silent: true }).catch(() => []),
+ listMoodBoardNames({ silent: true }).catch(() => []),
+ ]).then(([universes, styles, boards]) => {
+ if (!active) return;
+ setLists({
+ universes: rowsOf(universes),
+ universeStyles: Object.fromEntries(rowsOf(styles).map((row) => [row.id, row])),
+ boards: rowsOf(boards),
+ loaded: true,
+ });
+ });
+ return () => { active = false; };
+ }, []);
+ return lists;
+}
+
+/**
+ * The universe + mood-board selects, the chosen universe's embrace/avoid tags,
+ * and the empty-state hints. Fully controlled; `lists` comes from
+ * `useStyleSourceLists()` so a page that needs the lists elsewhere loads once.
+ */
+export default function UniverseMoodBoardPicker({
+ lists, universeId, moodBoardChoice, onUniverseChange, onBoardChoiceChange,
+ idPrefix, labelClass, inputClass, universeLabel = 'Universe',
+}) {
+ const { universes, universeStyles, boards, loaded } = lists;
+ const activeStyle = universeId ? universeStyles[universeId] : null;
+ const embrace = activeStyle?.influences?.embrace || [];
+ const avoid = activeStyle?.influences?.avoid || [];
+ // Keep a stored choice selectable before the lists load (or after the
+ // record it names was deleted), so the select never shows another value.
+ const universeKnown = !universeId || universes.some((u) => u.id === universeId);
+ const boardKnown = moodBoardChoice === BOARD_FOLLOW_UNIVERSE || moodBoardChoice === BOARD_NONE
+ || boards.some((b) => b.id === moodBoardChoice);
+
+ return (
+ <>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div>
+ <label htmlFor={`${idPrefix}-universe`} className={labelClass}>{universeLabel}</label>
+ <select id={`${idPrefix}-universe`} value={universeId} onChange={(e) => onUniverseChange(e.target.value)} className={inputClass}>
+ <option value="">No universe</option>
+ {!universeKnown && <option value={universeId}>{universeId}</option>}
+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor={`${idPrefix}-board`} className={labelClass}>Mood board</label>
+ <select id={`${idPrefix}-board`} value={moodBoardChoice} onChange={(e) => onBoardChoiceChange(e.target.value)} className={inputClass}>
+ <option value={BOARD_FOLLOW_UNIVERSE}>Universe&apos;s linked board</option>
+ <option value={BOARD_NONE}>No mood board</option>
+ {!boardKnown && <option value={moodBoardChoice}>{moodBoardChoice}</option>}
+ {boards.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
+ </select>
+ </div>
+ </div>
+ {(embrace.length > 0 || avoid.length > 0) && (
+ <div className="flex flex-wrap gap-1 text-[11px]" aria-label="Universe style tags">
+ {embrace.slice(0, 12).map((token) => (
+ <span key={`e-${token}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-port-accent">{token}</span>
+ ))}
+ {avoid.slice(0, 6).map((token) => (
+ <span key={`a-${token}`} className="rounded bg-port-error/15 px-1.5 py-0.5 text-port-error line-through">{token}</span>
+ ))}
+ </div>
+ )}
+ {universeId && loaded && universeKnown && !activeStyle && (
+ <p className="text-xs text-gray-500">
+ This universe has no style tokens yet, so only its notes and style references will be used.{' '}
+ <Link to={`/universes/${encodeURIComponent(universeId)}`} className="text-port-accent hover:underline">Edit its style guide</Link>
+ </p>
+ )}
+ {loaded && boards.length === 0 && (
+ <p className="text-xs text-gray-500">
+ No mood boards yet. <Link to="/mood-boards" className="text-port-accent hover:underline">Create a mood board</Link> to collect style references.
+ </p>
+ )}
+ </>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e53101f77d..fd352d74ec 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -44,6 +44,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `cleanPlatePrompt.js` | Clean-plate prompt builder for setting canon entries (Cluster A — A4). |
| `personaTraitBlend.js` | Re-export of `server/lib/personaTraitBlend.js`. Digital-twin persona trait-blending (M34 P7) — `describeTraitAdjustments` / `renderTraitBlendDirective` / `BIG_FIVE_LEAN` for the Personas UI preview. |
| `seasonStructure.js` | Re-export of `server/lib/seasonStructure.js`. |
+| `styleSourceChoice.js` | `BOARD_FOLLOW_UNIVERSE` / `BOARD_NONE` — the mood-board choice sentinels shared by the universe/mood-board style pickers (Code Animation, Creative Commissions). |
| `squarifyTreemap.js` | `squarifyTreemap(items, width, height, getValue?)` — squarified treemap layout; returns `{ item, x, y, w, h }` tiles whose areas are proportional to each item's value. Drives the Data Manager disk-usage map. |
| `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. |
| `shotContinuity.js` | The storyboards / episode-video stages' INLINE pre-render continuity warnings (#1468). `findAxisReversals` / `findShotTypeMonotony` are re-exported from `server/lib/editorial/shotContinuity.js`, the same detectors the authoritative `visual.shot-continuity` check runs; `sceneShotWarnings(scene, opts)` is the client-only composer (the server emits findings in a different shape). Pure/DOM-free. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 7b82dc37c0..6ef7d00334 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -245,3 +245,4 @@ export * from './songBookDraft.js';
export * from './layoutRoutes.js';
export * from './navPresentation.js';
export * from './squarifyTreemap.js';
+export * from './styleSourceChoice.js';
diff --git a/client/src/lib/styleSourceChoice.js b/client/src/lib/styleSourceChoice.js
new file mode 100644
index 0000000000..d44d9c21b1
--- /dev/null
+++ b/client/src/lib/styleSourceChoice.js
@@ -0,0 +1,10 @@
+/**
+ * Mood-board choice sentinels shared by every universe/mood-board style picker
+ * (`components/media/UniverseMoodBoardPicker.jsx`): follow the universe's
+ * linked board, or none. Form-only values — each surface maps them onto its
+ * own wire contract. Code Animation persists them in saved drafts, so the
+ * values are frozen. Pure and DOM-free so node-side parity tests can import
+ * the commission form helpers that use it.
+ */
+export const BOARD_FOLLOW_UNIVERSE = 'universe';
+export const BOARD_NONE = 'none';
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index d8838fe8f0..242511cd97 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -5,6 +5,7 @@ import PageHeader from '../components/PageHeader';
import ProviderModelSelector from '../components/ProviderModelSelector';
import AlbumTrackPicker from '../components/music/AlbumTrackPicker';
import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';
+import UniverseMoodBoardPicker, { BOARD_FOLLOW_UNIVERSE, BOARD_NONE, useStyleSourceLists } from '../components/media/UniverseMoodBoardPicker';
import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
import useProviderModels from '../hooks/useProviderModels';
import { usePagedCollection } from '../hooks/usePagedCollection';
@@ -18,10 +19,7 @@ import {
getCodeAnimationJob,
getCodeAnimationOptions,
listCodeAnimationJobPage,
- listMoodBoardNames,
listTracks,
- listUniverseNames,
- listUniverseStyles,
startCodeAnimationGeneration,
uploadFile,
} from '../services/api';
@@ -32,9 +30,6 @@ import { formatCount, timeAgo } from '../utils/formatters';
const DRAFT_KEY = 'portos.codeAnimation.draft';
const JOB_EVENTS = ['code-animation:changed'];
-// Mood-board choice sentinels: follow the universe's linked board, or none.
-const BOARD_FOLLOW_UNIVERSE = 'universe';
-const BOARD_NONE = 'none';
const DEFAULT_DRAFT = {
title: '',
@@ -278,9 +273,8 @@ export default function CodeAnimation() {
const navigate = useNavigate();
const jobId = routeParams.jobId || searchParams.get('job') || '';
const [options, setOptions] = useState(null);
- const [universes, setUniverses] = useState([]);
- const [universeStyles, setUniverseStyles] = useState({});
- const [boards, setBoards] = useState([]);
+ const styleLists = useStyleSourceLists();
+ const { boards } = styleLists;
const [libraryTracks, setLibraryTracks] = useState([]);
const [trackPickerOpen, setTrackPickerOpen] = useState(false);
const [draft, setDraft] = useState(loadDraft);
@@ -339,11 +333,6 @@ export default function CodeAnimation() {
useEffect(() => {
getCodeAnimationOptions({ silent: true }).then(setOptions).catch(() => toast.error('Failed to load Code Animation options'));
- listUniverseNames({ silent: true }).then((rows) => setUniverses(Array.isArray(rows) ? rows : [])).catch(() => {});
- listUniverseStyles({ silent: true })
- .then((rows) => setUniverseStyles(Object.fromEntries((Array.isArray(rows) ? rows : []).map((row) => [row.id, row]))))
- .catch(() => {});
- listMoodBoardNames({ silent: true }).then((rows) => setBoards(Array.isArray(rows) ? rows : [])).catch(() => {});
listTracks({ silent: true })
.then((rows) => setLibraryTracks(Array.isArray(rows) ? rows : rows?.tracks || []))
.catch(() => {});
@@ -352,7 +341,6 @@ export default function CodeAnimation() {
const brief = useMemo(() => toBrief(draft), [draft]);
const briefKey = useMemo(() => JSON.stringify(brief), [brief]);
const promptStale = !!built && built.briefKey !== briefKey;
- const activeStyle = draft.universeId ? universeStyles[draft.universeId] : null;
const limits = options?.limits;
const maxRefs = limits?.referenceImagesMax ?? 8;
const audioAccept = (options?.audioExtensions || ['mp3', 'wav', 'ogg', 'm4a']).map((ext) => `.${ext}`).join(',');
@@ -613,38 +601,17 @@ export default function CodeAnimation() {
<div className="space-y-4">
<section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-style-heading">
<h2 id="ca-style-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><Globe className="h-4 w-4 text-port-accent" /> Style</h2>
- <div className="grid gap-3 sm:grid-cols-2">
- <div>
- <label htmlFor="ca-universe" className={labelClass}>Universe (sets the art style)</label>
- <select id="ca-universe" value={draft.universeId} onChange={(event) => update({ universeId: event.target.value })} className={inputClass}>
- <option value="">No universe</option>
- {universes.map((universe) => <option key={universe.id} value={universe.id}>{universe.name}</option>)}
- </select>
- </div>
- <div>
- <label htmlFor="ca-board" className={labelClass}>Mood board</label>
- <select id="ca-board" value={draft.moodBoardChoice} onChange={(event) => update({ moodBoardChoice: event.target.value })} className={inputClass}>
- <option value={BOARD_FOLLOW_UNIVERSE}>Universe&apos;s linked board</option>
- <option value={BOARD_NONE}>No mood board</option>
- {boards.map((board) => <option key={board.id} value={board.id}>{board.name}</option>)}
- </select>
- </div>
- </div>
- {activeStyle && (activeStyle.influences?.embrace?.length > 0 || activeStyle.influences?.avoid?.length > 0) && (
- <div className="flex flex-wrap gap-1 text-[11px]">
- {(activeStyle.influences.embrace || []).slice(0, 12).map((token) => (
- <span key={`e-${token}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-port-accent">{token}</span>
- ))}
- {(activeStyle.influences.avoid || []).slice(0, 6).map((token) => (
- <span key={`a-${token}`} className="rounded bg-port-error/15 px-1.5 py-0.5 text-port-error line-through">{token}</span>
- ))}
- </div>
- )}
- {draft.universeId && !activeStyle && (
- <p className="text-xs text-gray-500">
- This universe has no style tokens yet, so only its notes and style references will be used. <Link to={`/universes/${encodeURIComponent(draft.universeId)}`} className="text-port-accent hover:underline">Edit its style guide</Link>
- </p>
- )}
+ <UniverseMoodBoardPicker
+ lists={styleLists}
+ idPrefix="ca"
+ universeLabel="Universe (sets the art style)"
+ labelClass={labelClass}
+ inputClass={inputClass}
+ universeId={draft.universeId}
+ moodBoardChoice={draft.moodBoardChoice}
+ onUniverseChange={(universeId) => update({ universeId })}
+ onBoardChoiceChange={(moodBoardChoice) => update({ moodBoardChoice })}
+ />
<div>
<label htmlFor="ca-style-notes" className={labelClass}>Style refinements <span className="text-gray-600">(optional, applied on top of the universe style)</span></label>
<textarea id="ca-style-notes" rows={2} value={draft.styleNotes} maxLength={limits?.styleNotesMax} onChange={(event) => update({ styleNotes: event.target.value })} placeholder="Heavier film grain, slower camera, dusk palette" className={`${inputClass} resize-y`} />
diff --git a/server/lib/README.md b/server/lib/README.md
index e5014615f1..97e1dce1b6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -128,6 +128,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `roundsValidation.js` | Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — `sanitizeRound(raw, builtinIds)` and the length/count limits shared with routes/rounds.js. |
| `socketValidation.js` | Socket event payload schemas. |
| `spriteValidation.js` | Sprite Manager Zod schemas — record import/create/update, reference generate/lock/unlock + fork, walk-cycle generate/approve/reopen/trim, per-track generate/approve schemas built from the animation-track registry, publish binding + runtime contract, atlas publish/compile, and user-defined animation-track create/update. Split out of `validation.js` (#3873), which re-exports it. |
+| `styleSourcePrompt.js` | `universeStyleLines(universe)` / `moodBoardSection(board)` — a resolved universe style guide or mood board (`services/creativeStyleSources.js`) as prompt text; shared by Code Animation and Creative Commissions. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
diff --git a/server/lib/index.js b/server/lib/index.js
index cc4ff3c92e..6d1158b3b5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -742,3 +742,4 @@ export * from './modelComparisonComposite.js';
export * from './messageLogError.js';
export * from './launchVideoValidation.js';
+export * from './styleSourcePrompt.js';
diff --git a/server/lib/styleSourcePrompt.js b/server/lib/styleSourcePrompt.js
new file mode 100644
index 0000000000..f2ee5e26fd
--- /dev/null
+++ b/server/lib/styleSourcePrompt.js
@@ -0,0 +1,45 @@
+/**
+ * Style-source prompt renderers — a resolved universe style guide or mood
+ * board (`services/creativeStyleSources.js`) as prompt text. Shared by every
+ * surface that uses a universe / mood board as its look (Code Animation's
+ * coding prompt and brief writer, Creative Commissions' art-direction base),
+ * so the prompts describing one universe or board can't drift in what they
+ * show the model. Pure; no I/O.
+ */
+
+import { isNonBlankStr } from './textUtils.js';
+
+const bulletList = (values) => values.map((value) => `- ${value}`).join('\n');
+
+/**
+ * The universe's curated style, as prompt lines. Excludes the free-text
+ * `styleNotes`, which each caller frames itself.
+ */
+export function universeStyleLines(universe) {
+ const lines = [];
+ 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 (universe.styleReferences?.length) {
+ lines.push('Style references curated for this universe:');
+ lines.push(bulletList(universe.styleReferences.map((ref) => (ref.title ? `${ref.title}: ${ref.prompt}` : ref.prompt))));
+ }
+ return lines;
+}
+
+/** 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}`);
+ const fragments = (board.items || []).map((item) => {
+ const parts = [];
+ if (item.note) parts.push(`note: ${item.note}`);
+ if (item.caption) parts.push(`caption: ${item.caption}`);
+ if (item.analyzedPrompt) parts.push(`visual analysis: ${item.analyzedPrompt}`);
+ if (item.analyzedNegative) parts.push(`avoid: ${item.analyzedNegative}`);
+ return parts.join('; ');
+ }).filter(Boolean);
+ if (fragments.length) lines.push(bulletList(fragments));
+ if (board.droppedItems) lines.push(`(${board.droppedItems} more board items omitted for length.)`);
+ return lines.join('\n');
+}
diff --git a/server/services/codeAnimation/brief.js b/server/services/codeAnimation/brief.js
index ffaa9c6524..13dea74930 100644
--- a/server/services/codeAnimation/brief.js
+++ b/server/services/codeAnimation/brief.js
@@ -28,7 +28,8 @@ import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
import { extractJson } from '../../lib/jsonExtract.js';
import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { CODE_ANIMATION_LIMITS, PACING_RULE, moodBoardSection, universeStyleLines } from './prompt.js';
+import { moodBoardSection, universeStyleLines } from '../../lib/styleSourcePrompt.js';
+import { CODE_ANIMATION_LIMITS, PACING_RULE } from './prompt.js';
// What separates a studio short from a moving screensaver, distilled from how
// strong animation briefs are written. Static text — the per-film specifics
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index b470479083..6d664e925f 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -24,6 +24,7 @@
*/
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
+import { moodBoardSection, universeStyleLines } from '../../lib/styleSourcePrompt.js';
// The postMessage vocabulary between the preview host (parent) and the
// generated page (sandboxed iframe). Served to the client through the options
@@ -88,24 +89,6 @@ export function resolveFrameSize(aspectRatio, resolution) {
return { width: shortSide, height: even((shortSide * ratio.height) / ratio.width) };
}
-const bulletList = (values) => values.map((value) => `- ${value}`).join('\n');
-
-/**
- * The universe's curated style, as prompt lines. Shared with the brief writer
- * so the two prompts describing one universe can't drift in what they show the
- * model. Excludes the free-text `styleNotes`, which each caller frames itself.
- */
-export function universeStyleLines(universe) {
- const lines = [];
- 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 (universe.styleReferences?.length) {
- lines.push('Style references curated for this universe:');
- lines.push(bulletList(universe.styleReferences.map((ref) => (ref.title ? `${ref.title}: ${ref.prompt}` : ref.prompt))));
- }
- return lines;
-}
-
// The art direction. The universe's style guide IS the look — the same curated
// tokens every other Create surface renders that world with — so the film
// matches the universe's stills and videos; the per-animation notes only
@@ -131,24 +114,6 @@ function artDirectionSection({ universe, styleNotes, hasMoodBoard }) {
return lines.join('\n');
}
-/** 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}`);
- const fragments = (board.items || []).map((item) => {
- const parts = [];
- if (item.note) parts.push(`note: ${item.note}`);
- if (item.caption) parts.push(`caption: ${item.caption}`);
- if (item.analyzedPrompt) parts.push(`visual analysis: ${item.analyzedPrompt}`);
- if (item.analyzedNegative) parts.push(`avoid: ${item.analyzedNegative}`);
- return parts.join('; ');
- }).filter(Boolean);
- if (fragments.length) lines.push(bulletList(fragments));
- if (board.droppedItems) lines.push(`(${board.droppedItems} more board items omitted for length.)`);
- return lines.join('\n');
-}
-
function referenceImagesSection(images, delivery) {
if (!images.length) return '';
const intro = {
diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.js
index e99db0a638..53bb1557b5 100644
--- a/server/services/creativeCommissions/abilityAdapters.js
+++ b/server/services/creativeCommissions/abilityAdapters.js
@@ -219,11 +219,10 @@ const videoAdapter = {
sanitizeGeneration: (raw) => sanitizeGenerationFor('video', raw),
buildProjectParams: buildVideoGeometryParams,
buildDirective(commission, options = {}) {
- const { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = options;
const duration = isAutoDuration(commission?.generation)
? ' Choose an appropriate duration between 5 and 600 seconds for the brief.' : '';
const { lines, digest, constraints } = briefContext(commission, `Create a short-form video piece.${duration}`, options);
- lines.unshift(videoPromptGuidanceFor(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId }));
+ lines.unshift(videoPromptGuidanceFor(commission, options));
return { goal: composeDirectiveGoal(lines, digest), deliverables: ['One rendered video matching the brief'], constraints };
},
};
@@ -272,12 +271,11 @@ const musicVideoAdapter = {
sanitizeGeneration: (raw) => sanitizeGenerationFor('music-video', raw),
buildProjectParams: buildVideoGeometryParams,
buildDirective(commission, options = {}) {
- const { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = options;
const duration = isAutoDuration(commission?.generation)
? ' Choose an appropriate video duration between 5 and 600 seconds for the brief.' : '';
const lead = `Create a short-form music video:${duration} Generate an original music bed AND a matching video scored to it.`;
const { lines, digest, constraints } = briefContext(commission, lead, options);
- lines.unshift(videoPromptGuidanceFor(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId }));
+ lines.unshift(videoPromptGuidanceFor(commission, options));
return {
goal: composeDirectiveGoal(lines, digest),
deliverables: ['One original music bed', 'One video matching the brief, scored to the music bed'],
diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.js
index ef5c541de1..6f6704646e 100644
--- a/server/services/creativeCommissions/directive.js
+++ b/server/services/creativeCommissions/directive.js
@@ -50,7 +50,7 @@ export const MAX_DIRECTIVE_GOAL_LEN = COMMISSION_INTENT_MAX
+ MAX_STYLE_SOURCE_LEN
+ MAX_SYSTEM_PREFIX_LEN;
-const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
+export const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
const clampNote = (note) => clamp(note, MAX_DIGEST_NOTE_LEN);
const MONTHLY_DAY_RANGES = Object.freeze({
diff --git a/server/services/creativeCommissions/styleSource.js b/server/services/creativeCommissions/styleSource.js
index 0adb64b1ad..4dfe86ad4c 100644
--- a/server/services/creativeCommissions/styleSource.js
+++ b/server/services/creativeCommissions/styleSource.js
@@ -20,17 +20,15 @@
*/
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
-import { moodBoardSection, universeStyleLines } from '../codeAnimation/prompt.js';
+import { moodBoardSection, universeStyleLines } from '../../lib/styleSourcePrompt.js';
import { resolveMoodBoardStyleSource, resolveUniverseStyleSource } from '../creativeStyleSources.js';
import { COMMISSION_STYLE_SPEC_MAX } from '../../lib/creativeBriefLimits.js';
-import { MAX_STYLE_SOURCE_LEN } from './directive.js';
+import { MAX_STYLE_SOURCE_LEN, clamp } from './directive.js';
export const COMMISSION_STYLE_REFERENCE_IMAGES_MAX = 4;
const IMAGE_LABEL_MAX = 60;
const STYLE_SOURCE_HEADER = "Art direction base (from the commission's universe / mood board — ground every render in it):";
-const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
-
// A universe or board deleted after the commission was configured must not
// kill every future fire: skip it with a warning and render from what is left.
// Any other failure (a DB outage) propagates — it is not evidence of deletion.
@@ -83,15 +81,17 @@ export async function resolveCommissionStyleSource(commission) {
? await orSkipMissing(`universe ${universeId}`, resolveUniverseStyleSource(universeId, { imageSlots: slots }), null)
: null;
const boardChoice = constraints.moodBoardId;
- const moodBoardId = boardChoice == null ? universe?.moodBoardId || null : (isNonBlankStr(boardChoice) ? boardChoice : null);
+ const explicitBoard = isNonBlankStr(boardChoice) ? boardChoice : null;
+ const moodBoardId = boardChoice == null ? universe?.moodBoardId || null : explicitBoard;
const universeImages = universe?.images || [];
+ const noBoard = { board: null, images: [] };
const { board, images: boardImages } = moodBoardId
? await orSkipMissing(
`mood board ${moodBoardId}`,
resolveMoodBoardStyleSource(moodBoardId, { imageSlots: Math.max(0, slots - universeImages.length) }),
- { board: null, images: [] },
+ noBoard,
)
- : { board: null, images: [] };
+ : noBoard;
if (!universe && !board) return null;
const text = renderCommissionStyleSource({ universe, board, images: [...universeImages, ...boardImages] });
return {