Skip to content

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

feat: render one launch video in several aspect ratios from a single timeline (#8960)

[._.]/ Adam Eivy6656caac8bf6
diff --git a/client/src/components/apps/LaunchVideoPanel.jsx b/client/src/components/apps/LaunchVideoPanel.jsx
index b3f467fdfa..e397eff8f8 100644
--- a/client/src/components/apps/LaunchVideoPanel.jsx
+++ b/client/src/components/apps/LaunchVideoPanel.jsx
@@ -17,6 +17,14 @@ const inputClass = 'w-full rounded border border-port-border bg-port-bg p-2 text
const buttonClass = 'rounded bg-port-accent px-3 py-2 text-white disabled:opacity-50';
const videoUrl = video => `/data/videos/${encodeURIComponent(video.filename)}`;
const posterUrl = video => `/data/video-thumbnails/${encodeURIComponent(video.thumbnail)}`;
+// One run can render the same timeline in several frames (#8960); the order is
+// the server's canonical render order.
+const FORMATS = [
+ ['landscape', 'Landscape 16:9'],
+ ['vertical', 'Vertical 9:16'],
+ ['square', 'Square 1:1'],
+];
+const formatLabel = format => FORMATS.find(([value]) => value === format)?.[1] ?? format;
const MOTION_STYLES = [
['walkthrough', 'Product walkthrough', 'A paced tour of the key flow, a cursor driving real actions on springs.'],
['showreel', 'Motion-graphics showreel', 'Beat-cut kinetic type, color-field swaps and generative shapes around the key flow.'],
@@ -29,7 +37,7 @@ const MOTION_STYLES = [
function LaunchVideoForm({ appId, onQueued }) {
const [tone, setTone] = useState('default');
const [direction, setDirection] = useState('');
- const [format, setFormat] = useState('landscape');
+ const [formats, setFormats] = useState(['landscape']);
const [duration, setDuration] = useState(20);
const [motionStyle, setMotionStyle] = useState('walkthrough');
const [critiqueRounds, setCritiqueRounds] = useState(2);
@@ -61,7 +69,8 @@ function LaunchVideoForm({ appId, onQueued }) {
if (submitting.current) return;
submitting.current = true;
await createAppLaunchVideo(appId, {
- tone, direction, format, targetDurationSec: duration, motionStyle, critiqueRounds,
+ // A single frame keeps the original `format` request shape.
+ tone, direction, ...(formats.length === 1 ? { format: formats[0] } : { formats }), targetDurationSec: duration, motionStyle, critiqueRounds,
...(consultSkills ? { motionSkills: true } : {}),
...(music ? (generateMusic ? { generateMusic: true, musicMethod } : { musicTrack }) : {}),
...picker.pin,
@@ -76,7 +85,16 @@ function LaunchVideoForm({ appId, onQueued }) {
</section>
<div><label htmlFor="launch-tone">Tone</label><select id="launch-tone" className={inputClass} value={tone} onChange={event => setTone(event.target.value)}>{['default', 'polished', 'deadpan', 'cinematic', 'parody'].map(value => <option key={value} value={value}>{value}</option>)}</select></div>
<div><label htmlFor="launch-direction">Direction (optional)</label><textarea id="launch-direction" className={inputClass} maxLength={2000} value={direction} onChange={event => setDirection(event.target.value)} /></div>
- <div><label htmlFor="launch-format">Format</label><select id="launch-format" className={inputClass} value={format} onChange={event => setFormat(event.target.value)}>{['landscape', 'vertical', 'square'].map(value => <option key={value} value={value}>{value}</option>)}</select></div>
+ <fieldset>
+ <legend>Formats</legend>
+ <div className="flex flex-wrap gap-x-4 gap-y-1">
+ {FORMATS.map(([value, label]) => <label key={value} htmlFor={`launch-format-${value}`}>
+ <input id={`launch-format-${value}`} type="checkbox" checked={formats.includes(value)}
+ onChange={event => setFormats(current => FORMATS.map(([name]) => name).filter(name => name === value ? event.target.checked : current.includes(name)))} /> {label}
+ </label>)}
+ </div>
+ <p className="text-sm text-port-text-muted">Several formats render one film from a single timeline, recomposed for each frame.</p>
+ </fieldset>
<div><label htmlFor="launch-duration">Duration (15–120 seconds)</label><input id="launch-duration" type="number" min={15} max={120} step={1} required className={inputClass} value={duration} onChange={event => setDuration(event.target.value === '' ? '' : Number(event.target.value))} /></div>
<div>
<label htmlFor="launch-motion-style">Motion style</label>
@@ -130,7 +148,7 @@ function LaunchVideoForm({ appId, onQueued }) {
</ul>}
</fieldset>}
<p className="text-sm text-port-text-muted">These options are submitted together. Follow and cancel the run in CoS agents.</p>
- <button type="submit" className={buttonClass} disabled={running || duration === '' || (music && !generateMusic && !musicTrack)}>{running ? 'Queuing…' : 'Queue launch video'}</button>
+ <button type="submit" className={buttonClass} disabled={running || !formats.length || duration === '' || (music && !generateMusic && !musicTrack)}>{running ? 'Queuing…' : 'Queue launch video'}</button>
</form>;
}
@@ -191,8 +209,17 @@ export default function LaunchVideoPanel({ app }) {
const [videos, setVideos] = useState([]);
const [error, setError] = useState('');
const [queued, setQueued] = useState(false);
- // The previewed take lives in the URL so a specific video is linkable.
+ // The previewed video lives in the URL so a specific take and format is linkable.
const selected = videos.find(video => video.id === search.get('video')) ?? videos[0];
+ // A multi-format run registers one video per format under one runId (#8960);
+ // the tab shows it as a single take. Older entries without a runId stand alone.
+ const takes = [...videos.reduce((groups, video) => {
+ const key = video.runId ?? video.id;
+ groups.set(key, [...(groups.get(key) ?? []), video]);
+ return groups;
+ }, new Map()).values()];
+ const selectedTake = takes.find(take => take.includes(selected)) ?? [];
+ const selectVideo = id => updateParams({ video: id }, { replace: true });
useEffect(() => {
let active = true;
@@ -221,10 +248,16 @@ export default function LaunchVideoPanel({ app }) {
{error && <p role="alert" className="text-port-error">{error}</p>}
{!videos.length && !error && <p className="text-sm text-port-text-muted">No launch videos yet.</p>}
{selected && <div className="space-y-2">
+ {selectedTake.length > 1 && <div role="group" aria-label="Formats in this take" className="flex flex-wrap gap-2">
+ {selectedTake.map(video => <button key={video.id} type="button" aria-pressed={video.id === selected.id} onClick={() => selectVideo(video.id)}
+ className={`rounded border px-2 py-1 text-sm ${video.id === selected.id ? 'border-port-accent text-port-text' : 'border-port-border text-port-text-muted'}`}>{formatLabel(video.format)}</button>)}
+ </div>}
<video key={selected.id} controls preload="metadata" className="max-h-[60vh] w-full bg-black" src={videoUrl(selected)} poster={posterUrl(selected)} aria-label="Selected launch video" />
<div className="flex flex-wrap items-center gap-4 text-sm">
<span className="text-port-text-muted">{formatDateTime(selected.createdAt)}{Number.isFinite(selected.durationSec) ? ` · ${formatDurationSec(selected.durationSec)}` : ''}</span>
- <a className="inline-flex items-center gap-1 text-port-accent" href={videoUrl(selected)} download={`${app.id}-launch-video-${selected.id}.mp4`}><Download size={14} aria-hidden="true" />Download</a>
+ {selectedTake.length > 1
+ ? selectedTake.map(video => <a key={video.id} className="inline-flex items-center gap-1 text-port-accent" href={videoUrl(video)} download={`${app.id}-launch-video-${video.id}.mp4`}><Download size={14} aria-hidden="true" />Download {formatLabel(video.format)}</a>)
+ : <a className="inline-flex items-center gap-1 text-port-accent" href={videoUrl(selected)} download={`${app.id}-launch-video-${selected.id}.mp4`}><Download size={14} aria-hidden="true" />Download</a>}
<button type="button" className="text-port-accent" onClick={() => copyToClipboard(selected.caption)}>Copy caption</button>
<Link className="text-port-accent" to="/media/history">Media History</Link>
</div>
@@ -233,13 +266,16 @@ export default function LaunchVideoPanel({ app }) {
<ReviseLaunchVideo key={`revision:${app.id}:${selected.id}`} appId={app.id} videoId={selected.id} />
<PublishLaunchVideo key={`${app.id}:${selected.id}`} appId={app.id} videoId={selected.id} />
</div>}
- {videos.length > 1 && <ul aria-label="Launch video takes" className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-6">
- {videos.map(video => <li key={video.id}>
- <button type="button" aria-pressed={video.id === selected?.id} onClick={() => updateParams({ video: video.id }, { replace: true })} className={`w-full overflow-hidden rounded border text-left ${video.id === selected?.id ? 'border-port-accent' : 'border-port-border'}`}>
- <img src={posterUrl(video)} alt="" loading="lazy" className="aspect-video w-full object-cover" />
- <span className="block truncate p-1 text-xs text-port-text-muted">{formatDateTime(video.createdAt)}</span>
- </button>
- </li>)}
+ {takes.length > 1 && <ul aria-label="Launch video takes" className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-6">
+ {takes.map(([video, ...others]) => {
+ const current = selectedTake[0] === video;
+ return <li key={video.id}>
+ <button type="button" aria-pressed={current} onClick={() => selectVideo(video.id)} className={`w-full overflow-hidden rounded border text-left ${current ? 'border-port-accent' : 'border-port-border'}`}>
+ <img src={posterUrl(video)} alt="" loading="lazy" className="aspect-video w-full object-cover" />
+ <span className="block truncate p-1 text-xs text-port-text-muted">{formatDateTime(video.createdAt)}{others.length ? ` · ${others.length + 1} formats` : ''}</span>
+ </button>
+ </li>;
+ })}
</ul>}
<Drawer open={open} onClose={() => updateParams({ launchVideo: null })} title="Make launch video" size="md">
{queued ? <div className="space-y-3"><p>Launch video queued. Closing this drawer leaves the run active.</p><Link className="text-port-accent" to="/cos/agents">Open CoS agents to follow or cancel the run</Link></div>
diff --git a/client/src/components/apps/LaunchVideoPanel.test.jsx b/client/src/components/apps/LaunchVideoPanel.test.jsx
index de61077fd3..96e65860a2 100644
--- a/client/src/components/apps/LaunchVideoPanel.test.jsx
+++ b/client/src/components/apps/LaunchVideoPanel.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import LaunchVideoPanel from './LaunchVideoPanel';
import { createAppLaunchVideo, getAppLaunchVideos, getMotionToolkit, publishAppLaunchVideo } from '../../services/apiApps';
@@ -25,7 +25,9 @@ describe('launch video drawer', () => {
renderPanel();
fireEvent.click(screen.getByRole('button', { name: 'Make launch video' }));
fireEvent.change(screen.getByLabelText('Tone'), { target: { value: 'cinematic' } });
- fireEvent.change(screen.getByLabelText('Format'), { target: { value: 'vertical' } });
+ // One frame keeps the original single `format` request.
+ fireEvent.click(screen.getByLabelText('Vertical 9:16'));
+ fireEvent.click(screen.getByLabelText('Landscape 16:9'));
fireEvent.change(screen.getByLabelText('Duration (15–120 seconds)'), { target: { value: '22' } });
fireEvent.click(screen.getByLabelText('Include music'));
// Each track is identifiable by name + file and audible before choosing it.
@@ -57,14 +59,19 @@ describe('launch video drawer', () => {
await waitFor(() => expect(screen.getByLabelText('Consult motion skills').disabled).toBe(false));
fireEvent.click(screen.getByLabelText('Consult motion skills'));
fireEvent.change(screen.getByLabelText('Duration (15–120 seconds)'), { target: { value: '90' } });
+ fireEvent.click(screen.getByLabelText('Landscape 16:9'));
+ expect(screen.getByRole('button', { name: 'Queue launch video' }).disabled).toBe(true);
+ fireEvent.click(screen.getByLabelText('Square 1:1'));
+ fireEvent.click(screen.getByLabelText('Vertical 9:16'));
fireEvent.click(screen.getByLabelText('Include music'));
expect(screen.getByLabelText('Generate original music').checked).toBe(false);
fireEvent.click(screen.getByLabelText('Generate original music'));
expect(screen.getByLabelText('Music creation').value).toBe('agent');
fireEvent.change(screen.getByLabelText('Music creation'), { target: { value: musicMethod } });
fireEvent.click(screen.getByRole('button', { name: 'Queue launch video' }));
- await waitFor(() => expect(createAppLaunchVideo).toHaveBeenCalledWith('example', expect.objectContaining({ targetDurationSec: 90, generateMusic: true, musicMethod, motionStyle: 'ui-morph', critiqueRounds: 3, motionSkills: true }), { silent: true }));
+ await waitFor(() => expect(createAppLaunchVideo).toHaveBeenCalledWith('example', expect.objectContaining({ formats: ['vertical', 'square'], targetDurationSec: 90, generateMusic: true, musicMethod, motionStyle: 'ui-morph', critiqueRounds: 3, motionSkills: true }), { silent: true }));
expect(createAppLaunchVideo.mock.calls[0][1].musicTrack).toBeUndefined();
+ expect(createAppLaunchVideo.mock.calls[0][1].format).toBeUndefined();
});
it('previews the URL-selected take and offers it for download', async () => {
@@ -85,6 +92,31 @@ describe('launch video drawer', () => {
});
+it('groups a multi-format run into one take with a download per format', async () => {
+ getAppLaunchVideos.mockResolvedValueOnce({ videos: [
+ { id: 'run-a-landscape', runId: 'run-a', format: 'landscape', filename: 'a-landscape.mp4', thumbnail: 'a-landscape.jpg', createdAt: '2026-01-02T00:00:00.000Z', caption: 'Run A.' },
+ { id: 'run-a-vertical', runId: 'run-a', format: 'vertical', filename: 'a-vertical.mp4', thumbnail: 'a-vertical.jpg', createdAt: '2026-01-02T00:00:00.000Z', caption: 'Run A.' },
+ { id: 'run-b', runId: 'run-b', format: 'square', filename: 'b.mp4', thumbnail: 'b.jpg', createdAt: '2026-01-01T00:00:00.000Z', caption: 'Run B.' },
+ ] });
+ renderPanel('/?video=run-a-vertical');
+ expect(await screen.findByText('Run A.')).toBeTruthy();
+ expect(screen.getByLabelText('Selected launch video').getAttribute('src')).toBe('/data/videos/a-vertical.mp4');
+ // Two takes, not three videos; the run's tile names its format count.
+ const takes = screen.getByRole('list', { name: 'Launch video takes' });
+ expect(takes.querySelectorAll('button')).toHaveLength(2);
+ expect(takes.textContent).toContain('2 formats');
+ expect(screen.getByRole('link', { name: 'Download Landscape 16:9' }).getAttribute('href')).toBe('/data/videos/a-landscape.mp4');
+ expect(screen.getByRole('link', { name: 'Download Vertical 9:16' }).getAttribute('href')).toBe('/data/videos/a-vertical.mp4');
+ const switcher = screen.getByRole('group', { name: 'Formats in this take' });
+ fireEvent.click(within(switcher).getByRole('button', { name: 'Landscape 16:9' }));
+ await waitFor(() => expect(screen.getByLabelText('Selected launch video').getAttribute('src')).toBe('/data/videos/a-landscape.mp4'));
+ fireEvent.click(takes.querySelectorAll('button')[1]);
+ expect(await screen.findByText('Run B.')).toBeTruthy();
+ expect(screen.queryByRole('group', { name: 'Formats in this take' })).toBeNull();
+ expect(screen.getByRole('link', { name: 'Download' }).getAttribute('href')).toBe('/data/videos/b.mp4');
+});
+
+
it('publishes the URL-selected take once and exposes the queued workflow', async () => {
getAppLaunchVideos.mockResolvedValueOnce({ videos: [
{ id: 'newest', filename: 'newest.mp4', createdAt: '2026-01-02' },
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 99c641c680..a240602eaa 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -50,6 +50,37 @@ with the same tail fade, and removes the temporary file after completion or
failure. No music model, Python runtime, downloaded samples or music-library
write is required. Missing or invalid audio fails the job.
+## Several formats from one timeline
+
+One job can render the same composition at several aspect ratios, so a launch
+posted to several platforms is one film recomposed per frame rather than one
+agent run per format. The composition declares the extra sizes it supports and
+an optional layout hook:
+
+```js
+globalThis.portosComposition = {
+ durationSec: 20, fps: 24, width: 1920, height: 1080,
+ formats: ['1920x1080', '1080x1920', '1080x1080'],
+ async layout({ width, height }) { /* reflow type and UI for this frame */ },
+ async seek(t) { /* same timeline in every format */ },
+};
+```
+
+The render request names formats: `"formats": ["landscape", "vertical", "square"]`
+(1920×1080, 1080×1920, 1080×1080). The renderer renders them in that canonical
+order, in sequence, on the same page and frozen asset snapshot: for each one it
+resizes the viewport, awaits `layout({ width, height })` when defined, then seeks
+every frame. Duration, fps and timing are shared, and synthesized music is
+rendered once and muxed into every format. A requested format whose size is
+neither the composition's own `width`×`height` nor listed in `formats` fails
+the job before any output, naming the missing size. Without `formats` in the
+request, a job renders the composition's own size exactly as before.
+
+Each format is its own Media History entry (`<jobId>-<format>`), all written in
+one history update, so a job registers every format or none. The completed
+job result keeps `filename`/`thumbnail` for the first format and lists all of
+them in `videos: [{ format, id, filename, thumbnail, path }]`.
+
## Motion kit
`server/services/htmlComposition/kit/portos-motion.js` is a deterministic
@@ -75,13 +106,15 @@ directory. It is ordinary UTF-8 source, so it passes the launch asset gate.
## Proof renders (contact sheets)
Add `proof: { everySec: 1 }` (0.25–10 seconds) to the render request to get a
-silent contact sheet instead of a video. The renderer applies the same contract
+silent contact sheet instead of a video. `proof.format` (`landscape`,
+`vertical` or `square`) checks one declared framing, running `layout` first;
+a proof request cannot also carry `formats`. The renderer applies the same contract
and launch-video gates, seeks one frame per interval (at most 60), and tiles
them six across at phone size (360px wide, 240px for vertical) into one PNG.
A proof is silent, so the request must omit `musicTrack` and
`synthesizeMusic`. Nothing is registered in Media History and no
launch-video artifacts are delivered. The completed job's result carries
-`proof: { file, url, times, columns, width, height }`, where `file` is
+`proof: { file, url, times, columns, width, height }` (plus `format` when one was requested), where `file` is
relative to the data directory (never an absolute host path) and `url` serves
it under `/data/`; tile *n* shows `times[n]`.
Launch runs write `proofs/contact-<jobId>.png` beside the run; other
@@ -120,7 +153,7 @@ explicitly when either binary is unavailable; route and queue tests still run.
This option is required for directories rooted at `launch-videos/` and can also
be applied to other composition directories. An app's **Launch Video** tab
(`/apps/<appId>/launch-video`, also linked from Overview) queues a user-triggered CoS task with
-tone, direction, format, duration (15–120 seconds), an optional **Dynamic motion
+tone, direction, one or more formats (landscape, vertical, square), duration (15–120 seconds), an optional **Dynamic motion
graphics** style, optional generated original
music or an existing Music-library track (each listed with its filename and an
inline audio preview), and an optional
@@ -168,10 +201,18 @@ App runs pass `appId` and `runId` together in `launchVideo`, with directory exac
`launch-videos/<appId>/<runId>/composition`. The run is pinned to this instance.
On success, the renderer exclusively creates `plan.md`, `storyboard.json`,
`caption.txt`, `video.mp4` and `poster.jpg` beside `composition/`, using the
-validated in-memory source snapshot. Media History retains its normal video
+validated in-memory source snapshot. A run that asked for several formats
+(`formats` on the launch-video request; the older single `format` is a
+one-item list) gets one composition written against `layout`, and its render
+delivers `video-<format>.mp4` and `poster-<format>.jpg` per format with the
+plan, storyboard and caption once. Every format's history entry carries the
+same `launchVideo.runId`, and the privacy and storyboard gates run once per job
+on the frozen assets. A revision re-renders every format its source run
+delivered. Media History retains its normal video
and thumbnail copies with app/run metadata. The Launch Video tab previews the
-recent takes (the selected one is the `?video=<id>` URL param, newest by
-default), with caption copy, an MP4 download, and a new-run action. Existing artifacts are never
+recent takes (the selected video is the `?video=<id>` URL param, newest by
+default), groups a run's formats into one take with a format switcher and a
+download per format, and offers caption copy and a new-run action. Existing artifacts are never
overwritten. This reuses CoS queues and media history; it adds no record store.
Alongside `index.html`, put non-empty `plan.md`, `caption.txt`, and
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b105afe831..a6720f3ea4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2451,12 +2451,24 @@ export const appLaunchVideoPublishSchema = z.object({
export const LAUNCH_VIDEO_MOTION_STYLES = Object.freeze(['walkthrough', 'showreel', 'ui-morph']);
+// One launch timeline can render several frames (#8960). Each name maps to the
+// exact size a composition declares in portosComposition.formats; the order is
+// the canonical render/delivery order.
+export const LAUNCH_VIDEO_FORMAT_SIZES = Object.freeze({ landscape: '1920x1080', vertical: '1080x1920', square: '1080x1080' });
+export const LAUNCH_VIDEO_FORMATS = Object.freeze(Object.keys(LAUNCH_VIDEO_FORMAT_SIZES));
+const launchVideoFormatSchema = z.enum(LAUNCH_VIDEO_FORMATS);
+const launchVideoFormatListSchema = z.array(launchVideoFormatSchema).min(1).max(LAUNCH_VIDEO_FORMATS.length)
+ .refine(list => new Set(list).size === list.length, 'formats must not repeat');
+
export const appLaunchVideoRequestSchema = z.object({
sourceVideoId: z.string().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/).optional(),
feedback: z.string().trim().min(1).max(4000).optional(),
tone: z.enum(['default', 'polished', 'deadpan', 'cinematic', 'parody']).default('default'),
direction: z.string().trim().max(2000).default(''),
- format: z.enum(['landscape', 'vertical', 'square']).default('landscape'),
+ // `format` is the single-frame form older callers send; `formats` asks one
+ // run for several aspect ratios of the same film. The route normalizes both.
+ format: launchVideoFormatSchema.optional(),
+ formats: launchVideoFormatListSchema.optional(),
targetDurationSec: z.number().int().min(15).max(120).default(20),
generateMusic: z.boolean().default(false),
musicMethod: z.enum(['agent', 'service']).default('agent'),
@@ -2495,10 +2507,15 @@ export const htmlCompositionRenderSchema = z.object({
synthesizeMusic: z.boolean().optional(),
directory: z.string().min(1).max(1024).refine(value => !value.startsWith('/') && !value.includes('\\') && !value.includes(':') && !value.split('/').some(part => part === '..' || part === '.' || !part), 'directory must be a relative path inside data'),
musicTrack: z.string().min(1).max(255).regex(/^[^/\\]+$/, 'musicTrack must be a Music-library filename').optional(),
- // A proof renders a silent contact sheet for review instead of the video.
- proof: z.object({ everySec: z.number().min(0.25).max(10).default(1) }).strict().optional(),
+ // Several aspect ratios of one timeline, rendered in sequence on one page.
+ // Omitted, the job renders the composition's own width/height as before.
+ formats: launchVideoFormatListSchema.optional(),
+ // A proof renders a silent contact sheet for review instead of the video;
+ // `format` checks one declared framing, defaulting to the composition's own.
+ proof: z.object({ everySec: z.number().min(0.25).max(10).default(1), format: launchVideoFormatSchema.optional() }).strict().optional(),
}).refine(value => !(value.synthesizeMusic && value.musicTrack), 'Choose synthesized music or a library track, not both')
- .refine(value => !(value.proof && (value.synthesizeMusic || value.musicTrack)), 'A proof is silent; omit synthesizeMusic and musicTrack');
+ .refine(value => !(value.proof && (value.synthesizeMusic || value.musicTrack)), 'A proof is silent; omit synthesizeMusic and musicTrack')
+ .refine(value => !(value.proof && value.formats), 'A proof checks one framing; use proof.format instead of formats');
// GET /api/html-composition/beats — a Music-library filename, same shape as
// htmlCompositionRenderSchema's musicTrack but required (this endpoint exists
@@ -2515,6 +2532,10 @@ export const htmlCompositionContractSchema = z.object({
// Subframes averaged per output frame to fake motion blur on fast moves;
// 1 (default) keeps the existing single-sample-per-frame behavior.
motionBlur: z.number().int().min(1).max(4).default(1),
+ // Extra sizes this one timeline can render (#8960), reframed by the optional
+ // layout({ width, height }) hook before each format's first seek.
+ formats: z.array(z.enum(Object.values(LAUNCH_VIDEO_FORMAT_SIZES))).min(1).max(LAUNCH_VIDEO_FORMATS.length).optional(),
+ layout: z.boolean().default(false),
}).superRefine((value, ctx) => {
if (!['1920x1080', '1080x1920', '1080x1080', '1280x720'].includes(`${value.width}x${value.height}`)) {
ctx.addIssue({ code: 'custom', path: ['width'], message: 'width/height must be 1920x1080, 1080x1920, 1080x1080 or 1280x720' });
diff --git a/server/routes/apps/launchVideos.js b/server/routes/apps/launchVideos.js
index 99eb045ac4..53f8e751d8 100644
--- a/server/routes/apps/launchVideos.js
+++ b/server/routes/apps/launchVideos.js
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
import { mkdir, realpath, rm, stat, writeFile } from 'node:fs/promises';
import { join, dirname, resolve } from 'node:path';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { appLaunchVideoRequestSchema, appLaunchVideoPublishSchema, validateRequest } from '../../lib/validation.js';
+import { LAUNCH_VIDEO_FORMATS, appLaunchVideoRequestSchema, appLaunchVideoPublishSchema, validateRequest } from '../../lib/validation.js';
import { pullRequestProviderOverrideSchema } from '../../lib/cosValidation.js';
import { PATHS } from '../../lib/fileUtils.js';
import { PORTOS_API_URL } from '../../lib/portosUrls.js';
@@ -25,6 +25,11 @@ const LAUNCH_VIDEO_LIST_LIMIT = 50;
// composition/ directory so the agent can cut on it instead of guessing a BPM.
const BEATS_FILENAME = 'beats.json';
const publishTaskSchema = appLaunchVideoPublishSchema.extend(pullRequestProviderOverrideSchema.shape);
+// A rendered take's frame, from the size Media History recorded for it.
+const formatOf = ({ width, height }) => {
+ if (!Number.isFinite(width) || !Number.isFinite(height)) return undefined;
+ return width === height ? 'square' : width < height ? 'vertical' : 'landscape';
+};
const missingVideoSource = err => {
if (err.code === 'ENOENT') throw new ServerError('Launch video file is missing', { status: 404 });
throw err;
@@ -63,9 +68,12 @@ router.post('/:id/launch-videos/publish', loadApp, asyncHandler(async (req, res)
}));
router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
- const { provider, model, effort, sourceVideoId, feedback, motionGraphics, ...options } = validateRequest(launchVideoTaskSchema, req.body);
+ const { provider, model, effort, sourceVideoId, feedback, motionGraphics, format, formats: requestedFormats, ...options } = validateRequest(launchVideoTaskSchema, req.body);
options.motionStyle ??= motionGraphics ? 'showreel' : 'walkthrough';
if (Boolean(sourceVideoId) !== Boolean(feedback)) throw new ServerError('Choose a source video and provide feedback together', { status: 400 });
+ if (format && requestedFormats) throw new ServerError('Choose format or formats, not both', { status: 400 });
+ // `format` is the older single-frame request; both normalize to one list.
+ let formats = requestedFormats ?? [format ?? 'landscape'];
const app = req.loadedApp;
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(app.id) || !app.repoPath || !await pathExists(app.repoPath)) {
throw new ServerError('App repository is unavailable', { status: 400 });
@@ -88,7 +96,8 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
let assets;
if (sourceVideoId) {
const { loadHistory } = await import('../../services/videoGen/history.js');
- sourceVideo = (await loadHistory()).find(item => item.id === sourceVideoId && item.launchVideo?.appId === app.id);
+ const history = await loadHistory();
+ sourceVideo = history.find(item => item.id === sourceVideoId && item.launchVideo?.appId === app.id);
if (!sourceVideo) throw new ServerError('Launch video not found for this app', { status: 404 });
const sourceRunId = sourceVideo.launchVideo.runId;
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(sourceRunId ?? '')) throw new ServerError('This video has no editable source', { status: 409 });
@@ -102,11 +111,19 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
options.targetDurationSec = sourceVideo.durationSec;
validateLaunchVideoAssets(assets, { targetDurationSec: options.targetDurationSec });
// Revisions inherit the selected take, never the new-video form defaults.
- options.format = sourceVideo.width === sourceVideo.height ? 'square' : sourceVideo.width < sourceVideo.height ? 'vertical' : 'landscape';
+ // A multi-format run (#8960) is one take, so its revision re-renders every
+ // format that run delivered, not only the one being previewed.
+ const runFormats = history.filter(item => item.launchVideo?.appId === app.id && item.launchVideo.runId === sourceRunId)
+ .map(formatOf).filter(Boolean);
+ formats = runFormats.length ? runFormats : [formatOf(sourceVideo) ?? 'landscape'];
options.musicTrack = sourceVideo.launchVideo.musicTrack ?? undefined;
options.generateMusic = false;
for (const key of ['tone', 'direction', 'motionStyle', 'musicMethod']) delete options[key];
}
+ formats = LAUNCH_VIDEO_FORMATS.filter(name => formats.includes(name));
+ // One format keeps the original single-format prompt and render contract.
+ if (formats.length > 1) options.formats = formats;
+ else options.format = formats[0];
// A chosen library track gets its real tempo measured (#8958) so the agent
// can cut on it instead of guessing a BPM. Best-effort: a track that fails
// to decode (no ffmpeg, unsupported format, no confident tempo) still
@@ -119,7 +136,7 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
const { getBeatGrid } = await import('../../lib/beatGrid.js');
musicTrackBeatGrid = await getBeatGrid(trackPath).catch(() => null);
}
- const payload = { directory, musicTrack: options.musicTrack,
+ const payload = { directory, musicTrack: options.musicTrack, ...(options.formats ? { formats: options.formats } : {}),
...((sourceVideo?.launchVideo.synthesizeMusic || (options.generateMusic && options.musicMethod === 'agent')) ? { synthesizeMusic: true } : {}),
launchVideo: { appId: app.id, runId, targetDurationSec: options.targetDurationSec, ...(sourceVideoId ? { sourceVideoId } : {}) } };
const outputRoot = join(PATHS.data, 'launch-videos', app.id, runId);
@@ -171,8 +188,10 @@ router.get('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
const { loadHistory } = await import('../../services/videoGen/history.js');
// Bounded projection of the existing media store, not a new run database.
const videos = (await loadHistory()).filter(item => item.launchVideo?.appId === req.loadedApp.id)
- .slice(0, LAUNCH_VIDEO_LIST_LIMIT).map(({ id, filename, thumbnail, createdAt, durationSec, launchVideo }) => ({
+ .slice(0, LAUNCH_VIDEO_LIST_LIMIT).map(({ id, filename, thumbnail, createdAt, durationSec, width, height, launchVideo }) => ({
id, filename, thumbnail, createdAt, durationSec, caption: launchVideo.caption, ...(launchVideo.sourceVideoId ? { sourceVideoId: launchVideo.sourceVideoId } : {}),
+ // runId groups a multi-format run's entries into one take in the tab.
+ runId: launchVideo.runId, format: formatOf({ width, height }),
}));
res.json({ videos });
}));
diff --git a/server/routes/apps/launchVideos.test.js b/server/routes/apps/launchVideos.test.js
index cccc1065b1..ab8bb77576 100644
--- a/server/routes/apps/launchVideos.test.js
+++ b/server/routes/apps/launchVideos.test.js
@@ -67,6 +67,29 @@ describe('user-triggered launch videos', () => {
expect(duplicate.body.code).toBe('LAUNCH_VIDEO_ACTIVE');
});
+ it('asks one run for several aspect ratios of the same film, keeping the single-format contract for one (#8960)', async () => {
+ const response = await submit({ formats: ['square', 'landscape', 'vertical'] });
+ expect(response.status).toBe(202);
+ const { prompt } = addTask.mock.calls[0][0];
+ // Canonical order in both the agent's options and the render payload it submits.
+ expect(prompt).toContain('"formats":["landscape","vertical","square"]');
+ expect(prompt).not.toContain('"format":');
+ const renderJson = JSON.parse(prompt.match(/^Render JSON: (.*)$/m)[1]);
+ expect(renderJson.formats).toEqual(['landscape', 'vertical', 'square']);
+ expect(prompt).toContain('portosComposition.formats');
+ addTask.mockClear();
+ // A one-item list is the older single-format request.
+ expect((await submit({ formats: ['vertical'] })).status).toBe(202);
+ const single = addTask.mock.calls[0][0].prompt;
+ expect(single).toContain('"format":"vertical"');
+ expect(JSON.parse(single.match(/^Render JSON: (.*)$/m)[1])).not.toHaveProperty('formats');
+ addTask.mockClear();
+ expect((await submit({ format: 'square', formats: ['square', 'vertical'] })).status).toBe(400);
+ expect((await submit({ formats: ['square', 'square'] })).status).toBe(400);
+ expect((await submit({ formats: [] })).status).toBe(400);
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
it('queues a two-minute managed-app video with explicit music generation and product context', async () => {
getAppById.mockResolvedValue({ id: 'example', name: 'Example Product', repoPath: process.cwd(), processes: [{ name: 'example-ui', port: 4321 }], secret: 'never-forward' });
expect((await submit({ targetDurationSec: 120, generateMusic: true, motionGraphics: true })).status).toBe(202);
@@ -151,6 +174,14 @@ describe('user-triggered launch videos', () => {
expect(response.status).toBe(200);
expect(response.body.videos).toHaveLength(50);
expect(response.body.videos[0]).toEqual({ id: 'video-0', filename: 'example.mp4', thumbnail: 'example.jpg', createdAt: '2026-01-01T00:00:00.000Z', durationSec: 20, caption: 'A clear plan.' });
+ // A multi-format run's entries carry their run and frame so the tab groups them into one take.
+ loadHistory.mockResolvedValue([
+ { id: 'run-a-vertical', width: 1080, height: 1920, launchVideo: { appId: 'example', runId: 'run-a' } },
+ { id: 'run-a-square', width: 1080, height: 1080, launchVideo: { appId: 'example', runId: 'run-a' } },
+ ]);
+ expect((await request(app).get('/api/apps/example/launch-videos')).body.videos.map(({ id, runId, format }) => ({ id, runId, format }))).toEqual([
+ { id: 'run-a-vertical', runId: 'run-a', format: 'vertical' }, { id: 'run-a-square', runId: 'run-a', format: 'square' },
+ ]);
loadHistory.mockRejectedValue(new Error('Storage unavailable'));
expect((await request(app).get('/api/apps/example/launch-videos')).status).toBe(500);
});
@@ -262,6 +293,15 @@ describe('feedback revisions', () => {
expect(task.prompt).toContain('"format":"vertical"');
expect(task.prompt).toContain('"synthesizeMusic":true');
});
+ it('revises every format of a multi-format take, whichever format was previewed (#8960)', async () => {
+ const sibling = (format, width, height) => ({ ...video, id: `take-${format}`, width, height });
+ loadHistory.mockResolvedValue([sibling('square', 1080, 1080), video, sibling('landscape', 1920, 1080),
+ { ...sibling('landscape', 1920, 1080), id: 'other-run', launchVideo: { ...video.launchVideo, runId: 'other-run' } }]);
+ expect((await submit({ sourceVideoId: 'take-square', feedback: 'Tighten the intro' })).status).toBe(202);
+ const { prompt } = addTask.mock.calls[0][0];
+ expect(prompt).toContain('"formats":["landscape","vertical","square"]');
+ expect(JSON.parse(prompt.match(/^Render JSON: (.*)$/m)[1]).formats).toEqual(['landscape', 'vertical', 'square']);
+ });
it('drops a stale beats.json copied from the source take when this revision has no musicTrack (#8958)', async () => {
// Simulates a source composition carrying a leftover beats.json from an
// earlier run whose musicTrack this revision no longer uses.
diff --git a/server/routes/htmlComposition.launchVideo.test.js b/server/routes/htmlComposition.launchVideo.test.js
index 7858ec1978..67349f7e45 100644
--- a/server/routes/htmlComposition.launchVideo.test.js
+++ b/server/routes/htmlComposition.launchVideo.test.js
@@ -93,6 +93,8 @@ describe('launch-video render admission', () => {
});
it('cannot omit the gate for a launch-videos directory', async () => {
expect((await submit({ launchVideo: undefined })).status).toBe(400);
+ // A proof checks one framing; several formats belong only to the final render.
+ expect((await submit({ formats: ['landscape', 'vertical'], proof: { everySec: 1 } })).status).toBe(400);
expect(enqueueJob).not.toHaveBeenCalled();
});
it('fails closed on uninspectable raster assets', async () => {
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 974ee6ca45..e5163aad07 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -4,6 +4,18 @@ import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { findFfmpeg, H264_ENCODE_ARGS, AAC_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter } from '../../lib/ffmpeg.js';
+// Size the viewport for this format, then let the composition reframe itself
+// (#8960) before any seek captures it. A composition without a layout hook
+// renders exactly as before.
+async function frameFormat(page, { width, height, layout }) {
+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ if (layout) {
+ page.check();
+ await page.evaluate(`globalThis.portosComposition.layout({ width: ${width}, height: ${height} })`);
+ }
+ page.check();
+}
+
// Stream one frame at a time. The write callback supplies back-pressure and
// the terminal race releases a pending write on exit, disconnect or cancel.
export async function encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress } = {}) {
@@ -20,7 +32,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
const motionBlurFilter = sub > 1
? `tmix=frames=${sub},select='eq(mod(n\\,${sub})\\,${sub - 1})',setpts=N/${fps}/TB`
: null;
- await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ await frameFormat(page, contract);
const args = ['-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps * sub), '-vcodec', 'png', '-i', 'pipe:0'];
if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);
args.push('-map', '0:v', '-vf', [motionBlurFilter, 'scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS);
@@ -98,7 +110,7 @@ export async function encodeContactSheet(page, contract, outputPath, { times, si
const tileWidth = width < height ? 240 : 360;
const columns = Math.min(PROOF_COLUMNS, times.length);
const rows = Math.ceil(times.length / columns);
- await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ await frameFormat(page, contract);
const proc = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-vcodec', 'png', '-i', 'pipe:0',
'-vf', `scale=${tileWidth}:-2,tile=${columns}x${rows}:padding=4:color=black`,
'-frames:v', '1', '-y', outputPath], safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));
diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.js
index 67d775b39d..9b9c95b0a0 100644
--- a/server/services/htmlComposition/index.js
+++ b/server/services/htmlComposition/index.js
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { PATHS, ensureDir, unlinkGuarded } from '../../lib/fileUtils.js';
-import { htmlCompositionContractSchema, htmlCompositionRenderSchema, validateRequest } from '../../lib/validation.js';
+import { LAUNCH_VIDEO_FORMATS, LAUNCH_VIDEO_FORMAT_SIZES, htmlCompositionContractSchema, htmlCompositionRenderSchema, validateRequest } from '../../lib/validation.js';
import { generateThumbnail } from '../../lib/ffmpeg.js';
import { videoGenEvents } from '../videoGen/events.js';
import { mutateVideoHistory } from '../videoGen/history.js';
@@ -22,27 +22,49 @@ export function cancel(jobId) {
return true;
}
+// The frame fields a render publishes; `formats`/`layout` describe the source only.
+const frameOf = ({ durationSec, fps, width, height, motionBlur }) => ({ durationSec, fps, width, height, motionBlur });
+
+/**
+ * The frames one job renders from a single timeline (#8960). Without requested
+ * formats it is the composition's own size under the job id, exactly as before.
+ * A named format other than the composition's own size must be declared in
+ * portosComposition.formats, so a fixed-layout scene is never squeezed into a
+ * frame it was not written for. Duration, fps and timing are shared by all.
+ */
+function renderTargets(contract, jobId, formats) {
+ if (!formats) return [{ id: jobId, format: null, contract }];
+ const own = `${contract.width}x${contract.height}`;
+ return LAUNCH_VIDEO_FORMATS.filter(format => formats.includes(format)).map(format => {
+ const size = LAUNCH_VIDEO_FORMAT_SIZES[format];
+ if (size !== own && !contract.formats?.includes(size)) {
+ throw new Error(`portosComposition.formats must include ${size} to render ${format}`);
+ }
+ const [width, height] = size.split('x').map(Number);
+ return { id: `${jobId}-${format}`, format, contract: { ...contract, width, height } };
+ });
+}
+
export async function renderComposition({ jobId, ...input }) {
const job = { controller: new AbortController(), committing: false };
active.set(jobId, job);
const { signal } = job.controller;
- const filename = `composition-${jobId}.mp4`;
- const outputPath = join(PATHS.videos, filename);
let page;
let audioDirectory;
let success = false;
let result;
let failure;
- let proofPath;
- const deliveredPaths = [];
+ // Every file this job creates, recorded before its first byte, so a failure
+ // or cancellation removes all formats' partial output.
+ const ownedPaths = [];
const deliver = async (target, write) => {
const handle = await open(target, 'wx');
// Record ownership after exclusive creation, before any fallible I/O.
- deliveredPaths.push(target);
+ ownedPaths.push(target);
try { await write(handle); } finally { await handle.close(); }
};
try {
- const { directory, musicTrack, launchVideo, synthesizeMusic, proof } = validateRequest(htmlCompositionRenderSchema, input);
+ const { directory, musicTrack, launchVideo, synthesizeMusic, proof, formats } = validateRequest(htmlCompositionRenderSchema, input);
let musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;
if (musicTrack && !musicPath) throw new Error('musicTrack is missing from the Music library');
signal.throwIfAborted();
@@ -57,13 +79,16 @@ export async function renderComposition({ jobId, ...input }) {
deliveryRoot = join(dataRoot, 'launch-videos', launchVideo.appId, launchVideo.runId);
}
const needsLaunchGate = launchVideo || directory.split('/')[0] === 'launch-videos';
+ // One page and one frozen snapshot per job: the privacy and storyboard
+ // gates run once however many formats render from it.
page = await openComposition(directory, { signal, validateAssets: needsLaunchGate
? assets => { launchPlan = validateLaunchVideoAssets(assets, launchVideo); launchAssets = assets; }
: undefined });
const metadata = await page.evaluate(`(() => {
const c = globalThis.portosComposition;
if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');
- return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, motionBlur: c.motionBlur };
+ return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, motionBlur: c.motionBlur,
+ formats: c.formats, layout: typeof c.layout === 'function' };
})()`);
const parsed = htmlCompositionContractSchema.safeParse(metadata);
if (!parsed.success) throw new Error(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));
@@ -72,24 +97,29 @@ export async function renderComposition({ jobId, ...input }) {
throw new Error('Composition durationSec must match storyboard.json');
}
if (proof) {
+ const [target] = renderTargets(contract, jobId, proof.format && [proof.format]);
// Launch runs keep their proofs beside the run so the iteration history
// stays with the take; other compositions share one proofs directory.
// The result names the sheet relative to the data directory, never an
// absolute host path: job results are visible to API and SSE clients.
const proofName = `contact-${jobId}.png`;
const proofFile = deliveryRoot ? `launch-videos/${launchVideo.appId}/${launchVideo.runId}/proofs/${proofName}` : `composition-proofs/${proofName}`;
- proofPath = deliveryRoot ? join(deliveryRoot, 'proofs', proofName) : join(PATHS.data, proofFile);
+ const proofPath = deliveryRoot ? join(deliveryRoot, 'proofs', proofName) : join(PATHS.data, proofFile);
await ensureDir(dirname(proofPath));
const times = proofTimes(contract.durationSec, proof.everySec);
- const { columns } = await encodeContactSheet(page, contract, proofPath, { times, signal });
+ ownedPaths.push(proofPath);
+ const { columns } = await encodeContactSheet(page, target.contract, proofPath, { times, signal });
page.check();
await page.close({ verify: true });
page = null;
signal.throwIfAborted();
success = true;
- result = { generationId: jobId, id: jobId, proof: { file: proofFile, url: `/data/${proofFile}`, times, columns, ...contract } };
+ result = { generationId: jobId, id: jobId, proof: { file: proofFile, url: `/data/${proofFile}`, times, columns,
+ ...(target.format ? { format: target.format } : {}), ...frameOf(target.contract) } };
} else {
+ const targets = renderTargets(contract, jobId, formats);
if (synthesizeMusic) {
+ // One score for every format: they share the timeline and duration.
const wav = await synthesizeCompositionMusic(page, contract.durationSec);
page.check();
audioDirectory = await mkdtemp(join(tmpdir(), 'portos-composition-audio-'));
@@ -97,28 +127,40 @@ export async function renderComposition({ jobId, ...input }) {
await writeFile(musicPath, wav, { flag: 'wx' });
}
await ensureDir(PATHS.videos);
- await encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress: progress => {
- videoGenEvents.emit('progress', { generationId: jobId, progress: progress * 0.95 });
- } });
+ const rendered = [];
+ for (const [index, target] of targets.entries()) {
+ const filename = `composition-${target.id}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+ ownedPaths.push(outputPath, join(PATHS.videoThumbnails, `${target.id}.jpg`));
+ await encodeComposition(page, target.contract, outputPath, { musicPath, signal, onProgress: progress => {
+ videoGenEvents.emit('progress', { generationId: jobId, progress: (index + progress) / targets.length * 0.95 });
+ } });
+ page.check();
+ rendered.push({ ...target, filename, outputPath });
+ }
// End script execution before post-processing and publishing the result.
- page.check();
await page.close({ verify: true });
page = null;
signal.throwIfAborted();
- const thumbnail = await generateThumbnail(outputPath, jobId, launchPlan ? { atSec: launchPlan.posterSec } : undefined);
- if (!thumbnail) throw new Error('Composition thumbnail generation failed');
- signal.throwIfAborted();
+ for (const video of rendered) {
+ video.thumbnail = await generateThumbnail(video.outputPath, video.id, launchPlan ? { atSec: launchPlan.posterSec } : undefined);
+ if (!video.thumbnail) throw new Error('Composition thumbnail generation failed');
+ signal.throwIfAborted();
+ }
let launchMetadata;
if (deliveryRoot) {
// Exclusive creation refuses pre-existing files/symlinks. Publish only the
// validated snapshot, never re-read source prose after rendering.
for (const name of ['plan.md', 'storyboard.json', 'caption.txt']) {
- const target = join(deliveryRoot, name);
- await deliver(target, handle => handle.writeFile(launchAssets.get(`/${name}`)));
+ await deliver(join(deliveryRoot, name), handle => handle.writeFile(launchAssets.get(`/${name}`)));
}
- for (const [source, name] of [[outputPath, 'video.mp4'], [join(PATHS.videoThumbnails, thumbnail), 'poster.jpg']]) {
- const target = join(deliveryRoot, name);
- await deliver(target, handle => pipeline(createReadStream(source), handle.createWriteStream()));
+ // A multi-format run names each file by its frame; a single-format
+ // render keeps the original video.mp4/poster.jpg names.
+ for (const video of rendered) {
+ const suffix = video.format ? `-${video.format}` : '';
+ for (const [source, name] of [[video.outputPath, `video${suffix}.mp4`], [join(PATHS.videoThumbnails, video.thumbnail), `poster${suffix}.jpg`]]) {
+ await deliver(join(deliveryRoot, name), handle => pipeline(createReadStream(source), handle.createWriteStream()));
+ }
}
launchMetadata = { appId: launchVideo.appId, runId: launchVideo.runId,
...(launchVideo.sourceVideoId ? { sourceVideoId: launchVideo.sourceVideoId } : {}),
@@ -128,15 +170,21 @@ export async function renderComposition({ jobId, ...input }) {
signal.throwIfAborted();
// Once the shared history write starts, cancellation must be refused.
job.committing = true;
- const meta = {
- id: jobId, prompt: `HTML composition: ${directory}`, modelId: 'html-composition', seed: 0,
- ...contract, numFrames: Math.round(contract.durationSec * contract.fps),
+ const createdAt = new Date().toISOString();
+ // One Media History entry per format, linked by launchVideo.runId and
+ // written in a single mutation so a run registers all formats or none.
+ const metas = rendered.map(video => ({
+ id: video.id, prompt: `HTML composition: ${directory}`, modelId: 'html-composition', seed: 0,
+ ...frameOf(video.contract), numFrames: Math.round(contract.durationSec * contract.fps),
...(launchMetadata ? { launchVideo: launchMetadata, appId: launchMetadata.appId, posterSec: launchPlan.posterSec } : {}),
- filename, thumbnail, createdAt: new Date().toISOString(),
- };
- await mutateVideoHistory(history => { history.unshift(meta); return history; });
+ filename: video.filename, thumbnail: video.thumbnail, createdAt,
+ }));
+ await mutateVideoHistory(history => { history.unshift(...metas); return history; });
success = true;
- result = { ...(launchMetadata ? { appId: launchMetadata.appId } : {}), generationId: jobId, id: jobId, filename, thumbnail, path: `/data/videos/${filename}` };
+ const summary = ({ id, filename, thumbnail }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}` });
+ const [first] = rendered;
+ result = { ...(launchMetadata ? { appId: launchMetadata.appId } : {}), generationId: jobId, ...summary(first), id: jobId,
+ ...(formats ? { videos: rendered.map(video => ({ format: video.format, ...summary(video) })) } : {}) };
}
} catch (error) {
failure = error;
@@ -146,10 +194,7 @@ export async function renderComposition({ jobId, ...input }) {
console.warn('⚠️ Could not remove temporary composition audio');
});
if (!success) {
- for (const path of deliveredPaths) await unlinkGuarded(path).catch(() => {});
- await unlinkGuarded(outputPath).catch(() => {});
- if (proofPath) await unlinkGuarded(proofPath).catch(() => {});
- await unlinkGuarded(join(PATHS.videoThumbnails, `${jobId}.jpg`)).catch(() => {});
+ for (const path of ownedPaths) await unlinkGuarded(path).catch(() => {});
}
active.delete(jobId);
}
diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.js
index b34882e841..960ad71df3 100644
--- a/server/services/htmlComposition/index.test.js
+++ b/server/services/htmlComposition/index.test.js
@@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto';
import { execFileSync, spawn } from 'node:child_process';
import { chromium } from 'playwright-core';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
-import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { findFfmpeg, probeVideoStreamInfo } from '../../lib/ffmpeg.js';
import { PATHS } from '../../lib/fileUtils.js';
import { loadHistory } from '../videoGen/history.js';
import { videoGenEvents } from '../videoGen/events.js';
@@ -146,6 +146,64 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpe
expect(await loadHistory()).not.toContainEqual(expect.objectContaining({ id: retryId }));
}, 60000);
+ it('renders one launch timeline in three declared formats, each reframed by layout, as one take', async () => {
+ // layout() recolors the frame per orientation, so each poster proves the
+ // hook ran at that format's size before its seeks were captured.
+ const html = `<!doctype html><html><body style="margin:0"><script>
+ let fill = 'rgb(0,0,0)';
+ globalThis.portosComposition = { durationSec:15, fps:12, width:1920, height:1080,
+ formats: ['1920x1080', '1080x1920', '1080x1080'],
+ async layout({ width, height }) {
+ if (innerWidth !== width || innerHeight !== height) throw new Error('layout ran before the viewport resized');
+ fill = width === height ? 'rgb(0,0,255)' : width < height ? 'rgb(0,255,0)' : 'rgb(255,0,0)';
+ },
+ async seek(t) { document.body.style.background = fill; },
+ };</script></body></html>`;
+ const runId = randomUUID();
+ const input = await composition(html, `launch-videos/example/${runId}/composition`);
+ await writeFile(join(PATHS.data, input.directory, 'plan.md'), 'A fictional product demonstration.');
+ await writeFile(join(PATHS.data, input.directory, 'caption.txt'), 'Make a clear plan.');
+ await writeFile(join(PATHS.data, input.directory, 'storyboard.json'), JSON.stringify({ posterSec: 5, scenes: [{ durationSec: 15, lines: [] }] }));
+ const launchVideo = { targetDurationSec: 15, appId: 'example', runId };
+ const runRoot = join(PATHS.data, 'launch-videos', 'example', runId);
+
+ // A proof checks one framing at a time: vertical gets phone-width 240px tiles.
+ const proof = await renderComposition({ ...input, launchVideo, proof: { everySec: 5, format: 'vertical' } });
+ expect(proof.proof).toMatchObject({ format: 'vertical', width: 1080, height: 1920, columns: 3, times: [0, 5, 10] });
+ expect((await readFile(join(PATHS.data, proof.proof.file))).readUInt32BE(16)).toBe(3 * 240 + 2 * 4);
+
+ // Requested out of order; rendered and delivered in the canonical order.
+ const jobId = randomUUID();
+ const result = await renderComposition({ ...input, jobId, launchVideo, formats: ['square', 'landscape', 'vertical'] });
+ const expected = [['landscape', 1920, 1080, [255, 0, 0]], ['vertical', 1080, 1920, [0, 255, 0]], ['square', 1080, 1080, [0, 0, 255]]];
+ expect(result.videos.map(video => video.format)).toEqual(expected.map(([format]) => format));
+ expect(result).toMatchObject({ generationId: jobId, id: jobId, appId: 'example', filename: `composition-${jobId}-landscape.mp4` });
+ const history = await loadHistory();
+ for (const [format, width, height, rgb] of expected) {
+ const video = result.videos.find(item => item.format === format);
+ expect(video).toMatchObject({ id: `${jobId}-${format}`, filename: `composition-${jobId}-${format}.mp4`, thumbnail: `${jobId}-${format}.jpg` });
+ // Same timeline: every format carries all 180 frames of the 15s storyboard.
+ expect(await probeVideoStreamInfo(join(PATHS.videos, video.filename))).toMatchObject({ width, height, frameCount: 180 });
+ expect(await readFile(join(runRoot, `video-${format}.mp4`))).toEqual(await readFile(join(PATHS.videos, video.filename)));
+ const pixel = execFileSync(ffmpeg, ['-v', 'error', '-i', join(runRoot, `poster-${format}.jpg`), '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ rgb.forEach((value, channel) => expect(Math.abs(pixel[channel] - value)).toBeLessThan(40));
+ expect(history).toContainEqual(expect.objectContaining({ id: video.id, width, height, durationSec: 15, numFrames: 180,
+ launchVideo: expect.objectContaining({ appId: 'example', runId, caption: 'Make a clear plan.' }) }));
+ }
+ // The storyboard, plan and caption are delivered once for the whole run.
+ expect((await readdir(runRoot)).sort()).toEqual(['caption.txt', 'composition', 'plan.md', 'poster-landscape.jpg', 'poster-square.jpg',
+ 'poster-vertical.jpg', 'proofs', 'storyboard.json', 'video-landscape.mp4', 'video-square.mp4', 'video-vertical.mp4']);
+ expect(history.filter(item => item.launchVideo?.runId === runId)).toHaveLength(3);
+ }, 120000);
+
+ it('refuses a format the composition did not declare, before writing any output', async () => {
+ const input = await composition();
+ await expect(renderComposition({ ...input, formats: ['landscape', 'vertical'] })).rejects.toThrow('portosComposition.formats must include 1920x1080 to render landscape');
+ await expect(renderComposition({ ...input, jobId: randomUUID(), proof: { format: 'square' } })).rejects.toThrow('1080x1080');
+ expect((await readdir(PATHS.videos).catch(() => [])).some(name => name.includes(input.jobId))).toBe(false);
+ expect(await loadHistory()).not.toContainEqual(expect.objectContaining({ id: expect.stringContaining(input.jobId) }));
+ });
+
it('proofs a motion-kit launch composition as a contact sheet, then renders its synthesized cues', async () => {
const html = `<!doctype html><html><body><script src="portos-motion.js"></script><script>
const { spring, beats, renderCues } = globalThis.PortosMotion;
diff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.js
index ca1fdb68fe..3abd72a631 100644
--- a/server/services/mediaAssetIndex/index.js
+++ b/server/services/mediaAssetIndex/index.js
@@ -58,16 +58,20 @@ export async function indexImage({ filename, temp } = {}) {
await upsertAsset(row).catch((err) => console.error(`❌ Media index image upsert failed: ${err.message}`));
}
-// Index a single just-generated video. The 'completed' event carries the job
-// id (generationId); the full metadata is the matching video-history entry.
-async function onVideoCompleted({ generationId } = {}) {
- if (typeof generationId !== 'string' || !generationId) return;
+// Index the just-generated video(s). The 'completed' event carries the job id
+// (generationId); the full metadata is the matching video-history entry. A
+// multi-format HTML composition (#8960) registers one entry per format and
+// lists their ids in `videos`, none of which is the job id itself.
+async function onVideoCompleted({ generationId, videos } = {}) {
+ const ids = Array.isArray(videos) ? videos.map((video) => video?.id) : [generationId];
+ const wanted = new Set(ids.filter((id) => typeof id === 'string' && id));
+ if (!wanted.size) return;
const { loadHistory } = await import('../videoGen/local.js');
const history = await loadHistory().catch(() => []);
- const entry = Array.isArray(history) ? history.find((h) => h.id === generationId) : null;
- if (!entry) return;
- const row = videoToRow(entry);
- await upsertAsset(row).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));
+ const entries = Array.isArray(history) ? history.filter((h) => wanted.has(h.id)) : [];
+ for (const entry of entries) {
+ await upsertAsset(videoToRow(entry)).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));
+ }
}
// Drop one row, non-fatally. The delete paths call this AFTER the file is
diff --git a/server/services/mediaAssetIndex/index.test.js b/server/services/mediaAssetIndex/index.test.js
index a14f67bb6a..ad2945bd66 100644
--- a/server/services/mediaAssetIndex/index.test.js
+++ b/server/services/mediaAssetIndex/index.test.js
@@ -76,6 +76,16 @@ describe('initMediaAssetIndex', () => {
expect(upsertAsset).toHaveBeenCalledWith(expect.objectContaining({
mediaKey: 'video:job-1', kind: 'video', ref: 'job-1',
}));
+ // A multi-format composition (#8960) lists one history entry per format;
+ // none of them is keyed by the job id, so each is indexed from `videos`.
+ upsertAsset.mockClear();
+ loadHistory.mockResolvedValueOnce([
+ { id: 'job-2-landscape', filename: 'a.mp4', createdAt: '2026-01-03T00:00:00.000Z' },
+ { id: 'job-2-vertical', filename: 'b.mp4', createdAt: '2026-01-03T00:00:00.000Z' },
+ ]);
+ videoGenEvents.emit('completed', { generationId: 'job-2', videos: [{ id: 'job-2-landscape' }, { id: 'job-2-vertical' }] });
+ await flush();
+ expect(upsertAsset.mock.calls.map(([row]) => row.mediaKey)).toEqual(['video:job-2-landscape', 'video:job-2-vertical']);
});
});
diff --git a/server/services/taskPromptDefaults/appLaunchVideo.js b/server/services/taskPromptDefaults/appLaunchVideo.js
index 0e832a04fa..35157a90aa 100644
--- a/server/services/taskPromptDefaults/appLaunchVideo.js
+++ b/server/services/taskPromptDefaults/appLaunchVideo.js
@@ -8,6 +8,7 @@ Write only to the supplied output directory (plus the runner's completion sentin
- storyboard.json: {"posterSec":5,"scenes":[{"durationSec":20,"lines":[{"text":"Plan your next great project","wordCount":5,"holdSec":2}]}]}.
Every scene has durationSec; every visible text element has text, its exact whitespace-separated wordCount, and holdSec. Total 15–120 seconds and within two seconds of the chosen target. Each hold is at least max(0.8, 0.3 * wordCount) and fits its scene. Implement those holds faithfully, including transitions. Choose posterSec at the strongest settled beat.
- index.html and local assets: globalThis.portosComposition = {durationSec, fps:24, width, height, async seek(t){...}}. Use dimensions 1920x1080 (landscape), 1080x1920 (vertical), or 1080x1080 (square). Seek deterministically from t; await fonts and any asynchronous work. No wall-clock animations, external URLs, popups, workers or browser storage. Keep HTML/CSS/JS/SVG/JSON/Markdown/text UTF-8. No raster screenshots or footage.
+When the options list formats (several aspect ratios) instead of one format, make ONE film for all of them from a single timeline: set width and height to the first listed format, declare every listed size in portosComposition.formats (for example ["1920x1080","1080x1920","1080x1080"]), and implement async portosComposition.layout({width, height}), which the renderer calls before seeking in each format. Recompose type, UI and the key flow for each frame (reflow, rescale and reposition; never crop or letterbox one layout), keep every scene, line and hold on the same timeline in every format, and keep seek(t) pure given the current layout. The render JSON already carries formats; the renderer renders each format in turn and delivers video-<format>.mp4 and poster-<format>.jpg. When critiquing, proof each format by adding its name as "format" inside the Proof JSON proof object, and check readability in the narrowest frame.
Direct it like a motion designer, not a slideshow. Banned defaults: a centered title on a gradient, everything fading in, corner labels, frame borders, crop marks or HUD chrome, glow on UI chrome, generic particle bursts and dead beats. Hook within the first two seconds and make something new happen every two to four seconds. Use one display face, one UI face and one accent color from the app's palette. Motion has mass: drive position, scale, radius and width with closed-form springs, not fixed easing curves, with a tiny overshoot on UI and none on type. All motion stays a pure function of t: seeded pseudo-randomness only, never Math.random or timers.
The server pre-installed the PortOS motion kit at composition/portos-motion.js. Load it with <script src="portos-motion.js"></script> and use globalThis.PortosMotion: spring(t, stiffness, damping) and SPRINGS presets (snappy, default, heavy, playful); track(t, [[time, value], ...]) for any value with several targets (one spring per change, never restart one); indicator() for selection bars that stretch while they travel; swapAlpha() so content inside a morphing container enters after the morph starts and leaves before the next; rng(seed) for seeded noise; beats(bpm) for a beat grid; and renderCues, mixCues and toPcm for synthesized UI sound (click, tick, pop, thump, whoosh, riser). It is ordinary composition source: edit it or delete it if unused. If composition/beats.json exists, it holds a real measured analysis of the chosen library track: {"bpm","beats","downbeats","hits"} (seconds; bpm/beats/downbeats are null/empty when no confident tempo was found). Cut on its beats/downbeats/hits timestamp arrays directly, not a synthetic beats(bpm) grid (which starts at t=0 and will not match this track's real phase): place state changes at entries in beats, big moments at entries in downbeats, and UI sounds at entries in hits. Fall back to beats(bpm) with its bpm only when beats.json is absent or its arrays are empty.
motionStyle picks the film's grammar. "walkthrough": a clear, paced product walkthrough of the recreated key flow, a cursor driving real actions, springs on every change. "showreel": a designer's showreel built around this product, not a slideshow of recreated screens. Cut on a steady beat (a new beat every one to two seconds, landing on bar boundaries when music is present) and give each beat a distinct technique: bold color-field swaps drawn from the app's palette, oversized kinetic typography (scale, mask and slide reveals; repeated-word patterns), spring contrasts (snappy against heavy against playful), generative geometry computed from t (tiling patterns, radial forms, wireframes), shape morphs, and a logo/name lockup endcard. Keep the recreated key flow as one or two punchy beats so the evidence-backed claim still lands. "ui-morph": one shape, never cut. A single container morphs size, radius and fill from state to state along this app's real flow (for example button, input being typed, loader, success check, dashboard card, chart drawing itself, command palette, toast, logo), its content swaps behind a short blur with swapAlpha, a cursor drives each change with real clicks, a state change lands on every beat at 120 BPM, and the last frame equals the first, cursor position included, so it loops. Write the state list on the beat grid in plan.md before any code. In every style, each word shown, including repeated kinetic words, is a storyboard line whose hold meets the reading-time gate. For showreel and ui-morph, set motionBlur:4 on globalThis.portosComposition so the fast cuts and morphs render with blended motion blur instead of strobing.
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 2668ec17da..9c2c8c279f 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -2,7 +2,7 @@
"DEFAULT_TASK_PROMPTS": {
"accessibility": "46f628a44a919bb788de8761e86ca0e1",
"api-contract": "d52e00ec53eb5618df1a769efccc08f3",
- "app-launch-video": "d9ce59c884841cdfcab7139d05778e74",
+ "app-launch-video": "271c1e8bc301ba02b4a2207e0abf8573",
"better-cognitive-load": "a1fe22f6ef936131456c55a6b0623204",
"better-complexity": "c99f67b43ff54a1c8cf0176c721d9c06",
"better-dependency-freedom": "8a79c8be829f926bbc7720ee29818d53",
@@ -64,7 +64,7 @@
"PROMPT_VERSIONS": {
"accessibility": 5,
"api-contract": 2,
- "app-launch-video": 7,
+ "app-launch-video": 8,
"better-cognitive-load": 1,
"better-complexity": 2,
"better-dependency-freedom": 1,
@@ -136,7 +136,8 @@
"71962a1f6f902d93f2c8840e3281301b",
"f1aee8c3de778663a5ba44a4f3486ce5",
"c5f125ac04d41921030f7cd36a3ff3ee",
- "e355d37fb682c1f6c2ad4c031a7988a7"
+ "e355d37fb682c1f6c2ad4c031a7988a7",
+ "d9ce59c884841cdfcab7139d05778e74"
],
"better-complexity": [
"c92b99080d0453d70bb26a412fb48ce9"
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 9e4775efac..060f9d8734 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -7,7 +7,7 @@
// Prompt versions — bump when a default prompt changes so existing instances auto-upgrade.
// Only non-customized prompts (promptCustomized !== true) are upgraded.
export const PROMPT_VERSIONS = {
- 'app-launch-video': 7, // v7: measured composition/beats.json (bpm/beats/downbeats/hits from a real analysis of the chosen library track, #8958) is named next to the motion kit — place state changes on beats, big moments on downbeats, UI sounds on hits, instead of guessing a tempo. v6: showreel and ui-morph runs set motionBlur:4 on portosComposition so fast cuts and morphs render with blended motion blur (#8959)
+ 'app-launch-video': 8, // v8: options.formats renders one timeline in several aspect ratios — declare portosComposition.formats, implement layout({width,height}) to recompose per frame, proof each format (#8960). v7: measured composition/beats.json (bpm/beats/downbeats/hits from a real analysis of the chosen library track, #8958) is named next to the motion kit — place state changes on beats, big moments on downbeats, UI sounds on hits, instead of guessing a tempo. v6: showreel and ui-morph runs set motionBlur:4 on portosComposition so fast cuts and morphs render with blended motion blur (#8959)
'model-comparison-refresh': 4, // v4: installed inventory, sourced composite estimates and authenticated import
// Current claim-flow bumps retire the Copilot fallback, drive local reviewers
// fail closed, verify the remote merge state, and clean up without force-delete.