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
Cover art: each song gets its own design, steerable before publishing
Claude38ed03f35fe2
diff --git a/client/src/components/musicVideo/CoverArtPanel.jsx b/client/src/components/musicVideo/CoverArtPanel.jsxindex e8973959bf..8e10227894 100644--- a/client/src/components/musicVideo/CoverArtPanel.jsx+++ b/client/src/components/musicVideo/CoverArtPanel.jsx@@ -23,10 +23,12 @@ export function coverArtSources(project) {/*** Release cover art: the square image Spotify (via DistroKid) and Suno show.- * Any image the project has can be the source; the title and artist tag are- * set on it by code, so the lettering stays sharp. "Make with Codex" asks an- * image backend for a fresh source, and the cover is composed from it when it- * lands.+ * Each song has its own design: the lettering and the photo, drafted from the+ * song and steered by what the director types. "Restyle" redrafts the+ * lettering from that direction (or adjusts it); "Make a new image" asks an+ * image backend for a fresh photo (or an adjusted take on the current one).+ * Any image the project has can be the photo; the title and artist are set+ * on it by code, so the lettering stays sharp.*/export default function CoverArtPanel({ project, publishKit }) {const art = project?.publishKit?.coverArt || {};@@ -37,15 +39,16 @@ export default function CoverArtPanel({ project, publishKit }) {const [tag, setTag] = useState(null);const [focusX, setFocusX] = useState(Number.isFinite(art.focusX) ? art.focusX : 0.5);const [notes, setNotes] = useState('');- const [likeness, setLikeness] = useState(false);- const busy = publishKit.composing;+ const [adjustImage, setAdjustImage] = useState(false);+ const busy = publishKit.composing || publishKit.designing;const chosen = art.source ? `${art.source.kind}:${art.source.filename}` : null;const look = () => ({ title: title.trim(), ...(tag !== null ? { tag: tag.trim() } : {}), focusX });const compose = (source) => publishKit.composeCover({ ...(source ? { source: { kind: source.kind, filename: source.filename } } : {}), ...look() });const generate = () => publishKit.generateCover({...(notes.trim() ? { notes: notes.trim() } : {}),- ...(likeness && art.source?.kind === 'image' ? { reference: { kind: 'image', filename: art.source.filename } } : {}),+ ...(adjustImage && art.source?.kind === 'image' ? { reference: { kind: 'image', filename: art.source.filename } } : {}),});+ const restyle = () => publishKit.designCover(notes.trim() ? { direction: notes.trim() } : {});return (<section aria-label="Cover art" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">@@ -108,22 +111,29 @@ export default function CoverArtPanel({ project, publishKit }) {</div><div className="space-y-1 rounded border border-port-border p-2">- <label htmlFor={idFor('notes')} className="block text-[11px] text-port-text-muted">Make a new cover image (optional: what it should show)</label>+ {art.rationale && <p className="text-port-text-muted">This song's look: {art.rationale}</p>}+ <label htmlFor={idFor('notes')} className="block text-[11px] text-port-text-muted">+ {art.design ? 'Adjust the style or the image (optional)' : 'Style direction for this song (optional)'}+ </label><textarea id={idFor('notes')} value={notes} maxLength={1500} rows={2} onChange={(e) => setNotes(e.target.value)}- placeholder="Close-up profile of the singer under flash"+ placeholder={art.design ? 'Bigger title, warmer light, less contrast' : 'Grainy black and white, tiny lowercase type'}className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />- <div className="flex flex-wrap items-center gap-3">- {art.source?.kind === 'image' && (- <label htmlFor={idFor('likeness')} className="flex items-center gap-1.5 min-h-[44px] sm:min-h-0">- <input id={idFor('likeness')} type="checkbox" checked={likeness} onChange={(e) => setLikeness(e.target.checked)} />- Keep the likeness of the current cover image- </label>- )}+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" onClick={restyle} disabled={busy}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 min-h-[44px] sm:min-h-0">+ <Sparkles size={13} /> {publishKit.designing ? 'Designing…' : (art.design ? 'Restyle the lettering' : 'Design the cover')}+ </button>{/* Never disabled by `pending`: the server tells a live render from one a restart lost. */}<button type="button" onClick={generate}className="flex items-center gap-1 bg-port-accent/20 text-port-accent rounded px-2 py-1.5 min-h-[44px] sm:min-h-0">- <Sparkles size={13} /> Make with Codex+ <ImageIcon size={13} /> Make a new image</button>+ {art.source?.kind === 'image' && (+ <label htmlFor={idFor('adjust-image')} className="flex items-center gap-1.5 min-h-[44px] sm:min-h-0">+ <input id={idFor('adjust-image')} type="checkbox" checked={adjustImage} onChange={(e) => setAdjustImage(e.target.checked)} />+ Start from the current image+ </label>+ )}</div></div></section>diff --git a/client/src/components/musicVideo/PublishKitPanel.test.jsx b/client/src/components/musicVideo/PublishKitPanel.test.jsxindex bf110440d4..77cebbcec2 100644--- a/client/src/components/musicVideo/PublishKitPanel.test.jsx+++ b/client/src/components/musicVideo/PublishKitPanel.test.jsx@@ -16,7 +16,7 @@ import PublishKitPanel from './PublishKitPanel.jsx';const hook = (over = {}) => ({building: false, progress: 0, build: vi.fn(), drafting: false, saving: false,draftCopy: vi.fn(async () => null), saveCopy: vi.fn(async () => null), selectThumbnail: vi.fn(async () => null),- composing: false, composeCover: vi.fn(async () => null), generateCover: vi.fn(async () => null), ...over,+ composing: false, composeCover: vi.fn(async () => null), designing: false, designCover: vi.fn(async () => null), generateCover: vi.fn(async () => null), ...over,});const built = {builtAt: '2026-01-01T00:00:00.000Z', master: { filename: 'master.mp4' },@@ -70,13 +70,21 @@ describe('PublishKitPanel (#9281)', () => {fireEvent.click(screen.getByRole('button', { name: 'Make the cover from Video frame 1' }));expect(k.composeCover).toHaveBeenLastCalledWith(expect.objectContaining({ source: { kind: 'thumbnail', filename: 't1.jpg' } }));- fireEvent.change(screen.getByLabelText(/Make a new cover image/), { target: { value: 'profile under flash' } });- fireEvent.click(screen.getByRole('button', { name: /Make with Codex/ }));- expect(k.generateCover).toHaveBeenCalledWith({ notes: 'profile under flash' });+ fireEvent.change(screen.getByLabelText(/Style direction for this song/), { target: { value: 'grainy black and white' } });+ fireEvent.click(screen.getByRole('button', { name: /Design the cover/ }));+ expect(k.designCover).toHaveBeenCalledWith({ direction: 'grainy black and white' });+ fireEvent.click(screen.getByRole('button', { name: /Make a new image/ }));+ expect(k.generateCover).toHaveBeenCalledWith({ notes: 'grainy black and white' });- const art = { filename: 'cover-1.jpg', title: 'Example Song', tag: 'Example Artist', source: { kind: 'image', filename: 'sheet.png' }, pending: { mode: 'codex' } };+ const art = { filename: 'cover-1.jpg', title: 'Example Song', tag: 'Example Artist', source: { kind: 'image', filename: 'sheet.png' }, pending: { mode: 'codex' }, design: { layout: 'top-center' }, rationale: 'Example reason.' };rerender(<PublishKitPanel project={{ ...project, publishKit: { ...built, coverArt: art } }} publishKit={k} />);expect(screen.getByAltText('Cover art for Example Song')).toBeTruthy();expect(screen.getByText(/Making a cover image on codex/)).toBeTruthy();+ expect(screen.getByText(/This song's look: Example reason/)).toBeTruthy();+ // With a design in place the same box adjusts it, and can start from the current image.+ fireEvent.change(screen.getByLabelText(/Adjust the style or the image/), { target: { value: 'warmer light' } });+ fireEvent.click(screen.getByLabelText('Start from the current image'));+ fireEvent.click(screen.getByRole('button', { name: /Make a new image/ }));+ expect(k.generateCover).toHaveBeenLastCalledWith({ notes: 'warmer light', reference: { kind: 'image', filename: 'sheet.png' } });});});diff --git a/client/src/hooks/useMusicVideoPublishKit.js b/client/src/hooks/useMusicVideoPublishKit.jsindex 4ba928a89d..bbb1fd4e79 100644--- a/client/src/hooks/useMusicVideoPublishKit.js+++ b/client/src/hooks/useMusicVideoPublishKit.js@@ -11,6 +11,7 @@ import {selectMusicVideoPublishThumbnail,composeMusicVideoCoverArt,generateMusicVideoCoverArt,+ designMusicVideoCoverArt,} from '../services/apiMusicVideo.js';import useSseJobSlot from './useSseJobSlot.js';@@ -28,6 +29,7 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}const [drafting, setDrafting] = useState(false);const [saving, setSaving] = useState(false);const [composing, setComposing] = useState(false);+ const [designing, setDesigning] = useState(false);const reload = (id) => {if (!id) return;@@ -98,6 +100,13 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}.catch(() => null).finally(() => setComposing(false));};+ const designCover = (body) => {+ setDesigning(true);+ return designMusicVideoCoverArt(projectId, body)+ .then(apply)+ .catch(() => null)+ .finally(() => setDesigning(false));+ };const generateCover = (body) => generateMusicVideoCoverArt(projectId, body).then(apply).catch(() => null);return {@@ -112,6 +121,8 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}selectThumbnail,composing,composeCover,+ designing,+ designCover,generateCover,};}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 48edce0964..465a568667 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -248,6 +248,8 @@ export const selectMusicVideoPublishThumbnail = (id, filename, options = {}) =>// (the result arrives over the `music-video:cover-art` socket event).export const composeMusicVideoCoverArt = (id, body, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art`, { method: 'POST', body: JSON.stringify(body || {}), ...options });+export const designMusicVideoCoverArt = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/design`, { method: 'POST', body: JSON.stringify(body || {}), ...options });export const generateMusicVideoCoverArt = (id, body, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/generate`, { method: 'POST', body: JSON.stringify(body || {}), ...options });// ---- Posting (#9282) ----diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex cb8c6d83bf..0033607ef8 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -695,6 +695,11 @@ export const musicVideoCoverArtComposeSchema = z.object({tag: z.string().max(24).optional(),focusX: z.number().min(0).max(1).optional(),}).strict();+export const musicVideoCoverArtDesignSchema = z.object({+ direction: z.string().max(1500).optional(),+ providerId: z.string().min(1).max(200).optional(),+ model: z.string().min(1).max(200).optional(),+}).strict();export const musicVideoCoverArtGenerateSchema = z.object({notes: z.string().max(1500).optional(),reference: z.object({ kind: z.literal('image'), filename: z.string().min(1).max(300) }).strict().optional(),diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 36922c2188..c12c4cf93f 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -47,6 +47,7 @@ import {musicVideoPublishThumbnailSchema,musicVideoCoverArtComposeSchema,musicVideoCoverArtGenerateSchema,+ musicVideoCoverArtDesignSchema,musicVideoPublishTargetSchema,musicVideoPublishPrepareSchema,musicVideoPublishPlatformsPatchSchema,@@ -914,8 +915,9 @@ router.put('/:id/publish-kit/thumbnail', asyncHandler(async (req, res) => {res.json({ project });}));-// Release cover art: compose from a chosen image, or queue a fresh source-// image whose completion hook composes the cover.+// Release cover art: the song's own design (drafted, or adjusted from the+// director's direction), compose from a chosen image, or queue a fresh cover+// photo whose completion hook composes the cover.router.post('/:id/publish-kit/cover-art', asyncHandler(async (req, res) => {const input = validateRequest(musicVideoCoverArtComposeSchema, req.body || {});const { composeProjectCoverArt } = await import('../services/musicVideo/coverArt.js');@@ -923,6 +925,13 @@ router.post('/:id/publish-kit/cover-art', asyncHandler(async (req, res) => {res.json({ project });}));+router.post('/:id/publish-kit/cover-art/design', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoCoverArtDesignSchema, req.body || {});+ const { designCoverArt } = await import('../services/musicVideo/coverArt.js');+ const { project } = await designCoverArt(req.params.id, input);+ res.json({ project });+}));+router.post('/:id/publish-kit/cover-art/generate', asyncHandler(async (req, res) => {const input = validateRequest(musicVideoCoverArtGenerateSchema, req.body || {});const { generateCoverArtSource } = await import('../services/musicVideo/coverArt.js');diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex 44e6a43e7c..d2cf254f3e 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -91,6 +91,7 @@ const defaults = {attachAudio: async (trackId, filename, take) => (await import('../trackAudioAttach.js')).attachAudioAsRender(trackId, filename, take),probeDuration: (filename) => probeVideoDuration(join(PATHS.music, filename)).catch(() => null),analyzeSong: async (projectId) => (await import('./projectAudio.js')).analyzeProjectSong(projectId),+ designCoverArt: async (projectId, input) => (await import('./coverArt.js')).designCoverArt(projectId, input),startProduction: async (...args) => (await import('./productionService.js')).startProduction(...args),generateDocument: async (...args) => (await import('./documentGeneration.js')).generateMixedMediaDocument(...args),acceptDocument: async (...args) => (await import('./documentGeneration.js')).acceptMixedMediaDocument(...args),@@ -388,8 +389,15 @@ const STAGES = {return { output: { trackId: track.id, sunoSongIds: song.songIds } };},- async analyze({ project }) {+ async analyze({ project, run }) {await deps.analyzeSong(project.id);+ // The single's own cover design, drafted from the song just made, ready+ // for the publishing kit. Best-effort: a failed draft never stops the video.+ if (!project.publishKit?.coverArt?.design) {+ const { providerId, model } = await llmOf(run, 'brief');+ await deps.designCoverArt(project.id, { providerId: providerId || null, model: model || null })+ .catch((err) => console.warn(`⚠️ Autonomous music video ${short(run.id)} cover design skipped: ${trimTo(err.message, 200)}`));+ }return { output: {} };},diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex 2bf70d7ab3..4e49a293ac 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -90,6 +90,7 @@ beforeEach(() => {attachAudio: stub('attach', async () => ({})),probeDuration: stub('probe', async () => 187),analyzeSong: stub('analyze', async () => ({})),+ designCoverArt: vi.fn(async () => ({})),startProduction: stub('production', async () => ({ run: { id: 'mvpr-1' } })),generateCode: stub('code', async () => ({})),generateDocument: stub('document', async () => ({ document: { directory: 'music-video/mv-auto/composition/example' } })),@@ -117,6 +118,8 @@ describe('startAutonomousVideo', () => {expect(calls).toEqual(['createProject', 'brief', 'updateProject', 'lyrics', 'board', 'updateProject', 'suno', 'track', 'probe', 'attach', 'updateProject', 'analyze', 'production']);expect(runOf()).toMatchObject({ status: 'running', stage: 'produce' });expect(runOf().output).toMatchObject({ trackId: 'track-1', moodBoardId: 'board-1', productionRunId: 'mvpr-1', sunoSongIds: ['song-a', 'song-b'] });+ // The made song gets its own single cover design, ready in the publishing kit.+ expect(doubles.designCoverArt).toHaveBeenCalledWith('mv-auto', { providerId: null, model: null });expect(doubles.startProduction).toHaveBeenCalledWith('mv-auto', expect.objectContaining({pool: [{ kind: 'image', mode: 'local', model: 'flux2-dev' }, { kind: 'video', mode: 'local' }],limits: { maxGenerations: 40, maxReviewAttempts: 3 },diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex 401f50b79b..5ef84f547f 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -139,7 +139,7 @@ async function fail(projectId, reason, error = null) {* then the brief's other queueable image tools in catalog order, then the* install's Music Video render default. Returns `{ mode, model }` or null.*/-export async function chooseCastAndSetsRoute(project, { preferred = null, settings } = {}) {+async function chooseCastAndSetsRoute(project, { preferred = null, settings } = {}) {if (deps.resolveRoute) return deps.resolveRoute(project, { preferred, settings });const { resolveRenderTargetConfig } = await import('../imageGen/cloudProviderConfig.js');// A mode is usable when it rides the queue and, for a cloud backend, itsdiff --git a/server/services/musicVideo/coverArt.js b/server/services/musicVideo/coverArt.jsindex 68e83b21c2..593241ccac 100644--- a/server/services/musicVideo/coverArt.js+++ b/server/services/musicVideo/coverArt.js@@ -3,14 +3,17 @@** `project.publishKit.coverArt` holds one composed square cover: a source* image (a kit thumbnail or any gallery image, Cast & Sets renders included)- * cropped square with the title set on a split-flap row by code- * (coverArtCompose.js). The director can also ask an image backend (Codex- * first) for a fresh source; that job is tagged `musicVideo: { projectId,- * coverArt: { requestId } }` and musicVideoCoverArtImageHook.js composes the- * cover from it when it lands. Nothing here runs without a director action- * (AI Provider Usage Policy).+ * cropped square with the title and artist set over it by code, in the song's+ * own design (coverArtCompose.js). The design is drafted per song by one+ * provider call from the song and the director's direction, and redrafted+ * from their adjustments (coverArtDesign.js). The install's default image generator+ * makes the cover photo from the design's image prompt; that job is tagged+ * `musicVideo: { projectId, coverArt: { requestId } }` and+ * musicVideoCoverArtImageHook.js composes the cover from it when it lands.+ * Nothing here runs without a director action (AI Provider Usage Policy).** coverArt: { filename, source: { kind, filename }, title, tag, focusX,+ * design, imagePrompt, rationale, direction, designedAt,* composedAt, generated: [galleryFilename…],* pending: { requestId, jobId, mode, requestedAt } | null,* lastError: string | null }@@ -23,7 +26,8 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { safeUnder } from '../../lib/ffmpeg.js';import { resolveGalleryImage } from '../../lib/pathSafety.js';import { trimTo } from '../../lib/textUtils.js';-import { composeCoverArt } from './coverArtCompose.js';+import { composeCoverArt, normalizeCoverDesign } from './coverArtCompose.js';+import { buildCoverDesignPrompt, parseCoverDesign } from './coverArtDesign.js';import { musicVideoEvents } from './events.js';import { getProject, mutateProjectRecord } from './projects.js';import { projectPublishKit, releaseKitFiles } from './publishKit.js';@@ -32,7 +36,7 @@ const MAX_GENERATED = 12;const LIVE_JOB = new Set(['queued', 'running', 'canceling']);// A reservation that never got its job id (the process died mid-enqueue) stops blocking after this.const RESERVATION_TTL_MS = 2 * 60 * 1000;-// Codex renders square at 1024; the compose scales it to the store size.+// Cover photos render square at 1024; the compose scales them to the store size.const SOURCE_PX = 1024;const defaults = {@@ -40,14 +44,29 @@ const defaults = {getSettings: async () => (await import('../settings.js')).getSettings(),getPlatforms: async () => (await import('./publish/platforms.js')).getPublishPlatforms(),enqueue: async (job) => (await import('../mediaJobQueue/index.js')).enqueueJob(job),- chooseRoute: async (project, opts) => (await import('./castAndSetsService.js')).chooseCastAndSetsRoute(project, opts),+ defaultRoute: async (settings) => defaultImageRoute(settings),imageParams: async (settings, route, common) => (await import('./castAndSetsService.js')).imageJobParams(settings, route, common),withStyle: async (...args) => (await import('./styleReferences.js')).withMusicVideoStyle(...args),jobStatus: async (jobId) => (await import('../mediaJobQueue/index.js')).getJob(jobId)?.status || null,+ runner: async () => import('../promptRunner.js'),};let deps = { ...defaults };export function __setCoverArtDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }+/**+ * The install's own image generator for music videos: the Music Video render+ * default, else the PortOS image default (local, Codex, Grok, …). Null when+ * that backend cannot take a queued job or its cloud toggle is off.+ */+async function defaultImageRoute(settings) {+ const [{ resolveRenderTargetConfig }, { QUEUEABLE_IMAGE_MODES }, { RENDER_TARGET }] = await Promise.all([+ import('../imageGen/cloudProviderConfig.js'), import('../../lib/generationModes.js'), import('../../lib/renderTargets.js'),+ ]);+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, { usableInstallFallback: true });+ if (!QUEUEABLE_IMAGE_MODES.includes(resolved.mode) || (resolved.cloud && !resolved.cloud.enabled)) return null;+ return { mode: resolved.mode, model: null };+}+const coverError = (status, code, message) => new ServerError(message, { status, code });export const projectCoverArt = (project) => {const art = projectPublishKit(project).coverArt;@@ -110,7 +129,7 @@ export async function composeProjectCoverArt(projectId, { source = null, title,if (!next.title) throw coverError(422, 'VALIDATION_ERROR', 'Give the cover a title');await ensureDir(PATHS.videoThumbnails);const filename = `cover-${String(projectId).slice(3, 11)}-${randomUUID().slice(0, 8)}.jpg`;- await deps.compose({ ...next, source: path, out: safeUnder(PATHS.videoThumbnails, filename) });+ await deps.compose({ ...next, design: art.design || null, source: path, out: safeUnder(PATHS.videoThumbnails, filename) });// The JPEG is written in place; the row that first names it commits under a backup lease (#9982).const out = await withBackupAssetPublication(() => writeCoverArt(projectId, () => ({...next, filename, composedAt: new Date().toISOString(), lastError: null,@@ -121,18 +140,55 @@ export async function composeProjectCoverArt(projectId, { source = null, title,return { project: out.project };}-/** The image prompt for a fresh cover source: the singer, the look, and room for the title. */-function buildCoverArtPrompt(project, { notes = '' } = {}) {+/**+ * Draft this song's cover design (lettering and the photo to make) in one+ * provider call. With a design already in place, `direction` adjusts it. An+ * existing cover is recomposed in the new lettering at once; a new photo+ * waits for "Make a cover image".+ */+export async function designCoverArt(projectId, { direction = '', providerId = null, model = null } = {}) {+ const project = await requireProject(projectId);+ const art = projectCoverArt(project);+ const { resolveProviderAndModel, runPromptThroughProvider } = await deps.runner();+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ if (!provider) throw coverError(503, 'NO_PROVIDER', 'No AI provider is available to design the cover');+ const previous = art.design ? { design: art.design, imagePrompt: art.imagePrompt || '' } : null;+ const prompt = buildCoverDesignPrompt(project, { direction: trimTo(direction, 1500), previous });+ const { text } = await runPromptThroughProvider({ provider, model: selectedModel, prompt, source: 'music-video-cover-design' });+ const drafted = parseCoverDesign(text);+ if (!drafted) throw coverError(502, 'COVER_DESIGN_UNPARSEABLE', 'The cover design came back without a usable design. Try again or another model');+ const out = await writeCoverArt(projectId, () => ({+ design: drafted.design,+ imagePrompt: drafted.imagePrompt || art.imagePrompt || '',+ rationale: drafted.rationale,+ direction: trimTo(direction, 1500),+ designedAt: new Date().toISOString(),+ lastError: null,+ }));+ console.log(`🖼️ Music Video cover art ${String(projectId).slice(3, 11)}: design ${previous ? 'adjusted' : 'drafted'} (${drafted.design.layout}, ${drafted.design.typeface})`);+ if (art.source) return composeProjectCoverArt(projectId);+ publish(projectId, out.project);+ return { project: out.project };+}++// Where the photo should stay calm, so the title reads over it.+const QUIET_AREA = {+ 'bottom-left': 'the lower left', 'bottom-center': 'the bottom', 'top-left': 'the upper left',+ 'top-center': 'the top', center: 'the middle', 'vertical-left': 'the left edge',+};++/** The image prompt for a cover photo: the design's own photo when drafted, adjusted by `notes`. */+function buildCoverArtPrompt(project, art, { notes = '' } = {}) {const direction = project?.castAndSets?.direction || {};const p = direction.protagonist || {};const subject = trimTo([p.face, p.hair, p.signature].filter(Boolean).join('; '), 600);const look = trimTo(direction.look || project?.concept?.style, 600);+ const layout = normalizeCoverDesign(art.design).layout;return [`Square single cover photograph for the song "${trimTo(project?.name || 'Untitled', 120)}".`,- trimTo(notes, 1500) || `A tight close-up portrait of the lead singer${subject ? `: ${subject}` : ''}.`,- look ? `Look: ${look}.` : '',- 'Editorial flash photography: hard on-camera flash, deep shadows, rich color, sharp focus on the eyes.',- 'Keep the bottom fifth of the frame simple and dark, since a title band is set over it later.',+ art.imagePrompt || [`A close-up portrait of the lead singer${subject ? `: ${subject}` : ''}.`, look ? `Look: ${look}.` : ''].filter(Boolean).join(' '),+ notes ? `Adjustment from the artist: ${trimTo(notes, 1500)}` : '',+ `Keep ${QUIET_AREA[layout]} of the frame calm, since the title is set there later.`,'No text, letters, logos, or watermark anywhere in the image.',].filter(Boolean).join(' ');}@@ -149,19 +205,26 @@ async function pendingIsLive(pending) {}/**- * Ask an image backend (Codex when enabled) for a new cover source. The+ * Ask the install's default image generator for a new cover source. The* completion hook composes the cover from it with the current title and tag.- * `reference` (a gallery image) keeps the singer's likeness; it defaults to- * the Cast & Sets character sheet.+ * `reference` (a gallery image) keeps the singer's likeness, or is the image+ * `notes` adjusts; it defaults to the Cast & Sets character sheet. A song with+ * no design yet gets one first, steered by `notes`.*/export async function generateCoverArtSource(projectId, { notes = '', reference = null } = {}) {- const project = await requireProject(projectId);+ let project = await requireProject(projectId);const previous = projectCoverArt(project).pending;if (await pendingIsLive(previous)) throw coverError(409, 'COVER_ART_IN_PROGRESS', 'A cover image is already being made');+ if (!projectCoverArt(project).design) {+ const designed = await designCoverArt(projectId, { direction: notes }).then(() => true).catch((err) => {+ console.warn(`⚠️ Music Video cover art ${String(projectId).slice(3, 11)}: no design drafted (${err.message}); using the plain look`);+ return false;+ });+ if (designed) { project = await requireProject(projectId); notes = ''; }+ }const settings = await deps.getSettings();- const route = await deps.chooseRoute(project, { preferred: { mode: 'codex' }, settings })- || await deps.chooseRoute(project, { settings });- if (!route) throw coverError(409, 'COVER_ART_ROUTE_UNAVAILABLE', 'No image backend is enabled for music videos. Turn on Codex image generation and try again');+ const route = await deps.defaultRoute(settings);+ if (!route) throw coverError(409, 'COVER_ART_ROUTE_UNAVAILABLE', 'Image generation is not set up. Choose an image generator in Settings and try again');const refName = reference?.filename || project.castAndSets?.images?.character?.imageId || null;const refPath = refName ? resolveGalleryImage(refName) : null;if (reference?.filename && !refPath) throw coverError(422, 'PUBLISH_ASSET_MISSING', `The reference image is missing (${basename(reference.filename)})`);@@ -174,7 +237,7 @@ export async function generateCoverArtSource(projectId, { notes = '', referencereturn { pending: { requestId, jobId: null, mode: route.mode, requestedAt: new Date().toISOString() }, lastError: null };});const common = {- prompt: buildCoverArtPrompt(project, { notes }),+ prompt: buildCoverArtPrompt(project, projectCoverArt(project), { notes }),width: SOURCE_PX,height: SOURCE_PX,...(refPath ? { referenceImagePaths: [refPath], referenceImageStrengths: [1] } : {}),diff --git a/server/services/musicVideo/coverArt.test.js b/server/services/musicVideo/coverArt.test.jsindex 6ef9d9d328..bc543b8886 100644--- a/server/services/musicVideo/coverArt.test.js+++ b/server/services/musicVideo/coverArt.test.js@@ -26,13 +26,17 @@ afterAll(() => cleanupTempDataRoots());const compose = vi.fn(async ({ out }) => { await writeFile(out, 'jpeg'); return { width: 3000, height: 3000 }; });const enqueue = vi.fn(async () => ({ jobId: 'job-example' }));const jobStatus = vi.fn(async () => 'queued');-const chooseRoute = vi.fn(async (_project, { preferred } = {}) => (preferred?.mode === 'codex' ? { mode: 'codex', model: null } : null));+const DRAFT = { imagePrompt: 'Example image prompt: a grainy profile in blue light', rationale: 'Example reason.', design: { layout: 'top-center', typeface: 'serif', weight: 'light', letterCase: 'lower', titleColor: '#f0e6d2', accentColor: '#3366ff', backdrop: 'none', tagStyle: 'plain' } };+const runPrompt = vi.fn(async () => ({ text: JSON.stringify(DRAFT) }));+const defaultRoute = vi.fn(async () => ({ mode: 'grok', model: null }));beforeEach(() => {- compose.mockClear(); enqueue.mockReset(); enqueue.mockResolvedValue({ jobId: 'job-example' }); chooseRoute.mockClear();+ compose.mockClear(); enqueue.mockReset(); enqueue.mockResolvedValue({ jobId: 'job-example' }); defaultRoute.mockClear();jobStatus.mockReset(); jobStatus.mockResolvedValue('queued');+ runPrompt.mockReset(); runPrompt.mockResolvedValue({ text: JSON.stringify(DRAFT) });cover.__setCoverArtDepsForTests({- compose, enqueue, chooseRoute, jobStatus,+ compose, enqueue, defaultRoute, jobStatus,+ runner: async () => ({ resolveProviderAndModel: async () => ({ provider: { id: 'example-provider' }, selectedModel: null }), runPromptThroughProvider: runPrompt }),getSettings: async () => ({}),getPlatforms: async () => ({ distrokid: { enabled: true, account: 'Example Artist' } }),imageParams: async (_settings, route, common) => ({ ...common, provider: route.mode }),@@ -82,14 +86,19 @@ describe('release cover art', () => {expect(compose).not.toHaveBeenCalled();});- it('queues one tagged cover image on Codex, then composes the cover from it when it lands', async () => {+ it('queues one tagged cover image on the default image generator, then composes the cover from it when it lands', async () => {const { id } = await projectWithThumbnail();const { project } = await cover.generateCoverArtSource(id, { notes: 'Close-up profile of the singer' });- expect(project.publishKit.coverArt.pending).toMatchObject({ jobId: 'job-example', mode: 'codex' });+ expect(project.publishKit.coverArt.pending).toMatchObject({ jobId: 'job-example', mode: 'grok' });+ // No design yet: the song's own design is drafted first, steered by the notes.+ expect(runPrompt.mock.calls[0][0]).toMatchObject({ source: 'music-video-cover-design' });+ expect(runPrompt.mock.calls[0][0].prompt).toContain('Close-up profile of the singer');+ expect(project.publishKit.coverArt.design).toMatchObject({ layout: 'top-center', typeface: 'serif' });const { requestId } = project.publishKit.coverArt.pending;const job = enqueue.mock.calls[0][0];- expect(job).toMatchObject({ kind: 'image', params: { width: 1024, height: 1024, provider: 'codex', musicVideo: { projectId: id, coverArt: { requestId } } } });- expect(job.params.prompt).toContain('Close-up profile of the singer');+ expect(job).toMatchObject({ kind: 'image', params: { width: 1024, height: 1024, provider: 'grok', musicVideo: { projectId: id, coverArt: { requestId } } } });+ expect(job.params.prompt).toContain('Example image prompt');+ expect(job.params.prompt).toContain('Keep the top of the frame calm');expect(job.params.prompt).toContain('No text');await expect(cover.generateCoverArtSource(id)).rejects.toMatchObject({ status: 409, code: 'COVER_ART_IN_PROGRESS' });@@ -145,9 +154,43 @@ describe('release cover art', () => {expect(enqueue).toHaveBeenCalledTimes(2);});- it('says so when no image backend is enabled', async () => {+ it("drafts the song's own lettering, adjusts it from a direction, and re-sets an existing cover in it", async () => {+ const { id, thumb } = await projectWithThumbnail();+ await cover.composeProjectCoverArt(id, { source: { kind: 'thumbnail', filename: thumb } });+ expect(compose.mock.calls[0][0].design).toBeNull();++ const drafted = (await cover.designCoverArt(id, { direction: 'quiet and tiny type' })).project.publishKit.coverArt;+ expect(drafted).toMatchObject({ design: { layout: 'top-center', weight: 'light' }, imagePrompt: DRAFT.imagePrompt, rationale: 'Example reason.', direction: 'quiet and tiny type' });+ expect(compose.mock.calls.at(-1)[0].design).toMatchObject({ layout: 'top-center', typeface: 'serif' });++ // An adjustment sends the current design along to be revised.+ runPrompt.mockResolvedValueOnce({ text: JSON.stringify({ ...DRAFT, design: { ...DRAFT.design, scale: 'large', weight: 'banana' } }) });+ const adjusted = (await cover.designCoverArt(id, { direction: 'make the title bigger' })).project.publishKit.coverArt;+ expect(runPrompt.mock.calls.at(-1)[0].prompt).toContain('"layout":"top-center"');+ // An option outside the vocabulary falls back rather than reaching the renderer.+ expect(adjusted.design).toMatchObject({ scale: 'large', weight: 'bold' });++ runPrompt.mockResolvedValueOnce({ text: 'no json here' });+ await expect(cover.designCoverArt(id)).rejects.toMatchObject({ status: 502, code: 'COVER_DESIGN_UNPARSEABLE' });+ });++ it("queues on the install's own default image generator, never a fixed one", async () => {+ const { id } = await projectWithThumbnail();+ cover.__setCoverArtDepsForTests({+ compose, enqueue, jobStatus,+ runner: async () => ({ resolveProviderAndModel: async () => ({ provider: { id: 'example-provider' }, selectedModel: null }), runPromptThroughProvider: runPrompt }),+ getSettings: async () => ({ imageGen: { mode: 'local' } }),+ getPlatforms: async () => ({}),+ imageParams: async (_settings, route, common) => ({ ...common, provider: route.mode }),+ withStyle: async (_project, params) => params,+ });+ await cover.generateCoverArtSource(id);+ expect(enqueue.mock.calls[0][0].params.provider).toBe('local');+ });++ it('says so when image generation is not set up', async () => {const { id } = await projectWithThumbnail();- chooseRoute.mockResolvedValue(null);+ defaultRoute.mockResolvedValueOnce(null);await expect(cover.generateCoverArtSource(id)).rejects.toMatchObject({ status: 409, code: 'COVER_ART_ROUTE_UNAVAILABLE' });expect(enqueue).not.toHaveBeenCalled();});@@ -164,6 +207,11 @@ describe('cover lettering', () => {await composeCoverArt({ source, out, title: 'Example Song', tag: 'Example Artist', size: 1000 });const meta = await sharp(out).metadata();expect(meta).toMatchObject({ format: 'jpeg', width: 1000, height: 1000 });+ // Every layout renders (the vertical one rotates its line).+ for (const layout of ['top-center', 'center', 'vertical-left']) {+ await composeCoverArt({ source, out, title: 'A Much Longer Example Song Title Here', tag: 'Example Artist', design: { layout, backdrop: 'band', tagStyle: 'boxed', rule: true }, size: 600 });+ expect(await sharp(out).metadata()).toMatchObject({ width: 600, height: 600 });+ }// A portrait phone photo stored landscape with an EXIF rotation crops on the upright image.const rotated = join(dir, 'rotated.jpg');diff --git a/server/services/musicVideo/coverArtCompose.js b/server/services/musicVideo/coverArtCompose.jsindex 27e2a5346b..bd8163c0b1 100644--- a/server/services/musicVideo/coverArtCompose.js+++ b/server/services/musicVideo/coverArtCompose.js@@ -1,79 +1,200 @@/*** Music Video cover art: one square image for the song's release (Spotify via- * DistroKid, Suno). A photo or still, cropped square, with the title set by- * code on a split-flap row along the bottom (one capital per tile, like a- * departure board), a thin accent rule above it, and an accent tag top right.- * Lettering is set here rather than drawn by an image model, so it stays crisp.+ * DistroKid, Suno). A photo or still, cropped square, with the title and the+ * artist set by code from the song's own cover design: where the title sits,+ * its typeface, weight, case, spacing and colors, and what sits behind it.+ * Each song gets its own design (coverArt.js drafts it from the song); this+ * module only renders one. Lettering is set here rather than drawn by an image+ * model, so it stays crisp.** Pure apart from the files it reads and writes; `sharp` is loaded lazily so* the many suites that reach the publish services never pay for it.*/export const COVER_ART_SIZE = 3000;-export const COVER_ART_ACCENT = '#ff6a2b';-// Lines longer than this wrap at a word; tiles shrink to fit the longest line.-const MAX_LINE = 14;++// The vocabulary a design is written in (the drafting prompt offers exactly these).+export const COVER_DESIGN_OPTIONS = Object.freeze({+ layout: ['bottom-left', 'bottom-center', 'top-left', 'top-center', 'center', 'vertical-left'],+ typeface: ['sans', 'condensed', 'serif', 'mono'],+ weight: ['light', 'regular', 'bold', 'black'],+ letterCase: ['upper', 'lower', 'as-written'],+ scale: ['small', 'medium', 'large'],+ backdrop: ['none', 'fade', 'band', 'box'],+ tagStyle: ['plain', 'boxed', 'none'],+});++export const DEFAULT_COVER_DESIGN = Object.freeze({+ layout: 'bottom-left', typeface: 'sans', weight: 'bold', letterCase: 'upper', scale: 'medium',+ tracking: 0.02, titleColor: '#ffffff', accentColor: '#ffffff', backdrop: 'fade', tagStyle: 'plain', rule: false,+});++// Font stacks: the first face a Mac has, then what a Linux install has. `width`+// is the average advance per character as a fraction of the font size.+const FACES = {+ sans: { family: "'Helvetica Neue','Helvetica','Arial','DejaVu Sans',sans-serif", width: 0.6 },+ condensed: { family: "'Futura Condensed ExtraBold','Avenir Next Condensed','Impact','Arial Narrow','DejaVu Sans Condensed',sans-serif", width: 0.46 },+ serif: { family: "'Didot','Bodoni 72','Georgia','DejaVu Serif',serif", width: 0.58 },+ mono: { family: "'Menlo','SF Mono','DejaVu Sans Mono',monospace", width: 0.62 },+};+const WEIGHTS = { light: 300, regular: 400, bold: 700, black: 900 };+const SCALES = { small: 0.075, medium: 0.11, large: 0.16 };+const HEX = /^#[0-9a-f]{6}$/i;+const ASCENT = 0.78;+const MARGIN = 0.065;const escapeXml = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c]);+const pick = (value, list, fallback) => (list.includes(value) ? value : fallback);+const n = (v) => v.toFixed(1);++/** A design with every field valid: unknown or missing values take the default's. */+export function normalizeCoverDesign(design = {}) {+ const d = design && typeof design === 'object' ? design : {};+ const out = {};+ for (const [key, list] of Object.entries(COVER_DESIGN_OPTIONS)) out[key] = pick(d[key], list, DEFAULT_COVER_DESIGN[key]);+ const tracking = Number(d.tracking);+ out.tracking = Number.isFinite(tracking) ? Math.min(0.3, Math.max(-0.05, tracking)) : DEFAULT_COVER_DESIGN.tracking;+ out.titleColor = HEX.test(d.titleColor || '') ? d.titleColor : DEFAULT_COVER_DESIGN.titleColor;+ out.accentColor = HEX.test(d.accentColor || '') ? d.accentColor : DEFAULT_COVER_DESIGN.accentColor;+ out.rule = d.rule === true;+ return out;+}++const caseOf = (text, letterCase) => (letterCase === 'upper' ? text.toUpperCase() : letterCase === 'lower' ? text.toLowerCase() : text);-/** The title in capitals, broken into split-flap lines of at most MAX_LINE characters (at most 3). */-function coverTitleLines(title) {- const words = String(title || '').toUpperCase().replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);+/** Break the title into at most 3 lines of about `perLine` characters, at word boundaries. */+function titleLines(title, perLine) {+ const words = String(title || '').replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);const lines = [];for (const word of words) {const last = lines[lines.length - 1];- if (last !== undefined && last.length + 1 + word.length <= MAX_LINE) lines[lines.length - 1] = `${last} ${word}`;- else lines.push(word.slice(0, MAX_LINE * 2));+ if (last !== undefined && last.length + 1 + word.length <= perLine) lines[lines.length - 1] = `${last} ${word}`;+ else lines.push(word);}- return lines.slice(0, 3);+ return lines.length > 3 ? [...lines.slice(0, 2), lines.slice(2).join(' ')] : lines;}-/** The overlay as SVG: split-flap title rows, the accent rule above them, and the tag top right. */-function coverOverlaySvg({ title, tag = '', accent = COVER_ART_ACCENT, size = COVER_ART_SIZE }) {- const lines = coverTitleLines(title);- const margin = Math.round(size * 0.04);- const longest = Math.max(1, ...lines.map((l) => l.length));- const gap = size * 0.006;- const tileW = Math.min(size * 0.085, (size - 2 * margin - gap * (longest - 1)) / longest);- const tileH = tileW * 1.38;- const lineGap = tileH * 0.14;- const font = "'Menlo','DejaVu Sans Mono','Liberation Mono',monospace";+const titleFont = (d, fontSize) => `font-family="${FACES[d.typeface].family}" font-weight="${WEIGHTS[d.weight]}" letter-spacing="${n(d.tracking * fontSize)}"`;+const tagFont = (d, fontSize) => `font-family="${FACES[d.typeface].family}" font-weight="${Math.max(400, WEIGHTS[d.weight] - 200)}" letter-spacing="${n(0.08 * fontSize)}"`;++/** The title's lines as the design sets them (one line when it runs up the edge). */+function titleLinesFor(title, d, size) {+ const text = caseOf(String(title || '').trim(), d.letterCase);+ if (d.layout === 'vertical-left') return [text];+ const room = size * (1 - 2 * MARGIN);+ return titleLines(text, Math.max(6, Math.round(room / (size * SCALES[d.scale] * FACES[d.typeface].width * (1 + d.tracking)))));+}++/**+ * The title block: lines, size and where it sits, plus whatever the design+ * puts behind it. `widthOf(text)` is the text's rendered width at a 1px font+ * size (measured by composeCoverArt, since the face a stack resolves to varies+ * by machine); without it the face's average advance stands in.+ */+function titleParts(title, d, size, widthOf) {+ const face = FACES[d.typeface];+ const margin = size * MARGIN;+ const room = size - 2 * margin;+ const ink = (fontSize) => `${titleFont(d, fontSize)} fill="${d.titleColor}"`;const parts = [];- let y = size - margin - lines.length * tileH - (lines.length - 1) * lineGap;- const ruleY = y - tileH * 0.28;- parts.push(`<rect x="${margin}" y="${ruleY.toFixed(1)}" width="${size - 2 * margin}" height="${(size * 0.004).toFixed(1)}" fill="${accent}"/>`);- for (const line of lines) {- const rowW = line.length * tileW + (line.length - 1) * gap;- let x = (size - rowW) / 2;- for (const ch of line) {- parts.push(`<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${tileW.toFixed(1)}" height="${tileH.toFixed(1)}" rx="${(tileW * 0.09).toFixed(1)}" fill="#111" fill-opacity="0.9"/>`);- if (ch !== ' ') {- parts.push(`<text x="${(x + tileW / 2).toFixed(1)}" y="${(y + tileH * 0.72).toFixed(1)}" font-family="${font}" font-weight="700" font-size="${(tileH * 0.66).toFixed(1)}" fill="#f4f1ea" text-anchor="middle">${escapeXml(ch)}</text>`);- }- // The flap's split: a hairline across the middle of every tile.- parts.push(`<rect x="${x.toFixed(1)}" y="${(y + tileH / 2 - size * 0.0008).toFixed(1)}" width="${tileW.toFixed(1)}" height="${(size * 0.0016).toFixed(1)}" fill="#000" fill-opacity="0.75"/>`);- x += tileW + gap;+ const defs = [];+ const lines = titleLinesFor(title, d, size);+ const unitW = (line) => widthOf?.(line) ?? line.length * face.width * (1 + d.tracking);+ const unitWidest = Math.max(0.001, ...lines.map(unitW));++ if (d.layout === 'vertical-left') {+ // One line reading bottom to top along the left edge.+ const text = lines[0];+ const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);+ if (d.backdrop !== 'none') {+ parts.push(`<rect x="0" y="0" width="${n(margin * 2 + fontSize)}" height="${size}" fill="${d.backdrop === 'band' ? d.accentColor : '#000'}" fill-opacity="${d.backdrop === 'band' ? 1 : 0.6}"/>`);}- y += tileH + lineGap;+ parts.push(`<text transform="translate(${n(margin + fontSize * ASCENT)} ${n(size - margin)}) rotate(-90)" ${ink(fontSize)} font-size="${n(fontSize)}">${escapeXml(text)}</text>`);+ return { parts, defs };}- const tagText = String(tag || '').trim().slice(0, 24);- if (tagText) {- const fontSize = size * 0.032;- const padX = fontSize * 0.55;- const w = tagText.length * fontSize * 0.62 + padX * 2;- const h = fontSize * 1.55;- const x = size - margin - w;- parts.push(`<rect x="${x.toFixed(1)}" y="${margin}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" fill="${accent}"/>`);- parts.push(`<text x="${(x + w / 2).toFixed(1)}" y="${(margin + h * 0.7).toFixed(1)}" font-family="'Helvetica Neue','Arial','DejaVu Sans',sans-serif" font-weight="800" font-size="${fontSize.toFixed(1)}" fill="#1a1a1a" text-anchor="middle">${escapeXml(tagText)}</text>`);++ const center = d.layout.endsWith('center');+ const atTop = d.layout.startsWith('top');+ // As large as the design's scale allows; a long title shrinks to fit.+ const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);+ const lineH = fontSize * 1.08;+ const blockH = lineH * (lines.length - 1) + fontSize * ASCENT;+ const widest = Math.min(room, unitWidest * fontSize);+ const x = center ? size / 2 : margin;+ const left = center ? (size - widest) / 2 : margin;+ const top = atTop ? margin + size * 0.06 : d.layout === 'center' ? (size - blockH) / 2 : size - margin - blockH;++ if (d.backdrop === 'fade' && d.layout !== 'center') {+ defs.push(`<linearGradient id="fade" x1="0" y1="${atTop ? 1 : 0}" x2="0" y2="${atTop ? 0 : 1}"><stop offset="0" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity="0.7"/></linearGradient>`);+ const h = blockH + margin * 3;+ parts.push(`<rect x="0" y="${n(atTop ? 0 : size - h)}" width="${size}" height="${n(h)}" fill="url(#fade)"/>`);+ } else if (d.backdrop === 'band') {+ const pad = fontSize * 0.35;+ parts.push(`<rect x="0" y="${n(top - pad)}" width="${size}" height="${n(blockH + pad * 2)}" fill="${d.accentColor}"/>`);+ } else if (d.backdrop === 'box' || (d.backdrop === 'fade' && d.layout === 'center')) {+ const pad = fontSize * 0.4;+ parts.push(`<rect x="${n(left - pad)}" y="${n(top - pad)}" width="${n(widest + pad * 2)}" height="${n(blockH + pad * 2)}" fill="#000" fill-opacity="0.65"/>`);+ }+ if (d.rule) {+ const ry = atTop ? top + blockH + fontSize * 0.35 : top - fontSize * 0.35;+ parts.push(`<rect x="${n(left)}" y="${n(ry)}" width="${n(widest)}" height="${n(size * 0.004)}" fill="${d.accentColor}"/>`);+ }+ lines.forEach((line, i) => {+ parts.push(`<text x="${n(x)}" y="${n(top + fontSize * ASCENT + i * lineH)}" ${ink(fontSize)} font-size="${n(fontSize)}" text-anchor="${center ? 'middle' : 'start'}">${escapeXml(line)}</text>`);+ });+ return { parts, defs };+}++/** The artist tag, small, at the edge across from the title. */+const tagTextFor = (tag, d) => (d.tagStyle === 'none' ? '' : caseOf(String(tag || '').trim().slice(0, 24), d.letterCase));++function tagParts(tag, d, size, widthOf) {+ const text = tagTextFor(tag, d);+ if (!text) return [];+ const margin = size * MARGIN;+ const fs = size * 0.03;+ const w = (widthOf?.(text) ?? text.length * FACES[d.typeface].width * 1.08) * fs;+ const center = d.layout.endsWith('center') && d.layout !== 'center';+ const anchor = center ? 'middle' : 'end';+ const tx = center ? size / 2 : size - margin;+ const baseline = d.layout.startsWith('top') ? size - margin : margin + fs * ASCENT;+ const font = `${tagFont(d, fs)} font-size="${n(fs)}" text-anchor="${anchor}"`;+ if (d.tagStyle !== 'boxed') return [`<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="${d.accentColor}">${escapeXml(text)}</text>`];+ const pad = fs * 0.5;+ const bx = anchor === 'end' ? tx - w - pad : tx - w / 2 - pad;+ return [+ `<rect x="${n(bx)}" y="${n(baseline - fs * 1.05)}" width="${n(w + pad * 2)}" height="${n(fs * 1.45)}" fill="${d.accentColor}"/>`,+ `<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="#111">${escapeXml(text)}</text>`,+ ];+}++/** The overlay as SVG: the song's title and artist tag, laid out by its design. */+function coverOverlaySvg({ title, tag = '', design, size = COVER_ART_SIZE, widths = null }) {+ const d = normalizeCoverDesign(design);+ const { parts, defs } = titleParts(title, d, size, widths?.title);+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${[...parts, ...tagParts(tag, d, size, widths?.tag)].join('')}</svg>`;+}++const PROBE_PX = 100;++/** Each text's rendered width at a 1px font size, by drawing it at PROBE_PX and trimming the empty canvas around it. */+async function measureWidths(sharp, texts, font) {+ const out = new Map();+ for (const text of texts) {+ if (!text || out.has(text)) continue;+ const w = Math.ceil(text.length * PROBE_PX * 1.5) + 40;+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${PROBE_PX * 2}"><text x="20" y="${PROBE_PX * 1.3}" ${font} font-size="${PROBE_PX}" fill="#fff">${escapeXml(text)}</text></svg>`;+ const { info } = await sharp(Buffer.from(svg)).trim().toBuffer({ resolveWithObject: true }).catch(() => ({ info: null }));+ if (info?.width) out.set(text, info.width / PROBE_PX);}- return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${parts.join('')}</svg>`;+ return (text) => out.get(text);}/*** Write `out` (a JPEG): `source` cropped to its largest square at `focusX`- * (0 = left edge, 1 = right edge), scaled to `size`, with the overlay on top.+ * (0 = left edge, 1 = right edge), scaled to `size`, with the song's design on top.*/-export async function composeCoverArt({ source, out, title, tag = '', accent = COVER_ART_ACCENT, focusX = 0.5, size = COVER_ART_SIZE }, deps = {}) {+export async function composeCoverArt({ source, out, title, tag = '', design = null, focusX = 0.5, size = COVER_ART_SIZE }, deps = {}) {const sharp = deps.sharp || (await import('sharp')).default;// Apply the EXIF orientation first, so the crop is measured on the upright image.const { data, info } = await sharp(source).rotate().toBuffer({ resolveWithObject: true });@@ -81,7 +202,12 @@ export async function composeCoverArt({ source, out, title, tag = '', accent = Cconst fx = Math.min(1, Math.max(0, Number.isFinite(focusX) ? focusX : 0.5));const left = Math.round((info.width - side) * fx);const top = Math.round((info.height - side) / 2);- const overlay = Buffer.from(coverOverlaySvg({ title, tag, accent, size }));+ const d = normalizeCoverDesign(design);+ const widths = {+ title: await measureWidths(sharp, titleLinesFor(title, d, size), titleFont(d, PROBE_PX)),+ tag: await measureWidths(sharp, [tagTextFor(tag, d)], tagFont(d, PROBE_PX)),+ };+ const overlay = Buffer.from(coverOverlaySvg({ title, tag, design: d, size, widths }));await sharp(data).extract({ left, top, width: side, height: side }).resize(size, size, { kernel: 'lanczos3' })diff --git a/server/services/musicVideo/coverArtDesign.js b/server/services/musicVideo/coverArtDesign.jsnew file mode 100644index 0000000000..0b7ba2703f--- /dev/null+++ b/server/services/musicVideo/coverArtDesign.js@@ -0,0 +1,63 @@+/**+ * Music Video cover art — the design brief for one song's single artwork.+ *+ * Each song gets its own look, drafted from the song itself (title, lyrics,+ * the video's concept and visual direction) plus whatever the director typed+ * ("grainy black and white, tiny lowercase type", "make the title bigger").+ * The answer is a lettering design in coverArtCompose.js's vocabulary and a+ * prompt for the cover photo. Pure: project in, prompt out; text in, design out.+ */+import { extractJson } from '../../lib/jsonExtract.js';+import { fenceBlock } from '../../lib/promptFencing.js';+import { trimTo } from '../../lib/textUtils.js';+import { COVER_DESIGN_OPTIONS, normalizeCoverDesign } from './coverArtCompose.js';++const lyricsText = (project) => (project?.lyricCues || []).map((c) => (typeof c?.text === 'string' ? c.text.trim() : '')).filter(Boolean).join('\n');++/**+ * The drafting prompt. With a `previous` design the direction is an+ * adjustment to it; without one it is a fresh design (the direction, when+ * given, steering it).+ */+export function buildCoverDesignPrompt(project, { direction = '', previous = null } = {}) {+ const castDirection = project?.castAndSets?.direction || {};+ const p = castDirection.protagonist || {};+ const facts = [+ `Song title: ${project?.name || 'Untitled'}`,+ project?.concept?.style ? `The video's visual style: ${trimTo(project.concept.style, 800)}` : null,+ castDirection.look ? `The video's photographic look: ${trimTo(castDirection.look, 600)}` : null,+ [p.face, p.hair, p.signature].some(Boolean) ? `The singer: ${trimTo([p.face, p.hair, p.signature].filter(Boolean).join('; '), 600)}` : null,+ ].filter(Boolean).join('\n');+ const options = Object.entries(COVER_DESIGN_OPTIONS).map(([k, list]) => ` "${k}": one of ${list.map((v) => `"${v}"`).join(', ')}`).join(',\n');+ return [+ 'You are the art director for a single\'s cover artwork (the square image Spotify shows). Design a look that is this song\'s own: grow it from the song\'s words and its video\'s world, not from a genre template or another artist\'s cover.',+ 'The cover is one photograph with the song title and artist name set over it in type. You choose the photo and the type treatment.',+ facts,+ fenceBlock('Lyrics', lyricsText(project) || '(no lyrics)', 3000),+ previous ? fenceBlock('The current design (adjust it; keep what the direction does not change)', JSON.stringify(previous), 3000) : '',+ direction ? fenceBlock(previous ? "The artist's adjustment" : "The artist's direction", direction, 1500) : '',+ 'Return ONLY a JSON object:',+ `{+ "imagePrompt": "the cover photograph to generate, in one paragraph: subject, framing, light, palette, texture. Square. No text or lettering in the image. Leave calm space where the title goes.",+ "design": {+${options},+ "tracking": letter spacing in em from -0.05 to 0.3,+ "titleColor": "#rrggbb",+ "accentColor": "#rrggbb (artist name, rule, band)",+ "rule": true or false (a thin accent line by the title)+ },+ "rationale": "one sentence on why this look fits this song"+}`,+ ].filter(Boolean).join('\n\n');+}++/** The model's answer as `{ design, imagePrompt, rationale }`, or null when it has no usable design. */+export function parseCoverDesign(text) {+ const { value } = extractJson(text, { blockType: 'object' });+ if (!value || typeof value !== 'object' || !value.design || typeof value.design !== 'object') return null;+ return {+ design: normalizeCoverDesign(value.design),+ imagePrompt: trimTo(typeof value.imagePrompt === 'string' ? value.imagePrompt : '', 1500),+ rationale: trimTo(typeof value.rationale === 'string' ? value.rationale : '', 300),+ };+}