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([issue-3695]): per-chunk prompt beats for chained video renders

[._.]/ Adam Eivy63dd42885b1e
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index e1828668f3..ea6aa00858 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -1,6 +1,7 @@
/**
- * "Advanced" disclosure for the local-backend sampler knobs — frames, chunks,
- * fps, seed, steps, CFG scale, image strength, tiling and the audio flags.
+ * "Advanced" disclosure for the local-backend sampler knobs — frames, chunks
+ * (plus their optional per-chunk prompt beats), fps, seed, steps, CFG scale,
+ * image strength, tiling and the audio flags.
*
* Closed by default so the Generate button sits above the fold on /media/video
* the way it already does on the sibling /media/image tab (issue #3279), which
@@ -31,6 +32,7 @@ export default function AdvancedParamsPanel({
currentModel,
numFrames, onNumFramesChange,
chunks, onChunksChange, keyframesActive,
+ chunkPrompts = [], onChunkPromptChange, chainingActive = false,
fps, onFpsChange,
seed, onSeedChange, onRandomSeed,
steps, onStepsChange,
@@ -109,6 +111,41 @@ export default function AdvancedParamsPanel({
</div>
)}
+ {/* Per-chunk prompt beats (#3695). Only shown when the request really
+ chains — the parent derives `chainingActive` from the same
+ predicate that decides whether `chunks` is submitted at all, so
+ this editor can never appear for a mode the server pins to one
+ chunk. One row per LIVE chunk; the parent keeps text for chunks
+ beyond the current count, so lowering then raising the count
+ restores what was typed. */}
+ {chainingActive && (
+ <div className="col-span-2 sm:col-span-3">
+ <p className="block text-xs font-medium text-gray-400 mb-1">
+ Per-chunk beats <span className="font-normal text-gray-500">(optional — blank uses the main prompt)</span>
+ </p>
+ <div className="space-y-1.5">
+ {Array.from({ length: chunks }, (_, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <label htmlFor={`chunk-prompt-${i}`} className="text-[11px] text-gray-500 w-12 shrink-0">
+ Chunk {i + 1}
+ </label>
+ <input
+ id={`chunk-prompt-${i}`}
+ type="text"
+ value={chunkPrompts[i] || ''}
+ onChange={(e) => onChunkPromptChange(i, e.target.value)}
+ placeholder="Same as main prompt"
+ className={inputCls}
+ />
+ </div>
+ ))}
+ </div>
+ <p className="text-[10px] text-gray-500 leading-snug mt-1">
+ Each chunk still continues from the previous chunk&apos;s last frame — beats steer what happens next rather than starting a new shot.
+ </p>
+ </div>
+ )}
+
<FormField label="FPS" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<select
value={fps}
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
index 1498d8a10a..9c8b1d4d36 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
@@ -7,6 +7,7 @@ const baseProps = {
currentModel: { steps: 30, guidance: 3.0 },
numFrames: 121, onNumFramesChange: vi.fn(),
chunks: 1, onChunksChange: vi.fn(), keyframesActive: false,
+ chunkPrompts: [], onChunkPromptChange: vi.fn(), chainingActive: false,
fps: 24, onFpsChange: vi.fn(),
seed: '', onSeedChange: vi.fn(), onRandomSeed: vi.fn(),
steps: '', onStepsChange: vi.fn(),
@@ -140,4 +141,38 @@ describe('AdvancedParamsPanel', () => {
fireEvent.click(toggle());
expect(screen.getByLabelText(/No music/).disabled).toBe(true);
});
+
+ describe('per-chunk prompt beats (#3695)', () => {
+ it('hides the beat editor when the request does not chain', () => {
+ renderPanel({ chunks: 4, chainingActive: false });
+ fireEvent.click(toggle());
+ expect(screen.queryByLabelText('Chunk 1')).toBeNull();
+ });
+
+ it('renders one beat row per live chunk, prefilled from the parent', () => {
+ renderPanel({ chunks: 3, chainingActive: true, chunkPrompts: ['first', '', 'third'] });
+ fireEvent.click(toggle());
+ expect(screen.getByLabelText('Chunk 1').value).toBe('first');
+ expect(screen.getByLabelText('Chunk 2').value).toBe('');
+ expect(screen.getByLabelText('Chunk 3').value).toBe('third');
+ expect(screen.queryByLabelText('Chunk 4')).toBeNull();
+ });
+
+ it('shows only the live chunks even when the parent holds text for more', () => {
+ // The parent never truncates its array (so raising the count restores the
+ // text) — the editor is what scopes the view to the current chunk count.
+ renderPanel({ chunks: 2, chainingActive: true, chunkPrompts: ['a', 'b', 'c'] });
+ fireEvent.click(toggle());
+ expect(screen.getByLabelText('Chunk 2').value).toBe('b');
+ expect(screen.queryByLabelText('Chunk 3')).toBeNull();
+ });
+
+ it('reports edits by chunk index', () => {
+ const onChunkPromptChange = vi.fn();
+ renderPanel({ chunks: 2, chainingActive: true, onChunkPromptChange });
+ fireEvent.click(toggle());
+ fireEvent.change(screen.getByLabelText('Chunk 2'), { target: { value: 'the storm breaks' } });
+ expect(onChunkPromptChange).toHaveBeenCalledWith(1, 'the storm breaks');
+ });
+ });
});
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 3952216a62..3b554560ef 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -65,6 +65,13 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
const [numFrames, setNumFrames] = useState(121);
const [fps, setFps] = useState(24);
const [chunks, setChunks] = useState(1);
+ // Per-chunk prompt beats (#3695) — one editable string per chained chunk, so
+ // a longer shot can progress instead of replaying the same prompt at each
+ // seam. Kept as a plain sparse-by-blank array (index i steers chunk i); a
+ // blank entry means "use the main prompt for this chunk". Sized lazily by
+ // `chunkPromptAt`/`setChunkPromptAt` rather than eagerly resized on every
+ // chunk change, so lowering then raising the count doesn't lose typed text.
+ const [chunkPrompts, setChunkPrompts] = useState([]);
const [steps, setSteps] = useState('');
const [guidanceScale, setGuidanceScale] = useState('');
const [imageStrength, setImageStrength] = useState('');
@@ -848,6 +855,11 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
if (p.duration) setGrokDuration(p.duration);
} else if (p.mode) setMode(p.mode);
if (p.chunks && p.chunks > 1) setChunks(p.chunks);
+ // Per-chunk beats (#3695). The server normalizes an absent beat to null;
+ // the editor's shape is '' for the same thing, so map back on restore.
+ if (Array.isArray(p.chunkPrompts) && p.chunkPrompts.length) {
+ setChunkPrompts(p.chunkPrompts.map((cp) => (typeof cp === 'string' ? cp : '')));
+ }
// Multi-keyframe FFLF: the route maps the stored { path, index } back to
// { file, index } (gallery basename) for us, so restore the picker
// state directly. >= 2 mirrors the server's accept floor; flipping
@@ -919,6 +931,31 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
);
const modelSupportsChaining = currentModel?.runtime !== 'wan22'
|| currentModel?.supportedModes?.includes('image');
+ // The single predicate for "this request really chains" — keyframes, IC
+ // references and a2v each anchor a SINGLE clip, so the route pins them to one
+ // chunk (KEYFRAMES_CHUNKS_CONFLICT / IC_LORA_CHUNKS_CONFLICT). Derived once so
+ // the submitted `chunks`, the submitted `chunkPrompts`, and the per-chunk beat
+ // editor can never disagree about whether chaining is active.
+ const chainingActive = mode !== 'a2v' && !keyframesActive && !icModeActive
+ && modelSupportsChaining && chunks > 1;
+
+ // Edit one beat. The backing array is only ever GROWN (never truncated on a
+ // chunk-count change) so lowering the count and raising it again restores the
+ // text the user already typed; submit and the editor slice to the live count.
+ const setChunkPromptAt = (index, value) => {
+ setChunkPrompts((prev) => {
+ const next = prev.slice();
+ while (next.length <= index) next.push('');
+ next[index] = value;
+ return next;
+ });
+ };
+ // What actually rides to the server: exactly `chunks` entries, blanks kept in
+ // place as explicit "use the main prompt" markers, and the whole list dropped
+ // when chaining is off or every beat is blank.
+ const activeChunkPrompts = chainingActive
+ ? Array.from({ length: chunks }, (_, i) => chunkPrompts[i] || '')
+ : [];
// Snapshot the current form into a generate-payload. Used both by the
// inline Generate button and by enqueue, so the two paths stay in lockstep.
@@ -1016,8 +1053,14 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
// Keyframes and IC references each anchor a single clip — the route
// rejects chunks > 1 with KEYFRAMES_CHUNKS_CONFLICT /
// IC_LORA_CHUNKS_CONFLICT, so suppress chunking for both.
- chunks: mode !== 'a2v' && !keyframesActive && !icModeActive
- && modelSupportsChaining && chunks > 1 ? chunks : '',
+ chunks: chainingActive ? chunks : '',
+ // Per-chunk beats (#3695) go as a JSON string, like `keyframes` above:
+ // buildFormData appends arrays as repeated keys, which would collapse a
+ // one-entry list to a bare string server-side and — worse — lose the
+ // POSITION of a blank middle beat. Omitted entirely when chaining is off
+ // or every beat is blank, so a non-chained submit sends nothing.
+ chunkPrompts: activeChunkPrompts.some((p) => p.trim())
+ ? JSON.stringify(activeChunkPrompts) : '',
};
};
@@ -1039,6 +1082,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
numFrames, setNumFrames,
fps, setFps,
chunks, setChunks,
+ chunkPrompts, setChunkPromptAt, chainingActive,
steps, setSteps,
guidanceScale, setGuidanceScale,
imageStrength, setImageStrength,
diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsx
index 872f4e8972..fce81a55fc 100644
--- a/client/src/hooks/useVideoGenForm.test.jsx
+++ b/client/src/hooks/useVideoGenForm.test.jsx
@@ -191,6 +191,77 @@ describe('useVideoGenForm', () => {
expect(result.current.buildGeneratePayload().chunks).toBe('');
});
+ describe('per-chunk prompt beats (#3695)', () => {
+ const chained = async (count = 3) => {
+ const { result } = render();
+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));
+ act(() => { result.current.setPrompt('a long shot'); result.current.setChunks(count); });
+ return result;
+ };
+
+ it('serializes the beats as JSON, padded to the live chunk count', async () => {
+ const result = await chained(3);
+ act(() => result.current.setChunkPromptAt(0, 'she opens the door'));
+ act(() => result.current.setChunkPromptAt(2, 'the storm breaks'));
+
+ expect(result.current.chainingActive).toBe(true);
+ // A blank middle beat keeps its POSITION — that's what tells the server
+ // chunk 2 falls back to the main prompt rather than shifting beat 3 up.
+ expect(JSON.parse(result.current.buildGeneratePayload().chunkPrompts))
+ .toEqual(['she opens the door', '', 'the storm breaks']);
+ });
+
+ it('keeps text for chunks beyond the current count so lowering then raising restores it', async () => {
+ const result = await chained(3);
+ act(() => { result.current.setChunkPromptAt(0, 'first'); result.current.setChunkPromptAt(2, 'third'); });
+
+ act(() => result.current.setChunks(2));
+ expect(JSON.parse(result.current.buildGeneratePayload().chunkPrompts)).toEqual(['first', '']);
+
+ act(() => result.current.setChunks(3));
+ expect(JSON.parse(result.current.buildGeneratePayload().chunkPrompts))
+ .toEqual(['first', '', 'third']);
+ });
+
+ it('omits the beats when every one is blank', async () => {
+ const result = await chained(2);
+ act(() => result.current.setChunkPromptAt(0, ' '));
+ expect(result.current.buildGeneratePayload().chunkPrompts).toBe('');
+ });
+
+ it('omits the beats when the request does not chain', async () => {
+ const result = await chained(1);
+ act(() => result.current.setChunkPromptAt(0, 'a stale beat'));
+ expect(result.current.chainingActive).toBe(false);
+ expect(result.current.buildGeneratePayload().chunkPrompts).toBe('');
+ });
+
+ it('omits the beats for a mode the server pins to one chunk', async () => {
+ const result = await chained(3);
+ act(() => result.current.handleModelChange(LTX2.id));
+ act(() => result.current.handleModeChange('fflf'));
+ act(() => result.current.toggleKeyframesMode());
+ act(() => result.current.setChunkPromptAt(0, 'a beat'));
+
+ expect(result.current.keyframesActive).toBe(true);
+ expect(result.current.chainingActive).toBe(false);
+ expect(result.current.buildGeneratePayload().chunkPrompts).toBe('');
+ });
+
+ it('restores beats from a resumed job, mapping the server null back to blank', async () => {
+ const { result } = render();
+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));
+ act(() => result.current.applyResumedParams({
+ prompt: 'a long shot',
+ chunks: 3,
+ chunkPrompts: ['she opens the door', null, 'the storm breaks'],
+ }));
+ expect(result.current.chunkPrompts).toEqual(['she opens the door', '', 'the storm breaks']);
+ expect(JSON.parse(result.current.buildGeneratePayload().chunkPrompts))
+ .toEqual(['she opens the door', '', 'the storm breaks']);
+ });
+ });
+
it('serializes keyframes as JSON and suppresses chunking while they are active', async () => {
const { result } = render();
act(() => result.current.handleModelChange(LTX2.id));
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 0a4575e696..9f9b4c1d9f 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -144,6 +144,7 @@ export default function VideoGen() {
selectedLoras, setSelectedLoras,
width, height, handleResolutionChange,
numFrames, setNumFrames, fps, setFps, chunks, setChunks,
+ chunkPrompts, setChunkPromptAt, chainingActive,
steps, setSteps, guidanceScale, setGuidanceScale, imageStrength, setImageStrength,
seed, setSeed, handleRandomSeed, tiling, setTiling,
disableAudio, setDisableAudio, noMusic, setNoMusic,
@@ -1063,6 +1064,7 @@ export default function VideoGen() {
currentModel={currentModel}
numFrames={numFrames} onNumFramesChange={setNumFrames}
chunks={chunks} onChunksChange={setChunks} keyframesActive={keyframesActive}
+ chunkPrompts={chunkPrompts} onChunkPromptChange={setChunkPromptAt} chainingActive={chainingActive}
fps={fps} onFpsChange={setFps}
seed={seed} onSeedChange={setSeed} onRandomSeed={handleRandomSeed}
steps={steps} onStepsChange={setSteps}
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index e4b1b51d77..fc3dcbb3a4 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -124,6 +124,11 @@ const optionalInt = (min, max, label) => z.preprocess(
// still enforced against the mode's own spec (assertIcReferenceCount).
const MAX_IC_REFERENCES = Math.max(...listIcLoraWeights().map((s) => s.maxReferences));
+// Chain ceiling — 8 × ~5min ≈ 40min on an M3 Max keeps the worst-case wall time
+// bounded. Shared by `chunks` and the per-chunk prompt list so the two can never
+// drift apart.
+export const MAX_VIDEO_CHUNKS = 8;
+
// Render controls that only the local runtimes understand. Keep their schemas
// together so Grok eligibility and request validation cannot drift when a new
// local-only knob is added.
@@ -173,7 +178,27 @@ const generateBodySchema = z.object({
// Chain N renders end-to-end: each chunk's last frame becomes the next
// chunk's start frame, then ffmpeg concats them into one clip. 1..8 to
// keep the worst-case wall time bounded (8 × ~5min ≈ 40min on M3 Max).
- chunks: optionalInt(1, 8, 'chunks'),
+ chunks: optionalInt(1, MAX_VIDEO_CHUNKS, 'chunks'),
+ // Optional per-chunk prompt beats for a chained render (#3695). Entry i
+ // steers chunk i, so a longer shot can progress through an action instead of
+ // replaying the same prompt at every seam. A blank entry is an explicit
+ // fallback to the main `prompt` — that's why empty strings are accepted
+ // rather than filtered here; prepareVideoGenParams normalizes them to null.
+ // Rides as a JSON-encoded array (like `keyframes`) so blank middle entries
+ // keep their position and a one-element list can't collapse to the bare
+ // string multipart sends for a single repeated key — a bare string is still
+ // accepted as a one-entry list for hand-rolled/JSON clients.
+ chunkPrompts: z.preprocess(
+ (v) => {
+ if (v == null || v === '') return undefined;
+ if (typeof v === 'string') {
+ if (v.trim().startsWith('[')) { try { return JSON.parse(v); } catch { return [v]; } }
+ return [v];
+ }
+ return v;
+ },
+ z.array(z.string().max(8000)).max(MAX_VIDEO_CHUNKS).optional(),
+ ),
// History id of a prior render to extend natively (ltx2 runtime only —
// routes through ExtendPipeline.extend_from_video which conditions on
// the entire source video's latent rather than a single last frame).
@@ -872,7 +897,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
pythonPath, effectiveModelId, mode,
sourceImagePath, lastImagePath, audioFilePath, icReferencePaths,
resolvedKeyframes, extendFromVideoPath,
- uploadedTempPath, uploadedTempPaths, loras, effectiveChunks,
+ uploadedTempPath, uploadedTempPaths, loras, effectiveChunks, effectiveChunkPrompts,
} = prepared;
// Enqueue rather than spawn synchronously — the mediaJobQueue worker will
@@ -902,6 +927,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
mode,
imageStrength: body.imageStrength,
chunks: effectiveChunks,
+ // Undefined when the request doesn't chain (or every beat was blank) — the
+ // key is simply absent from job.params then, so a resumed form restores no
+ // stale beats. See prepareVideoGenParams for the normalization.
+ ...(effectiveChunkPrompts ? { chunkPrompts: effectiveChunkPrompts } : {}),
loras,
icReferencePaths,
icStrength: body.icStrength,
@@ -936,7 +965,7 @@ const ACTIVE_JOB_PARAM_FIELDS = [
'prompt', 'negativePrompt', 'modelId',
'width', 'height', 'numFrames', 'fps',
'steps', 'guidanceScale', 'seed',
- 'tiling', 'disableAudio', 'mode', 'chunks', 'imageStrength',
+ 'tiling', 'disableAudio', 'mode', 'chunks', 'chunkPrompts', 'imageStrength',
'audioStartSec',
// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the
// 'grok' discriminator for them) and the clip duration — both plain
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 29da6c96cb..8cf5d47215 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -936,6 +936,54 @@ describe('videoGen routes', () => {
expect(r.body.error).toMatch(/chunks/i);
});
+ it('forwards per-chunk prompt beats, keeping a blank entry as a fallback marker', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a long shot',
+ chunks: 3,
+ chunkPrompts: ['she opens the door', '', 'the storm breaks'],
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
+ chunks: 3,
+ chunkPrompts: ['she opens the door', null, 'the storm breaks'],
+ }),
+ }));
+ });
+
+ it('accepts a JSON-encoded beat list (the multipart submit shape)', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a long shot',
+ chunks: 2,
+ chunkPrompts: JSON.stringify(['first beat', 'second beat']),
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({ chunkPrompts: ['first beat', 'second beat'] }),
+ }));
+ });
+
+ it('omits beats entirely from a single-chunk render', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a single render',
+ chunkPrompts: ['a stale beat'],
+ });
+ expect(r.status).toBe(200);
+ const { params } = mediaJobQueue.enqueueJob.mock.calls.at(-1)[0];
+ expect(params.chunks).toBe(1);
+ expect('chunkPrompts' in params).toBe(false);
+ });
+
+ it('rejects a beat list longer than the chunk cap', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'too many beats',
+ chunks: 2,
+ chunkPrompts: Array.from({ length: 9 }, (_, i) => `beat ${i}`),
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/chunkPrompts/i);
+ });
+
it('forwards extendFromVideoId by resolving to a real disk path under data/videos/', async () => {
const id = '11111111-1111-4111-8111-111111111111';
const videoSvc = await import('../services/videoGen/local.js');
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 28236ad20d..4639a56933 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -1471,7 +1471,12 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// child is SIGTERM'd by cancel() and surfaces a 'failed' event we translate
// into a chain-level failure. Already-completed inner chunks are hidden but
// not deleted (the partial output is still on disk if the user wants it).
-export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest }) {
+//
+// `chunkPrompts` (#3695) optionally steers each chunk individually: entry i is
+// chunk i's prompt, and a null/blank/missing entry falls back to the main
+// `prompt`. It is destructured out of `rest` on purpose so the per-chunk
+// generateVideo() calls below never receive the whole list.
+export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJobId, ...rest }) {
const totalChunks = Number(chunks) || 1;
if (totalChunks === 1) {
return generateVideo({ jobId: outerJobId, ...rest });
@@ -1556,8 +1561,16 @@ export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest
: undefined;
const isExtendChain = firstMode === 'extend' && i > 0;
+ // Per-chunk beat (#3695). `chunkPrompts` is already normalized (blank →
+ // null) by prepareVideoGenParams, but re-guard on emptiness here too so a
+ // direct service caller can't hand a chunk an empty prompt — an absent beat
+ // must always resolve to the main prompt, never to ''.
+ const beat = Array.isArray(chunkPrompts) ? chunkPrompts[i] : null;
+ const chunkPrompt = (typeof beat === 'string' && beat.trim() !== '') ? beat : rest.prompt;
+
generateVideo({
...rest,
+ prompt: chunkPrompt,
seed: chunkSeed,
jobId: innerJobId,
// extend chain: subsequent chunks condition on the prior clip's full
@@ -1643,6 +1656,11 @@ export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest
filenamePrefix: 'chained',
historyKey: 'chainedFrom',
promptOverride: rest.prompt || null,
+ // Persist the beats alongside the stitched clip so the gallery entry (and
+ // a Remix off it) carries the same source of truth the chain rendered
+ // from — the individual chunk entries only ever hold their own resolved
+ // prompt, which loses which of them were explicit beats vs. fallbacks.
+ ...(Array.isArray(chunkPrompts) && chunkPrompts.some((p) => p) ? { extraMeta: { chunkPrompts } } : {}),
}).catch((err) => ({ error: err.message }));
if (stitched?.error) {
await setHistoryItemsHidden(chunkIds, true);
@@ -1817,14 +1835,20 @@ export async function sampleEvaluationFrames(jobId, count = 5) {
// lets users stitch from a single model so this holds in practice.
//
// `opts` lets the chained-render code reuse the same ffmpeg path with a
-// different identity (id, filename prefix, history-link key, prompt) without
-// duplicating the validation + concat-manifest plumbing.
+// different identity (id, filename prefix, history-link key, prompt) and extra
+// history metadata without duplicating the validation + concat-manifest
+// plumbing.
export async function stitchVideos(videoIds, opts = {}) {
const {
id = randomUUID(),
filenamePrefix = 'stitched',
historyKey = 'stitchedFrom',
promptOverride = null,
+ // Extra fields merged into the stitched history entry (chained renders use
+ // it for per-chunk prompt beats). Spread FIRST below so the derived fields
+ // win — a caller can annotate the entry but never overwrite the identity
+ // fields (id/filename/thumbnail/…) this function is responsible for.
+ extraMeta = null,
} = opts;
if (!Array.isArray(videoIds) || videoIds.length < 2) {
throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });
@@ -1874,6 +1898,7 @@ export async function stitchVideos(videoIds, opts = {}) {
const thumb = await generateThumbnail(outPath, id);
const stitchedMeta = {
+ ...(extraMeta && typeof extraMeta === 'object' ? extraMeta : {}),
id,
prompt: promptOverride != null
? promptOverride
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 3de49620da..d537dfd809 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -420,6 +420,116 @@ describe('generateChainedVideo — extend chain arg routing', () => {
});
});
+describe('generateChainedVideo — per-chunk prompt beats (#3695)', () => {
+ /**
+ * Drive a text chain of `totalChunks` and return the `--prompt` value each
+ * inner render was spawned with, in chunk order. Prompts are read off the
+ * spawn args rather than the 'started' event because that event carries
+ * sampler metadata, not the prompt — the spawn args are what the runner
+ * actually renders.
+ */
+ async function runChainAndCapturePrompts(chainParams, totalChunks) {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ // Between chunks the chain extracts the prior chunk's last frame, which
+ // looks the chunk up in history — feed it the ids as they start so the
+ // chain can advance past chunk 0.
+ const { readJSONFile } = await import('../../lib/fileUtils.js');
+ const innerJobIds = [];
+ vi.mocked(readJSONFile).mockImplementation(async () =>
+ innerJobIds.map((id) => ({ id, filename: `${id}.mp4` })),
+ );
+ videoGenEvents.on('started', (e) => innerJobIds.push(e.generationId));
+
+ generateChainedVideo({
+ chunks: totalChunks,
+ jobId: randomUUID(),
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'main prompt',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ mode: 'image',
+ sourceImagePath: '/mock/source.png',
+ extendFromVideoPath: null,
+ lastImagePath: null,
+ ...chainParams,
+ });
+
+ for (let i = 0; i < totalChunks; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ const check = () => {
+ if (innerJobIds.length > i) { resolve(); return; }
+ setTimeout(check, 10);
+ };
+ check();
+ });
+ const id = innerJobIds[i];
+ videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });
+ }
+ await new Promise((r) => setTimeout(r, 100));
+ videoGenEvents.removeAllListeners('started');
+
+ return spawnMock.mock.calls
+ .map(([, args]) => (Array.isArray(args) && args.includes('--prompt')
+ ? args[args.indexOf('--prompt') + 1] : null))
+ .filter((p) => p != null);
+ }
+
+ it('renders each chunk with its own beat', async () => {
+ const prompts = await runChainAndCapturePrompts(
+ { chunkPrompts: ['she opens the door', 'she steps into the rain'] },
+ 2,
+ );
+ expect(prompts).toEqual(['she opens the door', 'she steps into the rain']);
+ });
+
+ it('falls back to the main prompt for a blank beat', async () => {
+ // A blank middle entry is the explicit "no beat here" marker — it must
+ // render the MAIN prompt, never an empty prompt.
+ const prompts = await runChainAndCapturePrompts(
+ { chunkPrompts: ['she opens the door', '', ' '] },
+ 3,
+ );
+ expect(prompts).toEqual(['she opens the door', 'main prompt', 'main prompt']);
+ });
+
+ it('falls back to the main prompt for a null beat and for indices past the list', async () => {
+ const prompts = await runChainAndCapturePrompts(
+ { chunkPrompts: [null, 'the storm breaks'] },
+ 3,
+ );
+ expect(prompts).toEqual(['main prompt', 'the storm breaks', 'main prompt']);
+ });
+
+ it('renders the main prompt for every chunk when no beats are supplied', async () => {
+ const prompts = await runChainAndCapturePrompts({}, 2);
+ expect(prompts).toEqual(['main prompt', 'main prompt']);
+ });
+
+ it('persists the beat list on the stitched history entry', async () => {
+ // The individual chunk entries only record their own RESOLVED prompt, which
+ // loses which chunks carried an explicit beat — so the visible stitched
+ // entry has to carry the list for a Remix to round-trip it.
+ const { atomicWrite } = await import('../../lib/fileUtils.js');
+ await runChainAndCapturePrompts({ chunkPrompts: ['a beat', '', 'a later beat'] }, 3);
+
+ const stitched = vi.mocked(atomicWrite).mock.calls
+ .flatMap(([, payload]) => (Array.isArray(payload) ? payload : []))
+ .find((item) => Array.isArray(item?.chainedFrom));
+ expect(stitched).toBeTruthy();
+ expect(stitched.chunkPrompts).toEqual(['a beat', '', 'a later beat']);
+ // The stitched entry keeps its own derived identity — extraMeta annotates,
+ // it never overwrites.
+ expect(stitched.filename).toMatch(/^chained-/);
+ });
+});
+
describe('generateVideo — ltx2 FFLF image resizing', () => {
it('resizes both start and end frames before passing them to the ltx2 helper', async () => {
const { execFile } = await import('child_process');
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 0d649084c2..88282b29f0 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -99,7 +99,8 @@ export const withStagedRollback = async (cleanupStaged, fn) => {
* `{ backend, grok, sourceImagePath, uploadedTempPath, cleanupStaged }`.
* On the local lane, additionally `{ pythonPath, effectiveModelId, mode,
* lastImagePath, audioFilePath, icReferencePaths, resolvedKeyframes,
- * extendFromVideoPath, uploadedTempPaths, loras, effectiveChunks }`.
+ * extendFromVideoPath, uploadedTempPaths, loras, effectiveChunks,
+ * effectiveChunkPrompts }`.
* `cleanupStaged` is the caller's rollback hook for anything that can still
* throw after this resolves (today: `enqueueJob`) — pass it to
* `withStagedRollback`.
@@ -745,6 +746,27 @@ async function resolvePreparedParams({
// also hard-rejects an explicit chunks>1 above; this covers the default.
const effectiveChunks = (body.mode === 'a2v' || icSpec) ? 1 : (body.chunks ?? 1);
+ // Per-chunk prompt beats (#3695) — only meaningful once the RESOLVED request
+ // really chains, so a single-chunk render (or an a2v/IC one pinned to 1 above)
+ // drops the list entirely rather than persisting a stale array into job params
+ // that a resume would replay into the form.
+ //
+ // Sizing is forgiving in both directions: a stale overlong list (the user
+ // typed beats, then lowered the chunk count) is truncated to the resolved
+ // count, and a short list is left short — generateChainedVideo falls back to
+ // the main prompt for any index the list doesn't cover. Blank entries become
+ // an explicit null (absent beat → main prompt) rather than an empty string the
+ // runner would render as an empty prompt. An all-blank list collapses to
+ // undefined so "the user cleared every beat" and "no beats were sent" persist
+ // identically instead of storing a useless array of nulls.
+ const normalizedChunkPrompts = effectiveChunks > 1 && Array.isArray(body.chunkPrompts)
+ ? body.chunkPrompts.slice(0, effectiveChunks)
+ .map((p) => (typeof p === 'string' && p.trim() !== '' ? p.trim() : null))
+ : undefined;
+ const effectiveChunkPrompts = normalizedChunkPrompts?.some((p) => p != null)
+ ? normalizedChunkPrompts
+ : undefined;
+
return {
backend,
pythonPath,
@@ -760,6 +782,7 @@ async function resolvePreparedParams({
uploadedTempPaths: extraUploadedTempPaths,
loras,
effectiveChunks,
+ effectiveChunkPrompts,
cleanupStaged,
};
}
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index 6decec3b87..884f65ef16 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -157,6 +157,55 @@ describe('prepareVideoGenParams', () => {
});
});
+ describe('per-chunk prompt beats (#3695)', () => {
+ it('normalizes beats and keeps a blank entry in position as a fallback marker', async () => {
+ const prepared = await prepare({ mode: 'image', chunks: 3, chunkPrompts: [' opens the door ', '', 'the storm breaks'] });
+ expect(prepared.effectiveChunkPrompts).toEqual(['opens the door', null, 'the storm breaks']);
+ });
+
+ it('truncates a stale overlong list to the resolved chunk count', async () => {
+ // The user typed four beats, then lowered Chunks to 2 — the extra beats
+ // must not ride along and desync the list from the chain.
+ const prepared = await prepare({ mode: 'image', chunks: 2, chunkPrompts: ['a', 'b', 'c', 'd'] });
+ expect(prepared.effectiveChunkPrompts).toEqual(['a', 'b']);
+ });
+
+ it('leaves a short list short — uncovered chunks fall back to the main prompt', async () => {
+ const prepared = await prepare({ mode: 'image', chunks: 3, chunkPrompts: ['a'] });
+ expect(prepared.effectiveChunkPrompts).toEqual(['a']);
+ });
+
+ it('drops the list entirely for a single-chunk render', async () => {
+ const prepared = await prepare({ mode: 'image', chunks: 1, chunkPrompts: ['a', 'b'] });
+ expect(prepared.effectiveChunkPrompts).toBeUndefined();
+ });
+
+ it('drops the list for a mode pinned to one chunk', async () => {
+ // An IC remix anchors a single clip, so chunks is pinned to 1 — a beat
+ // list sent anyway must not persist into job params.
+ loadHistory.mockResolvedValue([{ id: '11111111-1111-4111-8111-111111111111', filename: 'prior.mp4' }]);
+ const prepared = await prepare({
+ mode: 'ic-control',
+ icReferenceVideoIds: ['11111111-1111-4111-8111-111111111111'],
+ chunkPrompts: ['a', 'b'],
+ });
+ expect(prepared.effectiveChunks).toBe(1);
+ expect(prepared.effectiveChunkPrompts).toBeUndefined();
+ });
+
+ it('collapses an all-blank list to undefined', async () => {
+ // "every beat cleared" and "no beats sent" must persist identically —
+ // otherwise a resume replays an array of nulls into the form.
+ const prepared = await prepare({ mode: 'image', chunks: 3, chunkPrompts: ['', ' ', ''] });
+ expect(prepared.effectiveChunkPrompts).toBeUndefined();
+ });
+
+ it('is undefined when no beats were supplied', async () => {
+ const prepared = await prepare({ mode: 'image', chunks: 2 });
+ expect(prepared.effectiveChunkPrompts).toBeUndefined();
+ });
+ });
+
describe('rejected-await rollback (#3326)', () => {
// Each case stages a durable copy, then makes the NEXT await reject. Without
// the withStagedRollback guard the rejection bubbles past every explicit