Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add release cover art to the music video publishing kit
Claudead6210b0c643
diff --git a/client/src/components/musicVideo/CoverArtPanel.jsx b/client/src/components/musicVideo/CoverArtPanel.jsxnew file mode 100644index 0000000000..3173e13c2b--- /dev/null+++ b/client/src/components/musicVideo/CoverArtPanel.jsx@@ -0,0 +1,130 @@+import { useState } from 'react';+import { Download, Image as ImageIcon, Sparkles } from 'lucide-react';++const MAX_SOURCES = 24;++/** Images the cover can be made from: cover images made for it, Cast & Sets renders, look references, scene frames, then kit thumbnails. */+export function coverArtSources(project) {+ const kit = project?.publishKit || {};+ const seen = new Set();+ const out = [];+ const add = (kind, filename, label) => {+ if (!filename || seen.has(`${kind}:${filename}`)) return;+ seen.add(`${kind}:${filename}`);+ out.push({ kind, filename, label, src: kind === 'thumbnail' ? `/data/video-thumbnails/${encodeURIComponent(filename)}` : `/data/images/${encodeURIComponent(filename)}` });+ };+ for (const f of kit.coverArt?.generated || []) add('image', f, 'Cover image');+ for (const [key, img] of Object.entries(project?.castAndSets?.images || {})) add('image', img?.imageId, `Cast & Sets: ${key}`);+ for (const ref of project?.visualSpec?.references || []) add('image', ref?.imageId, ref?.label || 'Look reference');+ (project?.scenes || []).forEach((scene, i) => add('image', scene?.referenceImageId, `Shot ${i + 1}${scene?.sectionLabel ? ` (${scene.sectionLabel})` : ''}`));+ (kit.thumbnails || []).forEach((f, i) => add('thumbnail', f, `Video frame ${i + 1}`));+ return out.slice(0, MAX_SOURCES);+}++/**+ * 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.+ */+export default function CoverArtPanel({ project, publishKit }) {+ const art = project?.publishKit?.coverArt || {};+ const sources = coverArtSources(project);+ const idFor = (s) => `mv-cover-${project?.id}-${s}`;+ const [title, setTitle] = useState(art.title ?? project?.name ?? '');+ // null = untouched, so the server keeps the last tag (or the DistroKid artist).+ 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 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 } } : {}),+ });++ return (+ <section aria-label="Cover art" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">+ <h3 className="text-sm font-medium flex items-center gap-1.5"><ImageIcon size={14} /> Cover art</h3>+ <p className="text-port-text-muted">The square cover Spotify (via DistroKid) and Suno show. Pick an image, and the title and artist are set on it.</p>+ <div className="flex flex-col sm:flex-row gap-3">+ <div className="w-full sm:w-48 shrink-0 space-y-1">+ {art.filename ? (+ <>+ <img src={`/data/video-thumbnails/${encodeURIComponent(art.filename)}`} alt={`Cover art for ${project?.name || 'the song'}`} className="w-full aspect-square object-cover rounded border border-port-border" />+ <a href={`/data/video-thumbnails/${encodeURIComponent(art.filename)}`} download className="text-port-accent flex items-center gap-1 min-h-[44px] sm:min-h-0"><Download size={12} /> Download</a>+ </>+ ) : (+ <div className="w-full aspect-square rounded border border-dashed border-port-border flex items-center justify-center text-port-text-muted p-2 text-center">No cover yet</div>+ )}+ </div>+ <div className="flex-1 space-y-2 min-w-0">+ <div className="grid grid-cols-2 gap-2">+ <div>+ <label htmlFor={idFor('title')} className="block text-[11px] text-port-text-muted">Title on the cover</label>+ <input id={idFor('title')} value={title} maxLength={60} onChange={(e) => setTitle(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />+ </div>+ <div>+ <label htmlFor={idFor('tag')} className="block text-[11px] text-port-text-muted">Artist tag</label>+ <input id={idFor('tag')} value={tag ?? art.tag ?? ''} maxLength={24} placeholder="Artist name" onChange={(e) => setTag(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />+ </div>+ </div>+ <div>+ <label htmlFor={idFor('focus')} className="block text-[11px] text-port-text-muted">Crop position (left to right)</label>+ <input id={idFor('focus')} type="range" min={0} max={1} step={0.05} value={focusX} onChange={(e) => setFocusX(Number(e.target.value))}+ className="w-full min-h-[44px] sm:min-h-0" />+ </div>+ <button type="button" onClick={() => compose(null)} disabled={busy || !art.source || !title.trim()}+ 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">+ {busy ? 'Setting the cover…' : 'Apply to the cover'}+ </button>+ </div>+ </div>++ {art.pending && <p role="status" className="text-port-text-muted">Making a cover image on {art.pending.mode || 'the image backend'}. The cover updates when it lands.</p>}+ {art.lastError && !art.pending && <p role="alert" className="text-port-warning">{art.lastError}</p>}++ <div className="space-y-1">+ <span className="text-port-text-muted">Cover image: pick one</span>+ {sources.length ? (+ <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">+ {sources.map((s) => (+ <button key={`${s.kind}:${s.filename}`} type="button" onClick={() => compose(s)} disabled={busy || !title.trim()}+ aria-pressed={chosen === `${s.kind}:${s.filename}`} aria-label={`Make the cover from ${s.label}`} title={s.label}+ className={`rounded overflow-hidden border-2 disabled:opacity-60 ${chosen === `${s.kind}:${s.filename}` ? 'border-port-accent' : 'border-transparent'}`}>+ <img src={s.src} alt="" loading="lazy" className="w-full aspect-square object-cover" />+ </button>+ ))}+ </div>+ ) : (+ <p className="text-port-text-muted">No images yet. Build the publishing kit for video frames, or make one below.</p>+ )}+ </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>+ <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"+ 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>+ )}+ <button type="button" onClick={generate} disabled={!!art.pending}+ 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} /> {art.pending ? 'Making…' : 'Make with Codex'}+ </button>+ </div>+ </div>+ </section>+ );+}diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsxindex b7884954dc..c6a44cc683 100644--- a/client/src/components/musicVideo/PublishKitPanel.jsx+++ b/client/src/components/musicVideo/PublishKitPanel.jsx@@ -3,6 +3,7 @@ import { Package, Download, Copy, Sparkles, Image as ImageIcon, Captions, ListOrimport useProviderModels from '../../hooks/useProviderModels.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';import { copyToClipboard } from '../../lib/clipboard.js';+import CoverArtPanel from './CoverArtPanel.jsx';const fmtTime = (sec) => {const s = Math.max(0, Math.floor(sec));@@ -161,6 +162,8 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets }))}</section>+ <CoverArtPanel key={project?.id} project={project} publishKit={publishKit} />+<section aria-label="Release copy" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs"><h3 className="text-sm font-medium flex items-center gap-1.5"><Sparkles size={14} /> Release copy</h3><p className="text-port-text-muted">The draft only states what you give it here, plus the song, its lyrics and its generation spend. Nothing runs until you press Draft.</p>diff --git a/client/src/components/musicVideo/PublishKitPanel.test.jsx b/client/src/components/musicVideo/PublishKitPanel.test.jsxindex 7bd3bb69ec..dbc96f09e9 100644--- a/client/src/components/musicVideo/PublishKitPanel.test.jsx+++ b/client/src/components/musicVideo/PublishKitPanel.test.jsx@@ -15,7 +15,8 @@ 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), ...over,+ 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,});const built = {builtAt: '2026-01-01T00:00:00.000Z', master: { filename: 'master.mp4' },@@ -57,4 +58,26 @@ describe('PublishKitPanel (#9281)', () => {fireEvent.click(screen.getByRole('button', { name: 'Use thumbnail t2.jpg' }));expect(k.selectThumbnail).toHaveBeenCalledWith('t2.jpg');});++ it('makes the cover art from a project image with the title, and asks Codex for a new one', () => {+ const k = hook();+ const project = { id: 'mv-1', name: 'Example Song', publishKit: built, castAndSets: { images: { character: { imageId: 'sheet.png' } } } };+ const { rerender } = render(<PublishKitPanel project={project} publishKit={k} />);+ expect(screen.getByText('No cover yet')).toBeTruthy();+ fireEvent.change(screen.getByLabelText('Title on the cover'), { target: { value: 'Example Retitle' } });+ fireEvent.click(screen.getByRole('button', { name: 'Make the cover from Cast & Sets: character' }));+ expect(k.composeCover).toHaveBeenCalledWith({ source: { kind: 'image', filename: 'sheet.png' }, title: 'Example Retitle', focusX: 0.5 });+ 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' });++ const art = { filename: 'cover-1.jpg', title: 'Example Song', tag: 'Example Artist', source: { kind: 'image', filename: 'sheet.png' }, pending: { mode: 'codex' } };+ 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.getByRole('button', { name: /Making/ })).toBeDisabled();+ });});diff --git a/client/src/hooks/useMusicVideoPublishKit.js b/client/src/hooks/useMusicVideoPublishKit.jsindex bbf3ae9e1e..4ba928a89d 100644--- a/client/src/hooks/useMusicVideoPublishKit.js+++ b/client/src/hooks/useMusicVideoPublishKit.js@@ -1,5 +1,6 @@import { useEffect, useRef, useState } from 'react';import toast from '../components/ui/Toast';+import socket from '../services/socket';import {getMusicVideoProject,buildMusicVideoPublishKit,@@ -8,6 +9,8 @@ import {draftMusicVideoPublishCopy,updateMusicVideoPublishCopy,selectMusicVideoPublishThumbnail,+ composeMusicVideoCoverArt,+ generateMusicVideoCoverArt,} from '../services/apiMusicVideo.js';import useSseJobSlot from './useSseJobSlot.js';@@ -16,13 +19,15 @@ const readPercent = (frame) => (Number.isFinite(frame.progress) ? frame.progress/*** Music Video publishing kit (#9281): the build is a `useSseJobSlot` job whose* terminal frame reloads the project it was started for (the kit lives on the- * server record); the copy draft, copy edits and thumbnail choice each return- * the whole project and apply it with `replaceProject`.+ * server record); the copy draft, copy edits, thumbnail choice and cover art+ * each return the whole project and apply it with `replaceProject`. A cover+ * image made by a backend lands later, over `music-video:cover-art`.*/export default function useMusicVideoPublishKit({ project, replaceProject } = {}) {const projectId = project?.id || null;const [drafting, setDrafting] = useState(false);const [saving, setSaving] = useState(false);+ const [composing, setComposing] = useState(false);const reload = (id) => {if (!id) return;@@ -61,6 +66,14 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}if (job.attach(runningJobId, projectId)) attachedJobs.current.add(runningJobId);}, [runningJobId, projectId]);+ useEffect(() => {+ if (!projectId) return undefined;+ const onCover = (e) => { if (e?.projectId === projectId && e.project) replaceProject(e.project); };+ socket.on('music-video:cover-art', onCover);+ return () => { socket.off('music-video:cover-art', onCover); };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [projectId]);+const apply = (res) => { if (res?.project) replaceProject(res.project); return res?.project || null; };const draftCopy = (body) => {@@ -78,6 +91,14 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}.finally(() => setSaving(false));};const selectThumbnail = (filename) => selectMusicVideoPublishThumbnail(projectId, filename).then(apply).catch(() => null);+ const composeCover = (body) => {+ setComposing(true);+ return composeMusicVideoCoverArt(projectId, body)+ .then(apply)+ .catch(() => null)+ .finally(() => setComposing(false));+ };+ const generateCover = (body) => generateMusicVideoCoverArt(projectId, body).then(apply).catch(() => null);return {building: job.active,@@ -89,5 +110,8 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}draftCopy,saveCopy,selectThumbnail,+ composing,+ composeCover,+ generateCover,};}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex a67e6d45b3..48edce0964 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -244,6 +244,12 @@ export const updateMusicVideoPublishCopy = (id, patch, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'PATCH', body: JSON.stringify(patch || {}), ...options });export const selectMusicVideoPublishThumbnail = (id, filename, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/thumbnail`, { method: 'PUT', body: JSON.stringify({ filename }), ...options });+// Release cover art: compose from a source image, or queue a fresh source+// (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 generateMusicVideoCoverArt = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/generate`, { method: 'POST', body: JSON.stringify(body || {}), ...options });// ---- Posting (#9282) ----// Prepare fills the platform's post in the PortOS Browser → { draftId, target,// summary, screenshot }. Manual posting is handled outside this wrapper.diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 1924b72274..61efce2b65 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -120,7 +120,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([modules: ['services/musicVideo/render.js', 'services/musicVideo/excerptRender.js','services/musicVideo/publishKit.js', 'services/musicVideo/compositionDocument.js',- 'services/musicVideo/sharingCopy.js',+ 'services/musicVideo/sharingCopy.js', 'services/musicVideo/coverArt.js',],},{diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex bbeee290a2..cb8c6d83bf 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -686,6 +686,20 @@ export const musicVideoPublishCopyDraftSchema = z.object({}).strict();export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().min(1).max(300) }).strict();+// Release cover art: a source (a kit thumbnail or a gallery image) composed+// with the title and artist tag, or a fresh source image from a backend.+const coverArtSourceSchema = z.object({ kind: z.enum(['thumbnail', 'image']), filename: z.string().min(1).max(300) }).strict();+export const musicVideoCoverArtComposeSchema = z.object({+ source: coverArtSourceSchema.optional(),+ title: z.string().max(60).optional(),+ tag: z.string().max(24).optional(),+ focusX: z.number().min(0).max(1).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(),+}).strict();+// #9282: posting to a platform through the PortOS Browser. One strict options// object covers every target; each target's payload builder reads only its own.export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'reddit', 'stackerNews', 'suno', 'distrokid']);diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 8d8ab373b1..36922c2188 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -45,6 +45,8 @@ import {musicVideoPublishCopyPatchSchema,musicVideoPublishCopyDraftSchema,musicVideoPublishThumbnailSchema,+ musicVideoCoverArtComposeSchema,+ musicVideoCoverArtGenerateSchema,musicVideoPublishTargetSchema,musicVideoPublishPrepareSchema,musicVideoPublishPlatformsPatchSchema,@@ -912,6 +914,22 @@ 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.+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');+ const { project } = await composeProjectCoverArt(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');+ const { project } = await generateCoverArtSource(req.params.id, input);+ res.json({ project });+}));+// --- Posting (#9282) ---// Fill a platform's post in the PortOS Browser and return a screenshot; post// only on a second, explicit request naming that live draft.diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex c18bdba38a..8470606889 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -152,6 +152,7 @@ import { initFableLoomSceneVideoHook } from './fableLoomSceneVideoHook.js';import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';import { initMusicVideoCastSetsImageHook } from './musicVideoCastSetsImageHook.js';+import { initMusicVideoCoverArtImageHook } from './musicVideoCoverArtImageHook.js';import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';import { initMusicStudioHook } from './musicStudioHook.js';import { initImageGenQuotaHook } from './imageGenQuota.js';@@ -690,6 +691,9 @@ const initMediaJobDependentHooks = () => {// (character sheet, looks, set plates, in-set tests) onto its stage key.// It only listens: nothing is generated at boot.initMusicVideoCastSetsImageHook();+ // Music Video cover art hook — composes the release cover from a cover+ // source image the director asked for. It only listens.+ initMusicVideoCoverArtImageHook();// Creative Director music-bed hook — durably files a queued first-pass// audio render onto its project's `musicBed` field on completion, even if// the requesting client unmounted mid-render (#1928).diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex e1d9ab2697..3928830149 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -1635,7 +1635,9 @@ export function assertMediaQueueRoom(count = 1) {// entry, no SSE entry, no snapshot write. The check and the push below run in// one synchronous stretch, so concurrent submissions cannot overshoot it.async function assertMusicVideoJobPolicy(kind, params) {- if (params?.musicVideo?.projectId && ['image', 'video'].includes(kind)) {+ // Release cover art is not footage in the video, so the media mode (what the+ // video itself may contain) does not govern it.+ if (params?.musicVideo?.projectId && !params.musicVideo.coverArt && ['image', 'video'].includes(kind)) {const { getProject } = await import('../musicVideo/projects.js');const { assertMusicVideoMedia } = await import('../../lib/musicVideoMediaPolicy.js');const project = await getProject(params.musicVideo.projectId);diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 3346d0aea2..33f5e7dee4 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -278,6 +278,14 @@ describe('mediaJobQueue', () => {expect(stubs.generateImage).not.toHaveBeenCalled();});+ it('admits release cover art for a code-only video: the cover is not footage in it', async () => {+ const { getProject } = await import('../musicVideo/projects.js');+ getProject.mockClear();+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'Synthetic cover', musicVideo: { projectId: 'mv-example', coverArt: { requestId: 'req-example' } } } });+ expect(mediaJobQueue.getJob(jobId)).toBeTruthy();+ expect(getProject).not.toHaveBeenCalled();+ });+it('rejects an unreviewed music-video scene before queue admission and rechecks delayed dispatch', async () => {const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');const request = { kind: 'video', params: { prompt: 'Synthetic scene', musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' } } };diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex f43d257335..401f50b79b 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.*/-async function chooseCastAndSetsRoute(project, { preferred = null, settings } = {}) {+export 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, its@@ -259,7 +259,7 @@ function referencePaths(stage, item) {}/** Job params for one image on the stage's route (cloud provider bag or the local model). */-async function imageJobParams(settings, route, common) {+export async function imageJobParams(settings, route, common) {const [{ resolveRenderTargetConfig }, { resolveImageCleaners }, { resolveLocalImageModel }] = await Promise.all([import('../imageGen/cloudProviderConfig.js'),import('../imageGen/index.js'),diff --git a/server/services/musicVideo/coverArt.js b/server/services/musicVideo/coverArt.jsnew file mode 100644index 0000000000..2df8e3db83--- /dev/null+++ b/server/services/musicVideo/coverArt.js@@ -0,0 +1,201 @@+/**+ * Music Video — cover art for the song's release (Spotify via DistroKid, Suno).+ *+ * `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).+ *+ * coverArt: { filename, source: { kind, filename }, title, tag, focusX,+ * composedAt, generated: [galleryFilename…],+ * pending: { requestId, jobId, mode, requestedAt } | null,+ * lastError: string | null }+ */+import { randomUUID } from 'crypto';+import { basename } from 'path';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { ServerError } from '../../lib/errorHandler.js';+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 { musicVideoEvents } from './events.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { projectPublishKit, releaseKitFiles } from './publishKit.js';++const MAX_GENERATED = 12;+// Codex renders square at 1024; the compose scales it to the store size.+const SOURCE_PX = 1024;++const defaults = {+ compose: composeCoverArt,+ 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),+ imageParams: async (settings, route, common) => (await import('./castAndSetsService.js')).imageJobParams(settings, route, common),+ withStyle: async (...args) => (await import('./styleReferences.js')).withMusicVideoStyle(...args),+};+let deps = { ...defaults };+export function __setCoverArtDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }++const coverError = (status, code, message) => new ServerError(message, { status, code });+export const projectCoverArt = (project) => {+ const art = projectPublishKit(project).coverArt;+ return art && typeof art === 'object' ? art : {};+};++async function requireProject(projectId) {+ const project = await getProject(projectId);+ if (!project) throw coverError(404, 'NOT_FOUND', 'Project not found');+ return project;+}++function publish(projectId, project) {+ musicVideoEvents.emit('cover-art', { projectId, project });+}++const writeCoverArt = (projectId, update) => mutateProjectRecord(projectId, (current) => {+ const kit = projectPublishKit(current);+ const art = projectCoverArt(current);+ return { project: { ...current, publishKit: { ...kit, coverArt: { ...art, ...update(art) } } } };+});++/** A source's file on disk: a thumbnail this kit cut, or a gallery image. */+function sourcePath(project, source) {+ const name = basename(String(source?.filename || ''));+ if (source?.kind === 'thumbnail') {+ if (!(projectPublishKit(project).thumbnails || []).includes(name)) throw coverError(422, 'VALIDATION_ERROR', 'That thumbnail is not one this kit built');+ const path = safeUnder(PATHS.videoThumbnails, name);+ if (path) return path;+ } else if (source?.kind === 'image') {+ const path = resolveGalleryImage(name);+ if (path) return path;+ }+ throw coverError(422, 'PUBLISH_ASSET_MISSING', `The cover source image is missing (${name || 'none'})`);+}++/** The artist tag: what the director set, else the DistroKid account under Where you post. */+async function defaultTag() {+ const platforms = await deps.getPlatforms().catch(() => null);+ return trimTo(platforms?.distrokid?.account, 24) || '';+}++/**+ * Compose the cover from `source` with the title and tag, and make it the+ * release's cover. Unset fields keep the last cover's (title defaults to the+ * project name, tag to the DistroKid artist).+ */+export async function composeProjectCoverArt(projectId, { source = null, title, tag, focusX } = {}) {+ const project = await requireProject(projectId);+ const art = projectCoverArt(project);+ const from = source || art.source;+ if (!from) throw coverError(422, 'VALIDATION_ERROR', 'Pick an image for the cover first');+ const path = sourcePath(project, from);+ const next = {+ source: { kind: from.kind, filename: basename(from.filename) },+ title: typeof title === 'string' ? title.trim() : (art.title ?? project.name ?? ''),+ tag: typeof tag === 'string' ? tag.trim() : (art.tag ?? await defaultTag()),+ focusX: Number.isFinite(focusX) ? focusX : (Number.isFinite(art.focusX) ? art.focusX : 0.5),+ };+ 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) });+ // 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,+ })));+ if (art.filename && art.filename !== filename) await releaseKitFiles([art.filename], [filename]);+ console.log(`🖼️ Music Video cover art ${String(projectId).slice(3, 11)} ← ${next.source.filename}`);+ publish(projectId, out.project);+ 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 = '' } = {}) {+ 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);+ 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.',+ 'No text, letters, logos, or watermark anywhere in the image.',+ ].filter(Boolean).join(' ');+}++/**+ * Ask an image backend (Codex when enabled) 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.+ */+export async function generateCoverArtSource(projectId, { notes = '', reference = null } = {}) {+ const project = await requireProject(projectId);+ if (projectCoverArt(project).pending) throw coverError(409, 'COVER_ART_IN_PROGRESS', 'A cover image is already being made');+ 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 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)})`);+ const requestId = randomUUID();+ const common = {+ prompt: buildCoverArtPrompt(project, { notes }),+ width: SOURCE_PX,+ height: SOURCE_PX,+ ...(refPath ? { referenceImagePaths: [refPath], referenceImageStrengths: [1] } : {}),+ // The completion hook files the result by this tag. No `sceneId` or+ // `castAndSets`, so the scene and Cast & Sets hooks ignore the job.+ musicVideo: { projectId: project.id, coverArt: { requestId } },+ };+ const params = await deps.withStyle(project, await deps.imageParams(settings, route, common), route.mode, route.model, settings);+ const sent = await deps.enqueue({ kind: 'image', params, owner: `music-video-cover-art:${project.id}` });+ const out = await writeCoverArt(projectId, () => ({+ pending: { requestId, jobId: typeof sent?.jobId === 'string' ? sent.jobId : null, mode: route.mode, requestedAt: new Date().toISOString() },+ lastError: null,+ }));+ console.log(`🖼️ Music Video cover art ${String(projectId).slice(3, 11)}: source image queued on ${route.mode}`);+ publish(projectId, out.project);+ return { project: out.project };+}++/**+ * The completion hook's entry: file a finished source image and compose the+ * cover from it, or record why it failed. A stale request (the director asked+ * again) still keeps its image as a pickable source but changes nothing else.+ * Returns true when the record changed.+ */+export async function onCoverArtImageSettled({ projectId, requestId, filename = null, status = null, error = null }) {+ const project = await getProject(projectId);+ if (!project) return false;+ const current = projectCoverArt(project).pending?.requestId === requestId;+ if (!filename) {+ if (!current) return false;+ const out = await writeCoverArt(projectId, () => ({ pending: null, lastError: trimTo(error || `The cover image render was ${status || 'not finished'}`, 300) }));+ console.warn(`⚠️ Music Video cover art ${String(projectId).slice(3, 11)}: source image ${status || 'failed'}`);+ publish(projectId, out.project);+ return true;+ }+ const out = await writeCoverArt(projectId, (art) => ({+ generated: [filename, ...(art.generated || []).filter((f) => f !== filename)].slice(0, MAX_GENERATED),+ ...(current ? { pending: null } : {}),+ }));+ if (!current) { publish(projectId, out.project); return true; }+ await composeProjectCoverArt(projectId, { source: { kind: 'image', filename } }).catch(async (err) => {+ console.error(`❌ Music Video cover art ${String(projectId).slice(3, 11)} compose failed: ${err.message}`);+ const failed = await writeCoverArt(projectId, () => ({ lastError: trimTo(`The cover could not be composed: ${err.message}`, 300) }));+ publish(projectId, failed.project);+ });+ return true;+}diff --git a/server/services/musicVideo/coverArt.test.js b/server/services/musicVideo/coverArt.test.jsnew file mode 100644index 0000000000..1459d355f5--- /dev/null+++ b/server/services/musicVideo/coverArt.test.js@@ -0,0 +1,136 @@+/**+ * Release cover art, through the real project store: composing writes one+ * square cover onto the kit (title from the project, tag from the DistroKid+ * artist) and frees the previous one; "make a cover image" queues one tagged+ * image job, and its completion composes the cover from the result, or+ * records why it failed. The lettering itself renders through real sharp once.+ */+import { describe, expect, it, vi, afterAll, beforeEach } from 'vitest';+import { existsSync } from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-cover-art-'),+}));++const { PATHS } = await import('../../lib/paths.js');+const projects = await import('./projects.js');+const { musicVideoEvents } = await import('./events.js');+const cover = await import('./coverArt.js');+const { composeCoverArt } = await import('./coverArtCompose.js');++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 chooseRoute = vi.fn(async (_project, { preferred } = {}) => (preferred?.mode === 'codex' ? { mode: 'codex', model: null } : null));++beforeEach(() => {+ compose.mockClear(); enqueue.mockClear(); chooseRoute.mockClear();+ cover.__setCoverArtDepsForTests({+ compose, enqueue, chooseRoute,+ getSettings: async () => ({}),+ getPlatforms: async () => ({ distrokid: { enabled: true, account: 'Example Artist' } }),+ imageParams: async (_settings, route, common) => ({ ...common, provider: route.mode }),+ withStyle: async (_project, params) => params,+ });+});++async function projectWithThumbnail(name = 'Example Song') {+ const { id } = await projects.createProject({ name });+ await mkdir(PATHS.videoThumbnails, { recursive: true });+ const thumb = `thumb-${id.slice(3, 11)}.jpg`;+ await writeFile(join(PATHS.videoThumbnails, thumb), 'jpeg');+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { thumbnails: [thumb], thumbnail: thumb } } }));+ return { id, thumb };+}++describe('release cover art', () => {+ it('composes a cover from a kit thumbnail with the project title and the DistroKid artist, and frees the one it replaces', async () => {+ const { id, thumb } = await projectWithThumbnail();+ const events = [];+ const onCover = (e) => events.push(e);+ musicVideoEvents.on('cover-art', onCover);+ try {+ const { project } = await cover.composeProjectCoverArt(id, { source: { kind: 'thumbnail', filename: thumb } });+ const art = project.publishKit.coverArt;+ expect(art).toMatchObject({ title: 'Example Song', tag: 'Example Artist', focusX: 0.5, source: { kind: 'thumbnail', filename: thumb } });+ expect(compose).toHaveBeenCalledWith(expect.objectContaining({ source: join(PATHS.videoThumbnails, thumb), title: 'Example Song', tag: 'Example Artist' }));+ expect(existsSync(join(PATHS.videoThumbnails, art.filename))).toBe(true);+ // The thumbnail stays the YouTube thumbnail; the cover is its own file.+ expect(project.publishKit.thumbnail).toBe(thumb);++ // A re-compose keeps the source and edits only what it names.+ const again = (await cover.composeProjectCoverArt(id, { title: 'Example Retitle', focusX: 0.2 })).project.publishKit.coverArt;+ expect(again).toMatchObject({ title: 'Example Retitle', tag: 'Example Artist', focusX: 0.2, source: { kind: 'thumbnail', filename: thumb } });+ expect(existsSync(join(PATHS.videoThumbnails, art.filename))).toBe(false);+ expect(events.map((e) => e.projectId)).toEqual([id, id]);+ } finally {+ musicVideoEvents.off('cover-art', onCover);+ }+ });++ it('refuses a thumbnail the kit did not cut and a gallery image that is not there', async () => {+ const { id } = await projectWithThumbnail();+ await expect(cover.composeProjectCoverArt(id, { source: { kind: 'thumbnail', filename: 'other.jpg' } })).rejects.toMatchObject({ status: 422 });+ await expect(cover.composeProjectCoverArt(id, { source: { kind: 'image', filename: 'missing-example.png' } })).rejects.toMatchObject({ status: 422, code: 'PUBLISH_ASSET_MISSING' });+ await expect(cover.composeProjectCoverArt(id, {})).rejects.toMatchObject({ status: 422 });+ expect(compose).not.toHaveBeenCalled();+ });++ it('queues one tagged cover image on Codex, 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' });+ 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.params.prompt).toContain('No text');+ await expect(cover.generateCoverArtSource(id)).rejects.toMatchObject({ status: 409, code: 'COVER_ART_IN_PROGRESS' });++ await mkdir(PATHS.images, { recursive: true });+ await writeFile(join(PATHS.images, 'job-example.png'), 'png');+ expect(await cover.onCoverArtImageSettled({ projectId: id, requestId, filename: 'job-example.png' })).toBe(true);+ const art = (await projects.getProject(id)).publishKit.coverArt;+ expect(art).toMatchObject({ pending: null, generated: ['job-example.png'], source: { kind: 'image', filename: 'job-example.png' } });+ expect(art.filename).toMatch(/^cover-.+\.jpg$/);+ });++ it('records a failed cover image, and a stale one only joins the pickable sources', async () => {+ const { id } = await projectWithThumbnail();+ const { requestId } = (await cover.generateCoverArtSource(id)).project.publishKit.coverArt.pending;+ expect(await cover.onCoverArtImageSettled({ projectId: id, requestId: 'req-stale', filename: 'stale-example.png' })).toBe(true);+ let art = (await projects.getProject(id)).publishKit.coverArt;+ expect(art.generated).toEqual(['stale-example.png']);+ expect(art.pending.requestId).toBe(requestId);+ expect(compose).not.toHaveBeenCalled();++ await cover.onCoverArtImageSettled({ projectId: id, requestId, status: 'failed', error: 'Codex refused the prompt' });+ art = (await projects.getProject(id)).publishKit.coverArt;+ expect(art).toMatchObject({ pending: null, lastError: 'Codex refused the prompt' });+ });++ it('says so when no image backend is enabled', async () => {+ const { id } = await projectWithThumbnail();+ chooseRoute.mockResolvedValue(null);+ await expect(cover.generateCoverArtSource(id)).rejects.toMatchObject({ status: 409, code: 'COVER_ART_ROUTE_UNAVAILABLE' });+ expect(enqueue).not.toHaveBeenCalled();+ });+});++describe('cover lettering', () => {+ it('renders a store-size square JPEG from a wide still', async () => {+ const sharp = (await import('sharp')).default;+ const dir = join(PATHS.videoThumbnails, 'lettering');+ await mkdir(dir, { recursive: true });+ const source = join(dir, 'wide.png');+ await sharp({ create: { width: 640, height: 360, channels: 3, background: '#335577' } }).png().toFile(source);+ const out = join(dir, 'cover.jpg');+ 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 });+ });+});diff --git a/server/services/musicVideo/coverArtCompose.js b/server/services/musicVideo/coverArtCompose.jsnew file mode 100644index 0000000000..f321063db8--- /dev/null+++ b/server/services/musicVideo/coverArtCompose.js@@ -0,0 +1,92 @@+/**+ * 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.+ *+ * 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;++const escapeXml = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c]);++/** 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);+ 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));+ }+ return lines.slice(0, 3);+}++/** 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 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;+ }+ y += tileH + lineGap;+ }+ 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>`);+ }+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${parts.join('')}</svg>`;+}++/**+ * 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.+ */+export async function composeCoverArt({ source, out, title, tag = '', accent = COVER_ART_ACCENT, focusX = 0.5, size = COVER_ART_SIZE }, deps = {}) {+ const sharp = deps.sharp || (await import('sharp')).default;+ const meta = await sharp(source).metadata();+ const side = Math.min(meta.width, meta.height);+ const fx = Math.min(1, Math.max(0, Number.isFinite(focusX) ? focusX : 0.5));+ const left = Math.round((meta.width - side) * fx);+ const top = Math.round((meta.height - side) / 2);+ const overlay = Buffer.from(coverOverlaySvg({ title, tag, accent, size }));+ await sharp(source)+ .rotate()+ .extract({ left, top, width: side, height: side })+ .resize(size, size, { kernel: 'lanczos3' })+ .composite([{ input: overlay, top: 0, left: 0 }])+ .jpeg({ quality: 92, chromaSubsampling: '4:4:4' })+ .toFile(out);+ return { width: size, height: size };+}diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 2b712a5540..7e9c0807a8 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -61,4 +61,7 @@ import { EventEmitter } from 'events';// 'publish-draft' → { projectId, draftId, target, state } — a publish draft's// tab was filled ('open'), closed by hand ('closed') or discarded; bridged// to `music-video:publish-draft`.+// 'cover-art' → { projectId, project } — the release cover art was+// composed, or a cover source image was queued, landed or failed; bridged+// to `music-video:cover-art`.export const musicVideoEvents = new EventEmitter();diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex d2ec000ffe..b9a1e88f09 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -105,6 +105,8 @@ async function withCovers(target, payload, deps) {if (target !== 'tiktok' && !SQUARE_COVER_PX[target]) return payload;const source = target === 'tiktok' ? payload.video?.path : payload.cover?.path;if (!source) return payload;+ // Composed cover art is already a store-size square.+ if (target === 'distrokid' && payload.cover?.square) return payload;const { findFfmpeg, runFfmpegProcess } = await import('../../../lib/ffmpeg.js');// A store rejects a non-square cover, so DistroKid gets no draft rather than the 16:9 frame.const uncut = () => {diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.jsindex 9db1fee83e..4d67d35bed 100644--- a/server/services/musicVideo/publish/index.test.js+++ b/server/services/musicVideo/publish/index.test.js@@ -210,6 +210,14 @@ describe('publish drafts (#9282)', () => {expect(payload.cover.name).toMatch(/^publish-cover-distrokid-/);expect(runFfmpegProcess.mock.calls[0][0].args.join(' ')).toContain('scale=3000:3000');expect(resolveAudio.mock.calls[0][0]).toMatchObject({ id, uploadedAudioFilename: 'song.wav' });++ // Composed cover art is already store size: it goes up as is, with no ffmpeg cut.+ await writeFile(join(PATHS.videoThumbnails, 'cover-example.jpg'), 'x');+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { ...current.publishKit, coverArt: { filename: 'cover-example.jpg' } } } }));+ runFfmpegProcess.mockClear();+ await preparePublishDraft(id, 'distrokid', options, { connect, adapters, platforms: dk, resolveAudio, findFfmpeg: async () => null, runFfmpegProcess });+ expect(adapters.distrokid.prepare.mock.calls.at(-1)[1].cover).toMatchObject({ name: 'cover-example.jpg', path: join(PATHS.videoThumbnails, 'cover-example.jpg') });+ expect(runFfmpegProcess).not.toHaveBeenCalled();});it('refuses a DistroKid draft whose song is unset or gone, in publishing terms, before opening a tab', async () => {diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.jsindex 4d14681126..0cb7468512 100644--- a/server/services/musicVideo/publish/payloads.js+++ b/server/services/musicVideo/publish/payloads.js@@ -77,6 +77,13 @@ function youtubeDescription(kit) {// A typed "@" on Instagram opens the mention picker, which swallows the next word.const instagramSafe = (caption) => caption.replace(/@(\w)/g, '$1');+// The release cover: the composed cover art when there is one (already square,+// with the title set), else the kit's thumbnail (cut square at post time).+const releaseCover = (kit) => {+ if (kit.coverArt?.filename) return { dir: 'videoThumbnails', name: kit.coverArt.filename, square: true };+ return kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null;+};+const BUILDERS = {youtube: (project, kit) => {if (!kit.master?.filename) throw missing('Build the publishing kit first — it names the final render to upload');@@ -162,10 +169,10 @@ const BUILDERS = {const video = fullVideoUrl(kit);const lead = text(kit.copy?.youtube?.description).split(/\n\s*\n/)[0] || '';const caption = [lead, video ? `Music video: ${video}` : ''].filter(Boolean).join(' ').slice(0, 500);- return { songUrl: song, caption, cover: kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null, pin: options.pin !== false };+ return { songUrl: song, caption, cover: releaseCover(kit), pin: options.pin !== false };},// The song as a single for Spotify and the other stores. The service adds the- // project's source audio; the cover is cut square from the kit's thumbnail.+ // project's source audio; the cover is the kit's cover art, else its thumbnail cut square.distrokid: (project, kit, options = {}) => {const title = text(project?.name);if (!title) throw missing('Name the project first: it is the song title on Spotify');@@ -173,7 +180,8 @@ const BUILDERS = {if (!artist) throw missing('Give the artist name the song is released under (or set it as the DistroKid account under Where you post)');const songwriter = { first: text(options.songwriterFirst), last: text(options.songwriterLast) };if (!songwriter.first || !songwriter.last) throw missing("DistroKid needs the songwriter's real first and last name");- if (!kit.thumbnail) throw missing('Pick a thumbnail in the publishing kit first: it becomes the cover art');+ const cover = releaseCover(kit);+ if (!cover) throw missing('Make the cover art in the publishing kit first (or pick a thumbnail)');const releaseDate = text(options.releaseDate);if (releaseDate && !/^\d{4}-\d{2}-\d{2}$/.test(releaseDate)) throw missing('Give the release date as YYYY-MM-DD');const hasLyrics = (project?.lyricCues || []).some((cue) => text(cue?.text));@@ -182,7 +190,7 @@ const BUILDERS = {explicit: options.explicit === true,instrumental: typeof options.instrumental === 'boolean' ? options.instrumental : !hasLyrics,ai: { lyrics: options.aiLyrics === true, music: options.aiMusic !== false, vocals: options.aiVocals !== false },- cover: { dir: 'videoThumbnails', name: kit.thumbnail },+ cover,};},};diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.jsindex 1440b8dafa..36eb8def6c 100644--- a/server/services/musicVideo/publish/payloads.test.js+++ b/server/services/musicVideo/publish/payloads.test.js@@ -136,5 +136,10 @@ describe('buildPublishPayload (#9282)', () => {});expect(buildPublishPayload('distrokid', song({ lyricCues: [] }), { ...who, aiLyrics: true, releaseDate: '2026-11-06' })).toMatchObject({ instrumental: true, releaseDate: '2026-11-06', ai: { lyrics: true } });+ // The composed cover art wins over the thumbnail, for DistroKid and Suno alike.+ const withCover = song({ publishKit: kit({ coverArt: { filename: 'cover-1.jpg' } }) });+ expect(buildPublishPayload('distrokid', withCover, who).cover).toEqual({ dir: 'videoThumbnails', name: 'cover-1.jpg', square: true });+ expect(buildPublishPayload('distrokid', { ...withCover, publishKit: kit({ thumbnail: null, coverArt: { filename: 'cover-1.jpg' } }) }, who).cover.name).toBe('cover-1.jpg');+ expect(buildPublishPayload('suno', withCover, { songUrl: 'https://suno.com/song/example' }).cover.name).toBe('cover-1.jpg');});});diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.jsindex 17d505319b..5e2ab6dcf3 100644--- a/server/services/musicVideo/publishKit.js+++ b/server/services/musicVideo/publishKit.js@@ -75,13 +75,13 @@ function thumbnailTimes(project, durationSec, max = MAX_THUMBNAILS) {}/** A file an older build left behind, deleted only once no project's kit still names it (a clone shares the record). */-async function releaseKitFiles(filenames, keep) {+export async function releaseKitFiles(filenames, keep = []) {if (!filenames.length) return;const others = await listProjects().catch(() => []);const referenced = new Set(keep);for (const p of others) {const kit = projectPublishKit(p);- for (const f of [...(kit.exports || []).map((e) => e.filename), ...(kit.thumbnails || []), kit.captionsFilename]) if (f) referenced.add(f);+ for (const f of [...(kit.exports || []).map((e) => e.filename), ...(kit.thumbnails || []), kit.captionsFilename, kit.coverArt?.filename]) if (f) referenced.add(f);}for (const name of filenames) {if (referenced.has(name)) continue;diff --git a/server/services/musicVideoCoverArtImageHook.js b/server/services/musicVideoCoverArtImageHook.jsnew file mode 100644index 0000000000..90482ffbc4--- /dev/null+++ b/server/services/musicVideoCoverArtImageHook.js@@ -0,0 +1,43 @@+/**+ * Music Video cover art image attach hook.+ *+ * "Make a cover image" (musicVideo/coverArt.js) queues one image on the normal+ * image queue with a `musicVideo: { projectId, coverArt: { requestId } }` tag.+ * This hook files the finished render as a cover source and composes the cover+ * from it, independent of any open client. A failed or cancelled job records+ * why. The scene-frame and Cast & Sets hooks ignore these jobs: their tag has+ * no `sceneId` or `castAndSets`.+ *+ * Built on the shared completion-hook scaffold (`createMediaJobImageHook`).+ * Mounted once at server boot; it only listens.+ */++import { createMediaJobImageHook } from './mediaJobImageHook.js';++const settle = async (payload) => (await import('./musicVideo/coverArt.js')).onCoverArtImageSettled(payload);++const hook = createMediaJobImageHook({+ label: 'music-video cover art image',+ initLog: '🖼️ Music Video cover art image hook initialized',+ tagKey: 'musicVideo',+ identify: (tag) => (tag?.projectId && typeof tag.coverArt?.requestId === 'string'+ ? { projectId: tag.projectId, requestId: tag.coverArt.requestId }+ : null),+ serializeKey: ({ projectId }) => projectId,+ describe: ({ projectId, requestId }) => `${projectId}/${requestId}`,+ attach: ({ projectId, requestId, filename }) => settle({ projectId, requestId, filename })+ .then((changed) => (changed ? { filename } : null)),+ onAttached: ({ projectId, filename }) => {+ console.log(`🖼️ music-video cover art ${projectId.slice(0, 11)} ← ${filename}`);+ },+ onTerminal: ({ projectId, requestId, job }, status) => settle({+ projectId, requestId, status, error: job?.error || `The render was ${status}`,+ }),+});++export function initMusicVideoCoverArtImageHook() {+ hook.init();+}++// Test-only reset so suites that re-init can do so cleanly.+export const __testing = hook.__testing;diff --git a/server/services/socket.js b/server/services/socket.jsindex 3eabccc2d6..bd37efbb64 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -323,6 +323,8 @@ const SIMPLE_BRIDGES = [{ emitter: musicVideoEvents, event: 'dev-artifact', channel: 'music-video:dev-artifact' },// A publish draft's tab was filled, closed by hand, or discarded.{ emitter: musicVideoEvents, event: 'publish-draft', channel: 'music-video:publish-draft' },+ // The release cover art was composed, or its source image was queued or failed.+ { emitter: musicVideoEvents, event: 'cover-art', channel: 'music-video:cover-art' },];let forwardingRegistered = false;