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

Continue a shot from the frame the previous shot ends on in the cut

Claude7e3f1af5b1dd
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index b14e10b1ff..fb73348ff8 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -3,7 +3,7 @@ import ShotActionInspector from './ShotActionInspector.jsx';
import SceneCameraControls from './SceneCameraControls.jsx';
import { MUSIC_VIDEO_MEDIUM_LABELS } from '../../../../server/lib/musicVideoMediumPlan.js';
import { useEffect, useRef, useState } from 'react';
-import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard } from 'lucide-react';
+import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, SkipForward } from 'lucide-react';
import { formatDurationSec } from '../../utils/formatters.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import PerformanceEvidence from './PerformanceEvidence.jsx';
@@ -87,7 +87,7 @@ export default function SceneCard({
scene, index, isLast, generatingFrame, generatingVideo, frameProgress = null, videoProgress = null,
settingsSaving, videoBlockedReason, canContinueShot,
onMove, onDelete, onEditLocal, onSave,
- onGenerateFrame, onGenerateVideo, onContinueVideo, onGenerateEndFrame, generatingEndFrame = false,
+ onGenerateFrame, onGenerateVideo, onContinueVideo, onGenerateEndFrame, generatingEndFrame = false, onContinueFromPrevious, previousHasClip = false,
onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false, documentComposition = false,
lipSyncBackend = '', songDurationSec = null, onSplit, onMergeNext, nextEndSec = null, falVideoSettings = null, onSeek, performanceReview = null, onRepairPerformance, repairBusy = false,
expanded, onToggleExpand, footageOptional = false, failedScenes = null, songReview = null,
@@ -116,6 +116,7 @@ export default function SceneCard({
// Source-clip length, read from the inline player's metadata and keyed to
// the clip it was measured from so a regenerated clip is re-measured.
const [speakerDirty, setSpeakerDirty] = useState(false);
+ const [keepStillAsEnd, setKeepStillAsEnd] = useState(false);
const [speakerSaving, setSpeakerSaving] = useState(false);
const [clipMeta, setClipMeta] = useState(null);
const clipSec = clipMeta && clipMeta.id === scene.videoHistoryId ? clipMeta.sec : null;
@@ -427,6 +428,23 @@ export default function SceneCard({
<ImagePlus size={14} /> Import take
</button>
)}
+ {onContinueFromPrevious && layer === 'footage' && index > 0 && (
+ <>
+ <button type="button" onClick={() => onContinueFromPrevious(scene, { keepStillAsEnd: keepStillAsEnd && Boolean(scene.referenceImageId) })}
+ disabled={takeBusy || !previousHasClip}
+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"
+ title={previousHasClip ? 'Start this shot from the last frame the previous shot shows in the cut' : 'The previous shot needs a clip first'}>
+ <SkipForward size={14} /> From previous shot
+ </button>
+ {scene.referenceImageId && (
+ <label htmlFor={`mv-scene-${scene.sceneId}-keep-still-end`} className="flex items-center gap-1 text-[11px] text-port-text-muted min-h-[44px] sm:min-h-0">
+ <input id={`mv-scene-${scene.sceneId}-keep-still-end`} type="checkbox" checked={keepStillAsEnd}
+ onChange={(e) => setKeepStillAsEnd(e.target.checked)} />
+ Keep this frame as the end frame
+ </label>
+ )}
+ </>
+ )}
</div>
</div>
</div>
diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsx
index 1be9facf44..0da5ed03fc 100644
--- a/client/src/components/musicVideo/stages/BoardStage.jsx
+++ b/client/src/components/musicVideo/stages/BoardStage.jsx
@@ -232,6 +232,8 @@ export default function BoardStage({ board }) {
takeBusy={takes.busy}
onSelectTake={takes.selectTake}
onReviewTake={takes.reviewTake}
+ onContinueFromPrevious={takes.continueFromPrevious}
+ previousHasClip={Boolean(scenes[idx - 1]?.videoHistoryId)}
onImportTake={(target) => board.setPickerTarget({ type: 'take', sceneId: target.sceneId })}
onImportClipTake={(target) => board.setPickerTarget({ type: 'clip', sceneId: target.sceneId })}
layered={layered}
diff --git a/client/src/hooks/useMusicVideoTakes.js b/client/src/hooks/useMusicVideoTakes.js
index 64e6231918..03b783a4d1 100644
--- a/client/src/hooks/useMusicVideoTakes.js
+++ b/client/src/hooks/useMusicVideoTakes.js
@@ -3,6 +3,7 @@ import toast from '../components/ui/Toast';
import {
addMusicVideoSceneTake,
selectMusicVideoSceneTake,
+ continueMusicVideoSceneFromPrevious,
reviewMusicVideoSceneTake,
getMusicVideoHandoff,
getMusicVideoHandoffBundle,
@@ -68,6 +69,13 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
'Failed to select take',
);
+ // Continuing shot: the previous shot's last on-screen frame becomes this
+ // scene's start frame; `keepStillAsEnd` keeps the current one as its end frame.
+ const continueFromPrevious = (scene, { keepStillAsEnd = false } = {}) => runTakeOp(
+ (projectId) => continueMusicVideoSceneFromPrevious(projectId, scene.sceneId, { keepStillAsEnd }, { silent: true }).then((res) => res.scene),
+ 'Failed to continue from the previous shot',
+ );
+
const reviewTake = (scene, take, review) => runTakeOp(
(projectId) => reviewMusicVideoSceneTake(projectId, scene.sceneId, take.takeId, review, { silent: true }),
'Failed to update take',
@@ -146,5 +154,5 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
if (failures.length) toast.error(failures.slice(0, 3).join(' · '));
};
- return { busy, selectTake, reviewTake, importTake, importClipTake, exportHandoff, exportHandoffBundle, importHandoffFiles };
+ return { busy, selectTake, reviewTake, continueFromPrevious, importTake, importClipTake, exportHandoff, exportHandoffBundle, importHandoffFiles };
}
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index fb05c7452b..5c9085bde0 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -170,6 +170,11 @@ export const addMusicVideoSceneTake = (id, sceneId, body, options = {}) => reque
});
export const selectMusicVideoSceneTake = (id, sceneId, takeId, options = {}) =>
request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}/select`, { method: 'POST', ...options });
+// Start a shot from the previous shot's last on-screen frame → { scene, frame }.
+export const continueMusicVideoSceneFromPrevious = (id, sceneId, body = {}, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/continue-from-previous`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
export const reviewMusicVideoSceneTake = (id, sceneId, takeId, review, options = {}) =>
request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}`, {
method: 'PATCH', body: JSON.stringify(review), ...options,
diff --git a/server/lib/README.md b/server/lib/README.md
index b70ea1aa6a..6f5806a06a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -861,6 +861,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoTitleCard.js` | The MTV-style opening title card (song, artist, year over the opener): `normalizeTitleCard`, `titleCardVisible`, `titleCardPrefill` (a new card's text and a window ending before the first sung line), and `titleCardRuntimeSource` (the page script the live preview and the document render install to draw it per seek, with its fade and title-safe layout). Browser-safe. |
| `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. |
| `musicVideoEndFrame.js` | Style-break end frames (#11173): `sceneEndFramePlan(scene, { backend, falModelId })` says whether a clip sends the scene's end frame (only fal models with an end image, never a performance shot) and why not; `sceneEndFrameRequestFields` turns it into `lastImageFile`. Shared by the board and production. |
+| `musicVideoHandoffFrame.js` | Continuing shots: `sceneClipOutFrameSec(scene, clipDurationSec, fps)` is the time in a shot's clip of the last frame the cut shows (performance edit in/out, loop wrap, hold past the clip's end); `previousShot(project, sceneId)` is the shot before it by start time. |
| `musicVideoCrossLinks.js` | Cross-links between a release's posts: each post's public link, the `Label: url` lines a new draft adds, which links a posted record carries (`links`, or what its draft always linked), and `crossLinkBackfill(kit)` listing the links each editable post (YouTube, Suno, X, Stacker News) still lacks. Shared by the publish payloads and the Publish stage. |
| `musicVideoExcerptRange.js` | `excerptRangeFits(startSec, endSec, totalSec, fps)`: whether a code/document excerpt window fits a frame-quantized render, allowing the end up to one frame past it (scene ends follow the analysed song length; the caller clamps). The start must fall inside the render; an unknown fps allows no slack. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 9a94a17786..a008135a74 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -839,6 +839,7 @@ export * from './filmLookValidation.js';
export * from './musicVideoTitleCard.js';
export * from './musicVideoDependencies.js';
export * from './musicVideoEndFrame.js';
+export * from './musicVideoHandoffFrame.js';
export * from './musicVideoCrossLinks.js';
export * from './musicVideoExcerptRange.js';
diff --git a/server/lib/musicVideoHandoffFrame.js b/server/lib/musicVideoHandoffFrame.js
new file mode 100644
index 0000000000..dfd4a88bac
--- /dev/null
+++ b/server/lib/musicVideoHandoffFrame.js
@@ -0,0 +1,51 @@
+/**
+ * Music Video continuing shots: where the previous shot's clip ends on screen.
+ *
+ * A clip is usually longer than the shot that plays it (a 5.9 s fal clip under
+ * a 4.04 s shot), and the cut stops it at the shot's out-point. A continuing
+ * shot must start from the frame the viewer last saw, not from the clip's true
+ * last frame, which can be seconds further on. That frame sits at the clip's
+ * in-point plus the shot's authored span, using the same rules as the render:
+ * - a performance take starts at its edit in-point and stops at its edit out-point;
+ * - a looping shot wraps around the clip;
+ * - a non-looping shot longer than its clip holds the clip's last frame.
+ * The returned time is the last displayed frame, one frame before the out-point.
+ */
+import { sceneHasAuthoredSpan } from './musicVideoLayers.js';
+import { selectedPerformanceInstruction } from './musicVideoShotTiming.js';
+
+const round3 = (n) => Math.round(n * 1000) / 1000;
+
+/**
+ * Seconds into the scene's clip of the last frame the cut shows, or null when
+ * the scene is untimed or the clip length is unknown. `fps` sets the one-frame
+ * step back from the out-point (24 when unknown).
+ */
+export function sceneClipOutFrameSec(scene, clipDurationSec, fps = 24) {
+ const duration = Number(clipDurationSec);
+ if (!sceneHasAuthoredSpan(scene) || !(duration > 0)) return null;
+ const frameSec = 1 / (Number(fps) > 0 ? Number(fps) : 24);
+ const span = scene.endSec - scene.startSec;
+ const edit = selectedPerformanceInstruction(scene)?.edit ?? null;
+ const inSec = edit ? Math.min(Math.max(0, edit.inSec), duration) : 0;
+ const stopSec = edit ? Math.min(edit.outSec, duration) : duration;
+ // Mirrors render.js: only a pre-#8964 scene (no `loop` key) or `loop: true`
+ // repeats, and a performance take never does.
+ const loops = !edit && scene.loop !== false;
+ const playable = stopSec - inSec;
+ if (!(playable > 0)) return round3(inSec);
+ const played = loops && span > playable ? span % playable || playable : Math.min(span, playable);
+ return round3(Math.max(inSec, inSec + played - frameSec));
+}
+
+/**
+ * The shot that plays immediately before `sceneId` in the cut (by start time),
+ * or null for the first shot.
+ */
+export function previousShot(project, sceneId) {
+ const timed = (project?.scenes || [])
+ .filter((s) => sceneHasAuthoredSpan(s))
+ .sort((a, b) => a.startSec - b.startSec);
+ const idx = timed.findIndex((s) => s.sceneId === sceneId);
+ return idx > 0 ? timed[idx - 1] : null;
+}
diff --git a/server/lib/musicVideoHandoffFrame.test.js b/server/lib/musicVideoHandoffFrame.test.js
new file mode 100644
index 0000000000..3d80cc788e
--- /dev/null
+++ b/server/lib/musicVideoHandoffFrame.test.js
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { previousShot, sceneClipOutFrameSec } from './musicVideoHandoffFrame.js';
+
+// Where a continuing shot's start frame comes from: the last frame the cut
+// shows of the previous shot's clip, never the clip's own last frame.
+describe('sceneClipOutFrameSec', () => {
+ const shot = (extra) => ({ sceneId: 's1', startSec: 0, endSec: 4.04, loop: false, ...extra });
+ it.each([
+ ['a 4.04 s shot over a 5.9 s clip stops at 4.04 s, not 5.9 s', shot(), 5.9, 24, 3.998],
+ ['a shot longer than its clip holds the clip\'s last frame', shot({ endSec: 8 }), 5.9, 24, 5.858],
+ ['a looping shot wraps around the clip', shot({ endSec: 9, loop: true }), 6, 24, 2.958],
+ ['a legacy scene without a loop key loops', { sceneId: 's1', startSec: 0, endSec: 7 }, 6, 25, 0.96],
+ ['a performance take starts at its edit in-point', shot({
+ endSec: 3, shotMode: 'performance', videoHistoryId: 'clip',
+ takes: [{ kind: 'video', assetId: 'clip', shotInstruction: { shotMode: 'performance', edit: { inSec: 1.5, outSec: 4.5 } } }],
+ }), 6, 24, 4.458],
+ ])('%s', (_label, scene, durationSec, fps, expected) => {
+ expect(sceneClipOutFrameSec(scene, durationSec, fps)).toBe(expected);
+ });
+
+ it('is null for an untimed shot or an unreadable clip', () => {
+ expect(sceneClipOutFrameSec({ sceneId: 's1' }, 5, 24)).toBeNull();
+ expect(sceneClipOutFrameSec(shot(), null, 24)).toBeNull();
+ });
+});
+
+describe('previousShot', () => {
+ const project = { scenes: [{ sceneId: 'b', startSec: 4, endSec: 8 }, { sceneId: 'a', startSec: 0, endSec: 4 }, { sceneId: 'loose' }] };
+ it('is the shot before it in the cut, by start time', () => {
+ expect(previousShot(project, 'b')?.sceneId).toBe('a');
+ expect(previousShot(project, 'a')).toBeNull();
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index f12f59c13a..13dfc077a8 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1352,6 +1352,9 @@ export const musicVideoDocumentShotsSchema = z.object({
ids.add(shot.id);
}
});
+// Start a shot from the previous shot's on-screen out-frame; optionally keep
+// the current start frame as its end frame.
+export const musicVideoContinueShotSchema = z.object({ keepStillAsEnd: z.boolean().optional() }).strict();
export const musicVideoProductionImportSchema = z.object({ source: z.string().min(2).max(250000) }).strict();
export const musicVideoProductionApprovalSchema = z.object({
stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 1ef8000110..f9338d00fd 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -12,7 +12,7 @@ import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { pipeline } from 'stream/promises';
import { Router } from 'express';
-import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
+import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
import { productionReadiness } from '../services/musicVideo/productionReview.js';
import { finishedOutsideBlocker } from '../lib/musicVideoFinishedOutside.js';
import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';
@@ -1521,6 +1521,13 @@ router.post('/:id/scenes/:sceneId/takes', asyncHandler(async (req, res) => {
res.status(201).json({ scene, take: appended[0] });
}));
+// Continuing shot: the previous shot's last on-screen frame becomes this scene's start frame.
+router.post('/:id/scenes/:sceneId/continue-from-previous', asyncHandler(async (req, res) => {
+ const { keepStillAsEnd } = validateRequest(musicVideoContinueShotSchema, req.body ?? {});
+ const { continueFromPreviousShot } = await import('../services/musicVideo/continueShot.js');
+ res.json(await continueFromPreviousShot(req.params.id, req.params.sceneId, { keepStillAsEnd }));
+}));
+
router.post('/:id/scenes/:sceneId/takes/:takeId/select', asyncHandler(async (req, res) => {
res.json(await selectSceneTake(req.params.id, req.params.sceneId, req.params.takeId));
}));
diff --git a/server/services/musicVideo/continueShot.js b/server/services/musicVideo/continueShot.js
new file mode 100644
index 0000000000..74d10ec9fa
--- /dev/null
+++ b/server/services/musicVideo/continueShot.js
@@ -0,0 +1,71 @@
+/**
+ * Music Video continuing shots: start a shot from the frame the previous shot
+ * ends on in the cut.
+ *
+ * A clip is often longer than the shot that plays it, so the clip's true last
+ * frame is not the last frame the viewer saw. Handing that later frame to the
+ * next shot jumps the action forward and can lose what was in frame (a car
+ * that had both headlights on screen at the cut kept only one by the clip's
+ * end). This extracts the previous shot's on-screen out-frame
+ * (lib/musicVideoHandoffFrame.js) into the gallery and selects it as this
+ * scene's start frame. With `keepStillAsEnd`, the scene's current start frame
+ * becomes its style-break end frame (#11173), so a fal clip on an end-frame
+ * model travels from the handoff to the planned still.
+ */
+import { join } from 'path';
+import { existsSync } from 'fs';
+import { ServerError } from '../../lib/errorHandler.js';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { findFfmpeg, probeVideoGeometry, runFfmpegProcess, safeUnder } from '../../lib/ffmpeg.js';
+import { previousShot, sceneClipOutFrameSec } from '../../lib/musicVideoHandoffFrame.js';
+import { getHistoryItem } from '../videoGen/history.js';
+import { appendSceneTakes, getProject, selectSceneTake } from './projects.js';
+
+const refuse = (message, code, status = 409) => new ServerError(message, { status, code });
+
+/**
+ * Extract the previous shot's on-screen out-frame and make it `sceneId`'s
+ * start frame. Returns `{ scene, frame: { imageId, atSec, fromSceneId } }`.
+ */
+export async function continueFromPreviousShot(projectId, sceneId, { keepStillAsEnd = false } = {}) {
+ const project = await getProject(projectId);
+ if (!project) throw refuse('Project not found', 'NOT_FOUND', 404);
+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);
+ if (!scene) throw refuse('Scene not found', 'NOT_FOUND', 404);
+ const previous = previousShot(project, sceneId);
+ if (!previous) throw refuse('This is the first shot, so there is no previous shot to continue from', 'MUSIC_VIDEO_NO_PREVIOUS_SHOT');
+ const entry = previous.videoHistoryId ? await getHistoryItem(previous.videoHistoryId) : null;
+ const videoPath = entry?.filename ? safeUnder(PATHS.videos, entry.filename) : null;
+ if (!videoPath || !existsSync(videoPath)) {
+ throw refuse('The previous shot has no selected clip to continue from', 'MUSIC_VIDEO_PREVIOUS_CLIP_MISSING');
+ }
+ const geometry = await probeVideoGeometry(videoPath);
+ const atSec = sceneClipOutFrameSec(previous, geometry?.durationSec, geometry?.fps);
+ if (atSec == null) throw refuse('Could not read where the previous shot ends in its clip', 'MUSIC_VIDEO_PREVIOUS_CLIP_UNREADABLE', 422);
+
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw refuse('ffmpeg not found on PATH', 'FFMPEG_MISSING', 500);
+ await ensureDir(PATHS.images);
+ // Keyed by clip and time, so the same handoff is extracted once.
+ const imageId = `handoff-${entry.id}-${Math.round(atSec * 1000)}.png`;
+ const outPath = join(PATHS.images, imageId);
+ if (!existsSync(outPath)) {
+ const result = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: ['-y', '-hide_banner', '-loglevel', 'error', '-ss', String(atSec), '-i', videoPath, '-frames:v', '1', outPath],
+ });
+ if (!result.ok || !existsSync(outPath)) {
+ throw refuse(`Could not extract the previous shot's out-frame: ${result.reason || 'ffmpeg failed'}`, 'MUSIC_VIDEO_HANDOFF_FRAME_FAILED', 500);
+ }
+ }
+ console.log(`🎞️ Handoff frame for ${sceneId}: ${previous.sceneId} clip at ${atSec}s of ${geometry.durationSec.toFixed(2)}s`);
+
+ const plannedStill = keepStillAsEnd && scene.referenceImageId && scene.referenceImageId !== imageId ? scene.referenceImageId : null;
+ const { appended } = await appendSceneTakes(projectId, sceneId, [
+ { kind: 'image', assetId: imageId, source: 'generated', provider: 'portos', prompt: `Out-frame of the previous shot at ${atSec}s of its clip` },
+ ...(plannedStill ? [{ kind: 'endImage', assetId: plannedStill, source: 'imported', provider: 'portos' }] : []),
+ ]);
+ let updated = await selectSceneTake(projectId, sceneId, appended[0].takeId);
+ if (plannedStill) updated = await selectSceneTake(projectId, sceneId, appended[1].takeId);
+ return { scene: updated, frame: { imageId, atSec, fromSceneId: previous.sceneId } };
+}
diff --git a/server/services/musicVideo/continueShot.test.js b/server/services/musicVideo/continueShot.test.js
new file mode 100644
index 0000000000..4707819c85
--- /dev/null
+++ b/server/services/musicVideo/continueShot.test.js
@@ -0,0 +1,59 @@
+/**
+ * Continuing shots against a real ffmpeg: the handoff frame is the last frame
+ * the cut shows of the previous shot's clip, and it becomes this shot's start
+ * frame (optionally moving the planned still to the end frame).
+ */
+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const ROOT = mkdtempSync(join(tmpdir(), 'mv-continue-shot-'));
+const mocks = vi.hoisted(() => ({ project: null, appended: [], selected: [] }));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, videos: join(ROOT, 'videos'), images: join(ROOT, 'images') } };
+});
+vi.mock('../videoGen/history.js', () => ({ getHistoryItem: vi.fn(async (id) => (id === 'clip-a' ? { id, filename: 'clip-a.mp4' } : null)) }));
+vi.mock('./projects.js', () => ({
+ getProject: vi.fn(async () => mocks.project),
+ appendSceneTakes: vi.fn(async (_id, _sceneId, inputs) => {
+ mocks.appended.push(...inputs);
+ return { appended: inputs.map((input, i) => ({ ...input, takeId: `t${mocks.appended.length - inputs.length + i}` })) };
+ }),
+ selectSceneTake: vi.fn(async (_id, sceneId, takeId) => { mocks.selected.push(takeId); return { sceneId }; }),
+}));
+
+const { findFfmpeg, runFfmpegProcess, probeVideoStreamInfo } = await import('../../lib/ffmpeg.js');
+const { continueFromPreviousShot } = await import('./continueShot.js');
+const ffmpeg = await findFfmpeg();
+
+describe.skipIf(!ffmpeg)('continueFromPreviousShot', () => {
+ beforeAll(async () => {
+ mkdirSync(join(ROOT, 'videos'), { recursive: true });
+ // A 3 s clip under a 1 s shot.
+ const made = await runFfmpegProcess({ bin: ffmpeg, args: ['-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=320x180:rate=24:duration=3', '-pix_fmt', 'yuv420p', join(ROOT, 'videos', 'clip-a.mp4')] });
+ expect(made.ok).toBe(true);
+ });
+ afterAll(() => rmSync(ROOT, { recursive: true, force: true }));
+
+ it('extracts the frame at the previous shot\'s out-point and keeps the planned still as the end frame', async () => {
+ mocks.project = { id: 'mv-1', scenes: [
+ { sceneId: 'a', startSec: 0, endSec: 1, loop: false, videoHistoryId: 'clip-a' },
+ { sceneId: 'b', startSec: 1, endSec: 3, referenceImageId: 'planned.png' },
+ ] };
+ const { frame } = await continueFromPreviousShot('mv-1', 'b', { keepStillAsEnd: true });
+ expect(frame).toEqual({ imageId: 'handoff-clip-a-958.png', atSec: 0.958, fromSceneId: 'a' });
+ expect(existsSync(join(ROOT, 'images', frame.imageId))).toBe(true);
+ expect((await probeVideoStreamInfo(join(ROOT, 'images', frame.imageId))).width).toBe(320);
+ expect(mocks.appended.map((t) => [t.kind, t.assetId])).toEqual([['image', 'handoff-clip-a-958.png'], ['endImage', 'planned.png']]);
+ expect(mocks.selected).toEqual(['t0', 't1']);
+ });
+
+ it('refuses the first shot and a previous shot without a clip', async () => {
+ mocks.project = { id: 'mv-1', scenes: [{ sceneId: 'a', startSec: 0, endSec: 1 }, { sceneId: 'b', startSec: 1, endSec: 2 }] };
+ await expect(continueFromPreviousShot('mv-1', 'a')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_NO_PREVIOUS_SHOT' });
+ await expect(continueFromPreviousShot('mv-1', 'b')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_PREVIOUS_CLIP_MISSING' });
+ });
+});