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: choose video posters and prepare sharing downloads (#8650)

[._.]/ Adam Eivyab0ec9878bb3
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 04629d8e2e..6c0cb89558 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -119,6 +119,7 @@ export default function MediaLightbox({
onAnnotationChange,
onPromptChange,
onPromptAnalysis,
+ onPosterChange,
variantGroup = null,
onSelectVariant,
}) {
@@ -451,6 +452,8 @@ export default function MediaLightbox({
annotation={annotation}
onAnnotationChange={onAnnotationChange}
onPromptChange={item.compact ? undefined : onPromptChange}
+ onPosterChange={onPosterChange}
+ getPlayhead={() => videoRef.current?.currentTime ?? 0}
variantGroup={variantGroup}
onSelectVariant={onSelectVariant}
/>
@@ -492,10 +495,18 @@ function SettingsPane({
item, meta, isVideo,
onClose, onRemix, onSendToImage, onSendToVideo, onSendTo3d, onContinue, onClean, onRegenerate, onRemoveWatermark, regenAvailable, regenBounds,
copy, onRefine, onPromptFrom,
- annotation, onAnnotationChange, onPromptChange,
+ annotation, onAnnotationChange, onPromptChange, onPosterChange, getPlayhead,
variantGroup, onSelectVariant,
}) {
const asideClasses = 'md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border max-h-[40vh] md:max-h-[92vh]';
+ const [posterSaving, setPosterSaving] = useState(false);
+ const [posterError, setPosterError] = useState(null);
+ const savePoster = async atSec => {
+ if (posterSaving) return;
+ setPosterSaving(true);
+ setPosterError(null);
+ await onPosterChange(item, atSec).catch(error => setPosterError(error.message)).finally(() => setPosterSaving(false));
+ };
const [cleaning, setCleaning] = useState(false);
const [regenerating, setRegenerating] = useState(false);
const [lightRegenerating, setLightRegenerating] = useState(false);
@@ -954,6 +965,19 @@ function SettingsPane({
<ImageIcon className="w-3.5 h-3.5" /> Continue
</button>
)}
+ {isVideo && onPosterChange && (
+ <div className="w-full flex flex-wrap gap-2">
+ <button type="button" disabled={posterSaving} onClick={() => savePoster(getPlayhead())}
+ className="min-h-[44px] px-2 rounded bg-port-border text-white disabled:opacity-50">Use this frame as poster</button>
+ <button type="button" disabled={posterSaving} onClick={() => savePoster(null)}
+ className="min-h-[44px] px-2 rounded bg-port-border text-white disabled:opacity-50">Reset poster</button>
+ {posterError && <p role="alert" className="text-port-error">{posterError}</p>}
+ </div>
+ )}
+ {isVideo && item.id && item.previewUrl && (
+ <a href={`/api/video-gen/history/${encodeURIComponent(item.id)}/sharing-download`} download
+ className="min-h-[44px] flex items-center px-2 rounded bg-port-border text-white">Download for sharing</a>
+ )}
<AddToCollectionMenu item={item} size="md" />
<PinToMoodBoardMenu item={item} size="md" />
<a
diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsx
index 3a7776eadc..72d2096d30 100644
--- a/client/src/components/media/MediaLightbox.test.jsx
+++ b/client/src/components/media/MediaLightbox.test.jsx
@@ -335,3 +335,16 @@ describe('MediaLightbox compact preview item', () => {
expect(screen.getByRole('button', { name: 'Refine Prompt' })).toBeInTheDocument();
});
});
+
+ it('saves the current playhead, resets the poster, and offers a sharing copy', async () => {
+ HTMLMediaElement.prototype.play = vi.fn().mockResolvedValue();
+ const onPosterChange = vi.fn().mockResolvedValue({});
+ render(<MediaLightbox item={videoItem} onClose={() => {}} onPosterChange={onPosterChange} />);
+ videoEl().currentTime = 12.4;
+ fireEvent.click(screen.getByRole('button', { name: 'Use this frame as poster' }));
+ await waitFor(() => expect(onPosterChange).toHaveBeenCalledWith(videoItem, 12.4));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Reset poster' })).not.toBeDisabled());
+ fireEvent.click(screen.getByRole('button', { name: 'Reset poster' }));
+ await waitFor(() => expect(onPosterChange).toHaveBeenCalledWith(videoItem, null));
+ expect(screen.getByRole('link', { name: 'Download for sharing' })).toHaveAttribute('href', '/api/video-gen/history/abc/sharing-download');
+});
diff --git a/client/src/components/media/MediaPreview.jsx b/client/src/components/media/MediaPreview.jsx
index 7c68e861f7..f7165f08b7 100644
--- a/client/src/components/media/MediaPreview.jsx
+++ b/client/src/components/media/MediaPreview.jsx
@@ -3,7 +3,7 @@ import MediaLightbox from './MediaLightbox';
import { getMediaNavProps } from '../../lib/mediaNavigation';
import { computeImageVariantGroup } from './variants';
import useImageVariants from '../../hooks/useImageVariants';
-import { updateImagePrompt, updateVideoPrompt } from '../../services/apiImageVideo';
+import { updateImagePrompt, updateVideoPrompt, updateVideoPoster } from '../../services/apiImageVideo';
// Thin wrapper around MediaLightbox that owns the consistent wiring every
// page repeated by hand: open/close, prev/next nav, and the annotation
@@ -22,9 +22,11 @@ export default function MediaPreview({
annotations,
updateAnnotation,
onPromptSaved,
+ onPosterSaved,
...handlers
}) {
const [promptOverride, setPromptOverride] = useState(null);
+ const [posterOverride, setPosterOverride] = useState(null);
const navProps = useMemo(
() => getMediaNavProps(items, preview, setPreview),
[items, preview, setPreview]
@@ -35,9 +37,10 @@ export default function MediaPreview({
// has one). This is keyed to the media identity, never to the selection
// itself, so the URL remains the source of truth for which item is open.
useEffect(() => {
+ setPosterOverride(current => current?.key === preview?.key ? current : null);
setPromptOverride((current) => current?.key === preview?.key ? current : null);
}, [preview?.key]);
- const displayedPreview = useMemo(() => {
+ const promptedPreview = useMemo(() => {
if (!preview || promptOverride?.key !== preview.key) return preview;
const prompt = promptOverride.prompt;
return {
@@ -46,6 +49,16 @@ export default function MediaPreview({
raw: preview.raw ? { ...preview.raw, prompt: prompt === '(no prompt)' ? '' : prompt } : preview.raw,
};
}, [preview, promptOverride]);
+ const displayedPreview = posterOverride?.key === promptedPreview?.key && promptedPreview
+ ? { ...promptedPreview, ...posterOverride.patch, raw: { ...promptedPreview.raw, ...posterOverride.patch.raw } } : promptedPreview;
+ const savePoster = useCallback(async (item, atSec) => {
+ const result = await updateVideoPoster(item.id, atSec, { silent: true });
+ const patch = { posterSec: result.posterSec, previewUrl: `/data/video-thumbnails/${result.thumbnail}`,
+ raw: { thumbnail: result.thumbnail, posterSec: result.posterSec } };
+ setPosterOverride({ key: item.key, patch });
+ onPosterSaved?.(item, result);
+ return result;
+ }, [onPosterSaved]);
// Original-vs-cleaned toggle, computed over the UNION of the host's items
// and the image's fetched lineage — neither source alone is complete. The
// host list misses a copy it never held (see useImageVariants), while the
@@ -119,6 +132,7 @@ export default function MediaPreview({
annotation={annotations?.[preview?.key] ?? null}
onAnnotationChange={preview && updateAnnotation ? (patch) => updateAnnotation(preview.key, patch) : undefined}
onPromptChange={savePrompt}
+ onPosterChange={savePoster}
variantGroup={variantGroup}
onSelectVariant={onSelectVariant}
onPromptAnalysis={handlePromptAnalysis}
diff --git a/client/src/components/media/MediaPreview.test.jsx b/client/src/components/media/MediaPreview.test.jsx
index 441325f054..062619a9e5 100644
--- a/client/src/components/media/MediaPreview.test.jsx
+++ b/client/src/components/media/MediaPreview.test.jsx
@@ -4,11 +4,12 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router';
import MediaPreview from './MediaPreview';
import usePreviewRoute from '../../hooks/usePreviewRoute';
-import { updateVideoPrompt, listImageVariants, listMediaGalleryPage } from '../../services/apiImageVideo';
+import { updateVideoPrompt, updateVideoPoster, listImageVariants, listMediaGalleryPage } from '../../services/apiImageVideo';
vi.mock('../../services/apiImageVideo', () => ({
updateImagePrompt: vi.fn(),
updateVideoPrompt: vi.fn(),
+ updateVideoPoster: vi.fn(),
listImageVariants: vi.fn(),
listMediaGalleryPage: vi.fn(),
}));
@@ -17,8 +18,10 @@ vi.mock('../../services/apiImageVideo', () => ({
// its own interaction coverage; this stub exposes the item it receives and
// invokes the same callback the real Save prompt button uses.
vi.mock('./MediaLightbox', () => ({
- default: ({ item, onPromptChange, variantGroup, onSelectVariant }) => item ? (
+ default: ({ item, onPromptChange, onPosterChange, variantGroup, onSelectVariant }) => item ? (
<div data-testid="lightbox">
+ <span data-testid="lightbox-poster">{item.previewUrl}</span>
+ <button onClick={() => onPosterChange(item, 12.4)}>Save poster</button>
<span data-testid="lightbox-prompt">{item.prompt}</span>
<span data-testid="lightbox-filename">{item.filename}</span>
<button type="button" onClick={() => onPromptChange(item, 'a saved prompt')}>
@@ -277,3 +280,12 @@ describe('MediaPreview variant toggle', () => {
expect(listImageVariants).not.toHaveBeenCalled();
});
});
+
+it('applies a saved poster immediately and reports the updated history fields to the host', async () => {
+ updateVideoPoster.mockResolvedValue({ id: VIDEO.id, thumbnail: 'new-poster.jpg', posterSec: 12.4 });
+ const saved = vi.fn();
+ render(<MediaPreview preview={VIDEO} setPreview={() => {}} items={[VIDEO]} onPosterSaved={saved} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Save poster' }));
+ await waitFor(() => expect(screen.getByTestId('lightbox-poster')).toHaveTextContent('/data/video-thumbnails/new-poster.jpg'));
+ expect(saved).toHaveBeenCalledWith(VIDEO, { id: VIDEO.id, thumbnail: 'new-poster.jpg', posterSec: 12.4 });
+});
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index b1725c52f1..12ea0eacb7 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -123,6 +123,7 @@ export function normalizeVideo(v) {
return {
kind: 'video',
key: `video:${v.id}`,
+ posterSec: v.posterSec ?? null,
id: v.id,
filename: v.filename,
previewUrl: v.thumbnail ? `/data/video-thumbnails/${v.thumbnail}` : null,
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index ca1fac8f20..d47baffd0a 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -264,6 +264,8 @@ export default function MediaHistory() {
annotations={annotations}
updateAnnotation={updateAnnotation}
onPromptSaved={handlePromptSaved}
+ onPosterSaved={(item, result) => setItems(all => all.map(current => current.key === item.key
+ ? { ...current, raw: { ...current.raw, thumbnail: result.thumbnail, posterSec: result.posterSec } } : current))}
onRemix={handleRemix}
onSendToImage={handleSendToImage}
onSendToVideo={handleSendToVideo}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 5680f69482..2383c01b78 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -630,3 +630,7 @@ export const setMediaModelEnabled = (id, enabled, options = {}) => request(`/ima
export const requestMediaModelSupport = (input, options = {}) => request('/image-video/models/support-request', {
...options, method: 'POST', body: JSON.stringify(input),
});
+
+export const updateVideoPoster = (id, atSec, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}/poster`, {
+ method: 'PATCH', body: JSON.stringify({ atSec }), ...options,
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 9cb0a02cd9..d636a86cfc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -396,7 +396,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
| `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 3ae85fe06f..7193b8e018 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -200,7 +200,7 @@ const probeDurationSeconds = async (videoPath) => {
};
export const probeVideoDuration = probeDurationSeconds;
-export const generateThumbnail = async (videoPath, jobId) => {
+export const generateThumbnail = async (videoPath, jobId, { atSec } = {}) => {
await ensureDir(PATHS.videoThumbnails);
const thumbFilename = `${jobId}.jpg`;
const thumbPath = join(PATHS.videoThumbnails, thumbFilename);
@@ -211,10 +211,14 @@ export const generateThumbnail = async (videoPath, jobId) => {
// longer clips (Extend mode, 10s+) 2.5s is still past the LTX fade-in
// and not at an unreliable boundary. For short clips (<2s) seek to the
// actual midpoint. Fall back to 1s when ffprobe is unavailable.
- const seekSec = duration ? Math.min(2.5, Math.max(0.5, duration / 2)) : 1.0;
+ const stream = Number.isFinite(atSec) && duration ? await probeVideoStreamInfo(videoPath) : null;
+ const lastFrameSec = duration ? Math.max(0, duration - (stream?.fps > 0 ? 1 / stream.fps : 0.001)) : atSec;
+ const seekSec = Number.isFinite(atSec)
+ ? Math.max(0, Math.min(atSec, lastFrameSec))
+ : duration ? Math.min(2.5, Math.max(0.5, duration / 2)) : 1.0;
const result = await runFfmpegProcess({
bin: ffmpeg,
- args: ['-ss', seekSec.toFixed(2), '-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath],
+ args: ['-ss', seekSec.toFixed(Number.isFinite(atSec) ? 6 : 2), '-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath],
stderrTailBytes: 0,
});
if (!result.ok && result.reason?.startsWith('spawn failed: ')) {
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index b06067921a..c4ccd53ff8 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -7,6 +7,7 @@
*/
import { Router } from 'express';
+import { updateVideoPoster, createSharingCopy } from '../services/videoGen/poster.js';
import { basename } from 'path';
import os from 'os';
import { z } from 'zod';
@@ -1144,6 +1145,29 @@ router.post('/history/:id/visibility', asyncHandler(async (req, res) => {
res.json(await setHistoryItemHidden(parsedId.data, body.data.hidden));
}));
+const posterSchema = z.object({ atSec: z.number().finite().nullable() });
+router.patch('/history/:id/poster', asyncHandler(async (req, res) => {
+ const parsed = historyRecordIdSchema.safeParse(req.params.id);
+ if (!parsed.success) failValidation(parsed);
+ const body = validateRequest(posterSchema, req.body);
+ res.json(await updateVideoPoster(parsed.data, body.atSec));
+}));
+
+router.get('/history/:id/sharing-download', asyncHandler(async (req, res) => {
+ const parsed = historyRecordIdSchema.safeParse(req.params.id);
+ if (!parsed.success) failValidation(parsed);
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ res.once('close', abort);
+ const copy = await createSharingCopy(parsed.data, { signal: controller.signal });
+ if (res.destroyed) { await copy.cleanup(); return; }
+ res.download(copy.path, copy.filename, error => {
+ res.off('close', abort);
+ copy.cleanup().catch(err => console.error(`❌ Sharing download cleanup failed: ${err.message}`));
+ if (error && !res.destroyed) res.destroy(error);
+ });
+}));
+
router.patch('/history/:id/prompt', asyncHandler(async (req, res) => {
const parsedId = historyRecordIdSchema.safeParse(req.params.id);
if (!parsedId.success) failValidation(parsedId);
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index d87f2680b4..807a8f24a1 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -5,6 +5,8 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { DEFAULT_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
+const updateVideoPoster = vi.hoisted(() => vi.fn());
+vi.mock('../services/videoGen/poster.js', () => ({ updateVideoPoster, createSharingCopy: vi.fn() }));
const compiledVisual = vi.hoisted(() => ({
version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [], adapters: [], omitted: [], warnings: [],
}));
@@ -354,6 +356,20 @@ describe('isAudioMime', () => {
});
describe('videoGen routes', () => {
+ it('validates poster edits and allows an explicit reset', async () => {
+ const id = '00000000-0000-4000-8000-000000000001';
+ updateVideoPoster.mockResolvedValue({ id, thumbnail: 'poster.jpg', posterSec: 12.4 });
+ const saved = await request(app).patch(`/api/video-gen/history/${id}/poster`).send({ atSec: 12.4 });
+ expect(saved.status).toBe(200);
+ expect(saved.body.posterSec).toBe(12.4);
+ expect(updateVideoPoster).toHaveBeenCalledWith(id, 12.4);
+ const reset = await request(app).patch(`/api/video-gen/history/${id}/poster`).send({ atSec: null });
+ expect(reset.status).toBe(200);
+ expect(updateVideoPoster).toHaveBeenCalledWith(id, null);
+ for (const body of [{}, { atSec: '12.4' }]) {
+ expect((await request(app).patch(`/api/video-gen/history/${id}/poster`).send(body)).status).toBe(400);
+ }
+ });
let app;
beforeEach(() => {
loraCapability.capable = false;
diff --git a/server/services/creativeDirector/videoAssembly.js b/server/services/creativeDirector/videoAssembly.js
index 9cc3b82a3e..28d415a348 100644
--- a/server/services/creativeDirector/videoAssembly.js
+++ b/server/services/creativeDirector/videoAssembly.js
@@ -82,6 +82,20 @@ export async function runVideoAssembly(projectId) {
const { muxStripAudio, resolveMusicTrackPath } = await import('../pipeline/audioMux.js');
const history = await loadHistory();
const segments = await prepareClips(project, history);
+ // Use the actual trimmed segment offsets, not the requested shot lengths.
+ let offset = 0;
+ const scenes = project.directive && project.plan?.steps?.length ? []
+ : [...(project.treatment?.scenes || [])].sort((a, b) => a.order - b.order);
+ const beats = segments.map((segment, index) => {
+ const duration = segment.outSec - segment.inSec;
+ const scene = scenes[index];
+ const beat = { atSec: offset + duration / 2, duration, score: scene?.evaluation?.score };
+ offset += duration;
+ return beat;
+ });
+ const scored = beats.filter(beat => Number.isFinite(beat.score));
+ const best = (scored.length ? scored : beats).reduce((best, beat) =>
+ !best || (scored.length ? beat.score > best.score : beat.duration > best.duration) ? beat : best, null);
const contentRevision = canonicalSnapshotChecksum({ segments, audio: project.videoExecution.choices.audio,
input: project.videoExecution.inputRevision, revision: project.videoWorkRevision || 0 });
let entry = project.videoRoughCut?.contentRevision === contentRevision
@@ -113,7 +127,7 @@ export async function runVideoAssembly(projectId) {
entry = jobId ? history.find(row => row.id === jobId) : null;
if (!entry && !['running', 'pending'].includes(timeline.getRenderJobStatus(jobId)?.status)) {
if (!await isCurrent()) return;
- ({ jobId } = await timeline.renderProject(timelineProject.id));
+ ({ jobId } = await timeline.renderProject(timelineProject.id, { posterSec: best?.atSec }));
await mutateVideoProject(projectId, current => matches(current)
? { project: { ...current, videoExecution: { ...current.videoExecution, assembly: { jobId, contentRevision, timelineProjectId: timelineProject.id } } }, result: true }
: { project: current, result: false, skipPersist: true });
diff --git a/server/services/creativeDirector/videoAssembly.test.js b/server/services/creativeDirector/videoAssembly.test.js
index 4a55e8291a..27674a4a20 100644
--- a/server/services/creativeDirector/videoAssembly.test.js
+++ b/server/services/creativeDirector/videoAssembly.test.js
@@ -147,3 +147,21 @@ it('mutes a selected shot in the real cut while retaining the next shot audio',
expect(await rms(1)).toBeLessThan(0.0001);
expect(await rms(4)).toBeGreaterThan(0.01);
}, 30000);
+
+// Regression: the second accepted shot wins even though the old 2.5s seek is in shot one.
+it('uses the highest-scoring accepted scene midpoint on a three-scene timeline', async context => {
+ requireFfmpeg(context);
+ state.project.targetDurationSeconds = 9;
+ state.project.videoDraft.durationRange = { min: 9, max: 10 };
+ state.project.treatment.scenes = [0, 1, 0].map((clip, order) => ({
+ ...state.project.treatment.scenes[clip], sceneId: `shot-${order}`, order,
+ evaluation: { score: [0.2, 0.9, 0.3][order] },
+ }));
+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);
+ await runVideoAssembly('example-video');
+ expect(state.project.failureReason).toBeNull();
+ const final = state.history.find(item => item.id === state.project.finalVideoId);
+ const { stdout } = await exec(ffmpeg, ['-v', 'error', '-i', join(state.root, 'thumbnails', final.thumbnail), '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { encoding: 'buffer' });
+ expect(stdout[2]).toBeGreaterThan(200);
+ expect(stdout[0]).toBeLessThan(30);
+}, 30000);
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index d35ebb5bfb..a54fbcb2d0 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -389,7 +389,11 @@ export async function renderMusicVideo(projectId) {
// releases the slot.
try {
job.status = 'complete';
- const thumb = await generateThumbnail(outputPath, jobId);
+ const section = (project.audioAnalysis?.sections || [])
+ .filter(section => Number.isFinite(section.energy) && section.startSec >= 0 && section.endSec > section.startSec && section.startSec < totalDuration)
+ .sort((a, b) => b.energy - a.energy || a.startSec - b.startSec)[0];
+ const atSec = section ? (section.startSec + Math.min(section.endSec, totalDuration)) / 2 : undefined;
+ const thumb = await generateThumbnail(outputPath, jobId, { atSec });
const meta = {
id: jobId,
prompt: `Music Video: ${project.name}`,
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index b883bae63a..44f420c15e 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -61,7 +61,7 @@ vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));
vi.mock('./projects.js', () => ({ getProject: vi.fn(), listProjects: vi.fn(async () => []), updateProject: vi.fn(async () => ({})) }));
import { renderMusicVideo, getRenderJobStatus } from './render.js';
-import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { findFfmpeg, generateThumbnail } from '../../lib/ffmpeg.js';
import { loadHistory } from '../videoGen/local.js';
import { getTrack } from '../tracks/index.js';
import { getProject, listProjects, updateProject } from './projects.js';
@@ -246,3 +246,18 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
logSpy.mockRestore();
});
});
+
+it('chooses the loudest section midpoint within the rendered duration', async () => {
+ prime('poster-section');
+ const project = await getProject();
+ getProject.mockResolvedValue({ ...project, audioAnalysis: { sections: [
+ { startSec: 0, endSec: 1, energy: 0.2 },
+ { startSec: 1, endSec: 2, energy: 0.9 },
+ ] } });
+ const { jobId } = await renderMusicVideo('poster-section');
+ lastProc().emit('spawn');
+ lastProc().emit('close', 0, null);
+ await tick();
+ expect(generateThumbnail).toHaveBeenCalledWith(expect.any(String), jobId, { atSec: 1.5 });
+ expect(getRenderJobStatus(jobId).status).toBe('complete');
+});
diff --git a/server/services/videoGen/poster.js b/server/services/videoGen/poster.js
new file mode 100644
index 0000000000..923000b65a
--- /dev/null
+++ b/server/services/videoGen/poster.js
@@ -0,0 +1,73 @@
+/** Poster edits and disposable sharing copies of local video history. */
+import { randomUUID } from 'node:crypto';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PATHS, unlinkGuarded } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { safeUnder, generateThumbnail, probeVideoDuration, probeVideoStreamInfo, findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
+import { getHistoryItem, mutateVideoHistory } from './history.js';
+
+function sourcePath(item) {
+ const path = item && safeUnder(PATHS.videos, item.filename);
+ if (!path) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });
+ return path;
+}
+
+export async function updateVideoPoster(id, atSec) {
+ let result;
+ let generated;
+ let previous;
+ try {
+ await mutateVideoHistory(async history => {
+ const item = history.find(item => item.id === id);
+ const path = sourcePath(item);
+ let posterSec;
+ if (atSec !== null) {
+ const [duration, stream] = await Promise.all([probeVideoDuration(path), probeVideoStreamInfo(path)]);
+ if (!duration) throw new ServerError('Could not read video duration', { status: 422 });
+ posterSec = Math.max(0, Math.min(atSec, duration - (stream.fps > 0 ? 1 / stream.fps : Math.min(duration, 0.001))));
+ }
+ // A new basename prevents browser caching and leaves the old poster intact on failure.
+ generated = await generateThumbnail(path, `${id}-poster-${randomUUID()}`, { atSec: posterSec });
+ if (!generated) throw new ServerError('Could not generate poster', { status: 422 });
+ previous = item.thumbnail;
+ item.thumbnail = generated;
+ if (posterSec === undefined) delete item.posterSec;
+ else item.posterSec = posterSec;
+ result = { id, thumbnail: generated, posterSec: posterSec ?? null };
+ return history;
+ });
+ } catch (error) {
+ if (generated) await unlinkGuarded(join(PATHS.videoThumbnails, generated)).catch(() => {});
+ throw error;
+ }
+ const old = previous && safeUnder(PATHS.videoThumbnails, previous);
+ if (old) await unlinkGuarded(old).catch(() => {});
+ return result;
+}
+
+export async function createSharingCopy(id, { signal } = {}) {
+ const item = await getHistoryItem(id);
+ const source = sourcePath(item);
+ const poster = item.thumbnail && safeUnder(PATHS.videoThumbnails, item.thumbnail);
+ if (!poster) throw new ServerError('Set a poster before downloading for sharing', { status: 422 });
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg is unavailable', { status: 503 });
+ const dir = await mkdtemp(join(tmpdir(), 'portos-share-'));
+ const path = join(dir, 'sharing.mp4');
+ const cleanup = () => rm(dir, { recursive: true, force: true });
+ try {
+ const result = await runFfmpegProcess({ bin: ffmpeg, signal, args: [
+ '-i', source, '-i', poster,
+ '-filter_complex', "[0:v:0][1:v:0]overlay=enable='eq(n,0)':eof_action=repeat[v]",
+ '-map', '[v]', '-map', '0:a?', '-c:v', 'libx264', '-crf', '18',
+ '-fps_mode', 'passthrough', '-c:a', 'copy', '-movflags', '+faststart', '-y', path,
+ ] });
+ if (!result.ok) throw new ServerError('Could not prepare sharing download', { status: 422 });
+ return { path, filename: `sharing-${item.id}.mp4`, cleanup };
+ } catch (error) {
+ await cleanup();
+ throw error;
+ }
+}
diff --git a/server/services/videoGen/poster.test.js b/server/services/videoGen/poster.test.js
new file mode 100644
index 0000000000..a72f831974
--- /dev/null
+++ b/server/services/videoGen/poster.test.js
@@ -0,0 +1,64 @@
+import { beforeAll, afterAll, expect, it, vi } from 'vitest';
+import { mkdir, rm, readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+const state = vi.hoisted(() => ({ root: '', history: [] }));
+vi.mock('../../lib/fileUtils.js', async original => {
+ const actual = await original();
+ const { mkdtemp } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ state.root = await mkdtemp(join(tmpdir(), 'poster-test-'));
+ return { ...actual, PATHS: { ...actual.PATHS, videos: state.root, videoThumbnails: join(state.root, 'thumbs') } };
+});
+vi.mock('./history.js', () => ({
+ getHistoryItem: async id => state.history.find(item => item.id === id),
+ mutateVideoHistory: async mutate => { state.history = await mutate(structuredClone(state.history)); },
+}));
+import { updateVideoPoster, createSharingCopy } from './poster.js';
+import { findFfmpeg, findFfprobe, probeFrameCount, probeVideoDuration } from '../../lib/ffmpeg.js';
+const exec = promisify(execFile);
+let ffmpeg;
+beforeAll(async () => {
+ ffmpeg = await findFfmpeg();
+ if (!ffmpeg || !await findFfprobe()) { ffmpeg = null; return; }
+ await mkdir(join(state.root, 'thumbs'));
+ await exec(ffmpeg, ['-f', 'lavfi', '-i', 'testsrc2=s=64x64:r=10:d=15', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=15', '-c:v', 'libx264', '-c:a', 'aac', '-y', join(state.root, 'example.mp4')]);
+ state.history = [{ id: 'example', filename: 'example.mp4', prompt: 'Example clip' }];
+}, 30000);
+afterAll(async () => { await rm(state.root, { recursive: true, force: true }); });
+it('persists a playhead poster, exports only a changed first frame with identical timing and audio, and resets', async context => {
+ if (!ffmpeg) context.skip();
+ const source = join(state.root, 'example.mp4');
+ const original = await readFile(source);
+ const updated = await updateVideoPoster('example', 12.4);
+ expect(state.history[0]).toMatchObject({ posterSec: 12.4, thumbnail: updated.thumbnail, prompt: 'Example clip' });
+ const copy = await createSharingCopy('example');
+ try {
+ expect(await probeFrameCount(copy.path)).toBe(await probeFrameCount(source));
+ expect(await probeVideoDuration(copy.path)).toBe(await probeVideoDuration(source));
+ const decode = async (path, args) => (await exec(ffmpeg, ['-v', 'error', '-i', path, ...args, '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { encoding: 'buffer', maxBuffer: 4 * 1024 * 1024 })).stdout;
+ const poster = await decode(join(state.root, 'thumbs', updated.thumbnail), ['-frames:v', '1']);
+ const first = await decode(copy.path, ['-frames:v', '1']);
+ const mae = (a,b) => a.reduce((sum,value,i) => sum + Math.abs(value-b[i]), 0) / a.length;
+ expect(first.length).toBe(poster.length);
+ expect(mae(first, poster)).toBeLessThan(8);
+ const tail = ['-vf', 'select=gte(n\\,1)', '-fps_mode', 'passthrough'];
+ expect(mae(await decode(copy.path, tail), await decode(source, tail))).toBeLessThan(8);
+ const audio = async path => (await exec(ffmpeg, ['-v', 'error', '-i', path, '-map', '0:a:0', '-c:a', 'copy', '-f', 'adts', '-'], { encoding: 'buffer', maxBuffer: 4 * 1024 * 1024 })).stdout;
+ expect(await audio(copy.path)).toEqual(await audio(source));
+ expect(await readFile(source)).toEqual(original);
+ } finally { await copy.cleanup(); }
+ const clamped = await updateVideoPoster('example', 100);
+ expect(clamped.posterSec).toBeCloseTo(14.9);
+ const reset = await updateVideoPoster('example', null);
+ expect(reset.posterSec).toBeNull();
+ expect(state.history[0]).not.toHaveProperty('posterSec');
+ expect(reset.thumbnail).not.toBe(updated.thumbnail);
+}, 30000);
+it('rejects missing and unsafe history entries without creating a download', async () => {
+ await expect(updateVideoPoster('missing', 1)).rejects.toMatchObject({ status: 404 });
+ state.history.push({ id: 'unsafe', filename: '../private.mp4', thumbnail: '../private.jpg' });
+ await expect(createSharingCopy('unsafe')).rejects.toMatchObject({ status: 404 });
+});
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index 82c5a4696d..f8b746913b 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -618,7 +618,7 @@ export function cancelRender(jobId) {
return true;
}
-export async function renderProject(projectId) {
+export async function renderProject(projectId, { posterSec } = {}) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -741,7 +741,7 @@ export async function renderProject(projectId) {
job.status = 'complete';
// The encode args already include -movflags +faststart, so no separate
// remux pass is needed here.
- const thumb = await generateThumbnail(outputPath, jobId);
+ const thumb = await generateThumbnail(outputPath, jobId, { atSec: posterSec });
// Push to existing video history with a timelineProjectId flag so the
// Media History page picks it up alongside generated clips.