Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): address adversarial review findings on video conditioning media

Lincoln Stein22b656382c16
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
index 9b13d76e5b..3d3e6b55a9 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
@@ -242,6 +242,44 @@ describe('compileVideoGraph — Wan 2.2', () => {
expect(nodeOfType(midClip, 'extract_video_range').end_frame).toBe(40);
});
+ it('compiles ceiling-touching trim STARTS as negative indices too — a keep-the-tail trim survives estimate overshoot', () => {
+ const model = wanModel('i2v_a14b');
+ // numFrames 81: startFrame 77 has tail offset 3 (→ -4), endFrame 79 has
+ // tail offset 1 (→ -2). Both inside the tail window, order preserved.
+ const tailTrim = compileVideoGraph(
+ settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, endFrame: 79, startFrame: 77 } }),
+ model
+ ).backendGraph;
+
+ expect(nodeOfType(tailTrim, 'extract_video_range')).toMatchObject({ end_frame: -2, start_frame: -4 });
+
+ // Tail offset 4 is the first index OUTSIDE the window: it stays a
+ // positive literal (converting it would drift mid-clip picks when the
+ // estimate overshoots), even when the end still converts.
+ const boundary = compileVideoGraph(
+ settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, endFrame: 78, startFrame: 76 } }),
+ model
+ ).backendGraph;
+
+ expect(nodeOfType(boundary, 'extract_video_range')).toMatchObject({ end_frame: -3, start_frame: 76 });
+ });
+
+ it('records the delivered fps in Wan metadata — the panel fps normally, the source clip fps for extend', () => {
+ const t2vModel = wanModel('t2v_a14b');
+ const t2v = compileVideoGraph(settingsFor(t2vModel, { fps: 20 }), t2vModel).backendGraph;
+
+ expect(nodeOfType(t2v, 'core_metadata')).toMatchObject({ fps: 20 });
+
+ // Extend inherits the source clip's (rounded) rate, not the panel setting.
+ const extendModel = wanModel('i2v_a14b');
+ const extend = compileVideoGraph(
+ settingsFor(extendModel, { fps: 20, sourceVideo: { ...SOURCE_VIDEO, fps: 23.7 } }),
+ extendModel
+ ).backendGraph;
+
+ expect(nodeOfType(extend, 'core_metadata')).toMatchObject({ fps: 24 });
+ });
+
it('refuses a trim shorter than two frames', () => {
const model = wanModel('i2v_a14b');
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.ts
index c3f14a84a5..ddfe3fe39b 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts
@@ -75,17 +75,24 @@ const addExtendScaffolding = (
) => {
// The panel's frame count is an estimate (duration × fps; the records store
// no exact count, and VFR uploads can overshoot by a frame or two). A trim
- // end near the estimated ceiling therefore compiles as a NEGATIVE index —
+ // bound near the estimated ceiling therefore compiles as a NEGATIVE index —
// resolved by the backend against the clip's REAL count — so "keep to the
- // end" can never land past it. Mid-clip picks stay positive: a negative
- // offset computed from an overshooting estimate would drift them instead.
- const tailOffset = sourceVideo.numFrames - 1 - sourceVideo.endFrame;
- const endFrameLiteral = tailOffset <= 3 ? -(tailOffset + 1) : sourceVideo.endFrame;
+ // end" can never land past it. Both bounds get the same treatment: a start
+ // in the tail window would otherwise stay a positive estimate-based index
+ // and land out of range exactly when the end's conversion saves it (the
+ // start is always below the end, so the pair keeps its order when both go
+ // negative). Mid-clip picks stay positive: a negative offset computed from
+ // an overshooting estimate would drift them instead.
+ const toTailAwareIndex = (frame: number): number => {
+ const tailOffset = sourceVideo.numFrames - 1 - frame;
+
+ return tailOffset <= 3 ? -(tailOffset + 1) : frame;
+ };
const extract = addNode(graph, {
- end_frame: endFrameLiteral,
+ end_frame: toTailAwareIndex(sourceVideo.endFrame),
id: 'source_video',
is_intermediate: true,
- start_frame: sourceVideo.startFrame,
+ start_frame: toTailAwareIndex(sourceVideo.startFrame),
type: 'extract_video_range',
use_cache: false,
video: { video_name: sourceVideo.video_name },
@@ -157,7 +164,16 @@ const addVideoMetadata = ({
width,
...(settings.firstFrameImage ? { first_frame_image: toImageField(settings.firstFrameImage) } : {}),
...(settings.lastFrameImage ? { last_frame_image: toImageField(settings.lastFrameImage) } : {}),
- ...(settings.sourceVideo ? { source_video: { video_name: settings.sourceVideo.video_name } } : {}),
+ // The trim bounds ride along as plain extras (core_metadata allows extra
+ // fields): without them, recall could only rebuild the clip with its
+ // default trim and the extension would start from the wrong frame.
+ ...(settings.sourceVideo
+ ? {
+ source_video: { video_name: settings.sourceVideo.video_name },
+ source_video_end_frame: settings.sourceVideo.endFrame,
+ source_video_start_frame: settings.sourceVideo.startFrame,
+ }
+ : {}),
...(activeLoras.length
? { loras: activeLoras.map((lora) => ({ model: toModelIdentifier(lora.model), weight: lora.weight })) }
: {}),
@@ -309,6 +325,11 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Ba
const metadata = addVideoMetadata({
extras: {
cfg_scale: settings.cfgScale,
+ // The delivered frame rate: the extension inherits the source clip's
+ // (rounded, mirroring the float_to_int node the graph wires), every
+ // other mode uses the panel's fps setting. Without this, fps would be
+ // the one user-settable Wan parameter recall could never restore.
+ fps: extendParts && settings.sourceVideo ? Math.round(settings.sourceVideo.fps) : settings.fps,
...(policy.ui.cfgLowNoiseVisible && settings.cfgScaleLowNoise !== null
? { guidance_scale_low_noise: settings.cfgScaleLowNoise }
: {}),
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
index ac118d77c0..e19f3b2fbd 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -255,4 +255,23 @@ describe('clearDeletedVideoMedia', () => {
expect(clipCleared.sourceVideo).toBeNull();
});
+
+ it('clears a reference the exclusion masking would hide from a normalized snapshot', () => {
+ // A raw store can hold BOTH slots (a rollback race); normalization would
+ // mask the source video, so the sweep must run on the raw values or the
+ // masked reference dangles past the delete.
+ const rawBoth = { ...createSettings({ firstFrameImage: FIRST_FRAME }), sourceVideo: SOURCE_VIDEO } as Record<
+ string,
+ unknown
+ >;
+ const cleared = clearDeletedVideoMedia(rawBoth, new Set(), new Set(['clip.mp4']));
+
+ expect(cleared.sourceVideo).toBeNull();
+ expect(cleared.firstFrameImage).toEqual(FIRST_FRAME);
+
+ // Junk in a slot never throws — the guards ignore non-media shapes.
+ const junk = { firstFrameImage: 'nonsense', lastFrameImage: 7, sourceVideo: {} } as Record<string, unknown>;
+
+ expect(clearDeletedVideoMedia(junk, new Set(['nonsense']), new Set())).toBe(junk);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 9cd112c900..deddd4db0e 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -306,24 +306,32 @@ export const MIN_VIDEO_TRIM_FRAMES = 2;
/**
* Clears conditioning media that no longer exists in the gallery. Returns the
* input object untouched when nothing changes.
+ *
+ * Deliberately operates on RAW widget values rather than a normalized
+ * snapshot: normalization resolves the first-frame/initial-video exclusion by
+ * masking one slot, and a masked reference would silently survive the
+ * deletion sweep — a dangling media name waiting to resurface.
*/
-export const clearDeletedVideoMedia = (
- values: VideoSettings,
+export const clearDeletedVideoMedia = <T extends object>(
+ values: T,
removedImageNames: ReadonlySet<string>,
removedVideoNames: ReadonlySet<string>
-): VideoSettings => {
- const clearFirst = values.firstFrameImage !== null && removedImageNames.has(values.firstFrameImage.image_name);
- const clearLast = values.lastFrameImage !== null && removedImageNames.has(values.lastFrameImage.image_name);
- const clearSource = values.sourceVideo !== null && removedVideoNames.has(values.sourceVideo.video_name);
+): T => {
+ const slots = values as { firstFrameImage?: unknown; lastFrameImage?: unknown; sourceVideo?: unknown };
+ const clearFirst = isImageWithDims(slots.firstFrameImage) && removedImageNames.has(slots.firstFrameImage.image_name);
+ const clearLast = isImageWithDims(slots.lastFrameImage) && removedImageNames.has(slots.lastFrameImage.image_name);
+ const clearSource = isVideoSourceClip(slots.sourceVideo) && removedVideoNames.has(slots.sourceVideo.video_name);
if (!clearFirst && !clearLast && !clearSource) {
return values;
}
+ // The spread widens the cleared keys to `null`; T itself declares them
+ // nullable in every real shape (VideoSettings, raw widget values).
return {
...values,
...(clearFirst ? { firstFrameImage: null } : {}),
...(clearLast ? { lastFrameImage: null } : {}),
...(clearSource ? { sourceVideo: null } : {}),
- };
+ } as T;
};
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
index c35915443b..b16c59956f 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
@@ -673,6 +673,21 @@ describe('getVideoValidationReasons', () => {
expect(getVideoValidationReasons(model, settings)).toContainEqual(expect.stringContaining('cannot be combined'));
});
+ it('rejects a Wan extension whose source clip frame rate falls outside 1-120 fps', () => {
+ const model = wanModel('i2v_a14b', 'diffusers');
+
+ // wan_l2v/video_concat accept 1-120; an out-of-range clip would fail only
+ // AFTER the denoise. A slow-mo clip and an unprobeable sub-1 fps rate both
+ // block up front; an ordinary clip raises nothing.
+ expect(
+ getVideoValidationReasons(model, settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, fps: 240 } }))
+ ).toContainEqual(expect.stringContaining('1-120 fps'));
+ expect(
+ getVideoValidationReasons(model, settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, fps: 0.3 } }))
+ ).toContainEqual(expect.stringContaining('1-120 fps'));
+ expect(getVideoValidationReasons(model, settingsFor(model, { sourceVideo: SOURCE_VIDEO }))).toEqual([]);
+ });
+
it('validates frames, fps, and steps against the matrix', () => {
const wan = wanModel('t2v_a14b', 'diffusers');
const h3 = h3Model();
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
index 827fe9a58c..391ed76445 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
@@ -1122,6 +1122,20 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide
if (numFrames < MIN_VIDEO_TRIM_FRAMES) {
reasons.push('The initial video is too short to extend.');
}
+
+ // A Wan extension inherits the source clip's frame rate, and the backend's
+ // wan_l2v/video_concat nodes accept 1-120 fps. An out-of-range clip (a
+ // 240 fps slow-mo, an unprobeable sub-1 fps rate) would enqueue, run the
+ // whole denoise, then die assigning the fps — so block it here instead.
+ if (model.base === 'wan') {
+ const inheritedFps = Math.round(settings.sourceVideo.fps);
+
+ if (inheritedFps < 1 || inheritedFps > 120) {
+ reasons.push(
+ `The initial video's frame rate (${settings.sourceVideo.fps} fps) is outside the 1-120 fps range Wan extension supports.`
+ );
+ }
+ }
}
if (!getVideoDimensions(model, settings)) {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts
index 8dfbf0866f..a9142bc459 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts
@@ -168,6 +168,75 @@ describe('gallery optimistic rollback against the real reducer', () => {
expect(getProjectWidgetValues(getProject(restored, projectId), 'upscale').inputImage).toEqual(upscaleInputImage);
});
+ it('does not restore a video slot whose exclusive rival was claimed while the delete was in flight', () => {
+ const seeded = seedProjectWithItem();
+ const projectId = seeded.projectId;
+ const firstFrame = { height: 480, image_name: 'a.png', width: 832 };
+ const sourceClip = {
+ endFrame: 79,
+ fps: 16,
+ height: 480,
+ numFrames: 81,
+ startFrame: 0,
+ video_name: 'clip.mp4',
+ width: 832,
+ };
+ const state = workbenchReducer(seeded.state, {
+ projectId,
+ type: 'patchWidgetValues',
+ values: { firstFrameImage: firstFrame },
+ widgetId: 'video',
+ });
+
+ const before = captureGalleryWidgetKeyValues(state.projects);
+ const afterRemoval = workbenchReducer(state, { itemKeys: ['image:a.png'], type: 'removeGalleryItems' });
+
+ // Sanity: the optimistic removal cleared the video slot.
+ expect(getProjectWidgetValues(getProject(afterRemoval, projectId), 'video').firstFrameImage).toBeNull();
+
+ const entries = diffGalleryWidgetKeyValues(before, afterRemoval.projects);
+
+ // The slot freed up, so the user drops an initial video — exactly the
+ // patch `setSourceVideo` makes — before the server delete fails.
+ const claimed = workbenchReducer(afterRemoval, {
+ projectId,
+ type: 'patchWidgetValues',
+ values: { firstFrameImage: null, sourceVideo: sourceClip },
+ widgetId: 'video',
+ });
+
+ const patches = selectRestorableGalleryWidgetPatches(entries, claimed.projects);
+ const restored = applyRestorePatches(claimed, patches);
+ const videoValues = getProjectWidgetValues(getProject(restored, projectId), 'video');
+
+ // Restoring the first frame would recreate the forbidden
+ // first-frame+initial-video pair; the restore loses.
+ expect(videoValues.firstFrameImage).toBeNull();
+ expect(videoValues.sourceVideo).toEqual(sourceClip);
+ // Unrelated fields still restore normally.
+ expect(getProjectWidgetValues(getProject(restored, projectId), 'gallery').selectedImage).toEqual(galleryItem);
+ });
+
+ it('still restores a cleared video slot when its rival stayed empty', () => {
+ const seeded = seedProjectWithItem();
+ const projectId = seeded.projectId;
+ const firstFrame = { height: 480, image_name: 'a.png', width: 832 };
+ const state = workbenchReducer(seeded.state, {
+ projectId,
+ type: 'patchWidgetValues',
+ values: { firstFrameImage: firstFrame },
+ widgetId: 'video',
+ });
+
+ const before = captureGalleryWidgetKeyValues(state.projects);
+ const afterRemoval = workbenchReducer(state, { itemKeys: ['image:a.png'], type: 'removeGalleryItems' });
+ const entries = diffGalleryWidgetKeyValues(before, afterRemoval.projects);
+ const patches = selectRestorableGalleryWidgetPatches(entries, afterRemoval.projects);
+ const restored = applyRestorePatches(afterRemoval, patches);
+
+ expect(getProjectWidgetValues(getProject(restored, projectId), 'video').firstFrameImage).toEqual(firstFrame);
+ });
+
it('restores nothing when the optimistic removal did not actually change anything', () => {
const { state } = seedProjectWithItem();
const before = captureGalleryWidgetKeyValues(state.projects);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
index ee67c46736..bbd4026ce9 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts
@@ -36,6 +36,20 @@ const TRACKED_GALLERY_REMOVAL_FIELDS: ReadonlyArray<{ key: string; widgetId: Wid
{ key: 'sourceVideo', widgetId: 'video' },
];
+/**
+ * Widget slots that are mutually exclusive by design (the video widget's
+ * first-frame XOR initial-video rule, enforced by its setters). A rollback
+ * restore is the one write path that bypasses those setters: after our
+ * optimistic clear, the user may have claimed the RIVAL slot, and restoring
+ * this one would recreate a pair no setter can produce — normalization then
+ * masks one of the two, which reads as a silently wrong generation mode.
+ * When the rival slot is occupied, the restore loses.
+ */
+const EXCLUSIVE_RIVAL_FIELDS: ReadonlyArray<{ key: string; rivalKey: string; widgetId: WidgetTypeId }> = [
+ { key: 'firstFrameImage', rivalKey: 'sourceVideo', widgetId: 'video' },
+ { key: 'sourceVideo', rivalKey: 'firstFrameImage', widgetId: 'video' },
+];
+
const trackedFieldKey = (projectId: string, widgetId: WidgetTypeId, key: string): string =>
`${projectId}:${widgetId}:${key}`;
@@ -139,6 +153,17 @@ export const selectRestorableGalleryWidgetPatches = (
liveEntries,
(candidate) => getProjectWidgetValues(projectsById.get(candidate.projectId)!, candidate.widgetId)[candidate.key]
)) {
+ const rival = EXCLUSIVE_RIVAL_FIELDS.find((field) => field.widgetId === entry.widgetId && field.key === entry.key);
+ const isOccupied = (value: unknown): boolean => value !== null && value !== undefined;
+
+ if (
+ rival &&
+ isOccupied(entry.before) &&
+ isOccupied(getProjectWidgetValues(projectsById.get(entry.projectId)!, entry.widgetId)[rival.rivalKey])
+ ) {
+ continue;
+ }
+
const groupKey = widgetGroupKey(entry.projectId, entry.widgetId);
const patch = patchesByGroup.get(groupKey) ?? { projectId: entry.projectId, values: {}, widgetId: entry.widgetId };
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 2cbd44c9a0..2689c6548d 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -122,7 +122,6 @@ import {
compileVideoGraph,
getVideoDimensions,
getVideoWidgetValidationReasons,
- normalizeVideoSettings,
normalizeVideoWidgetValues,
resolveVideoSeed,
syncVideoWidgetValuesWithModels,
@@ -2629,28 +2628,12 @@ const removeGalleryItemsFromAllProjects = (
return { ...clearDeletedUpscaleInput(values, removedImageNames) };
});
- const withoutVideoMedia = updateProjectWidgetValues(withoutUpscaleInput, 'video', (rawValues) => {
- const values = normalizeVideoSettings(rawValues);
-
- if (!values) {
- return rawValues;
- }
-
- const cleared = clearDeletedVideoMedia(values, removedImageNames, removedVideoNames);
-
- if (cleared === values) {
- return rawValues;
- }
-
- // Patch only the cleared media slots: spreading the whole normalized
- // settings would rewrite every other key to its normalized form.
- return {
- ...rawValues,
- ...(cleared.firstFrameImage !== values.firstFrameImage ? { firstFrameImage: null } : {}),
- ...(cleared.lastFrameImage !== values.lastFrameImage ? { lastFrameImage: null } : {}),
- ...(cleared.sourceVideo !== values.sourceVideo ? { sourceVideo: null } : {}),
- };
- });
+ // The sweep runs against the RAW slots: normalizing first would let a
+ // reference masked by the first-frame/initial-video exclusion survive the
+ // deletion and resurface later as a dangling media name.
+ const withoutVideoMedia = updateProjectWidgetValues(withoutUpscaleInput, 'video', (rawValues) =>
+ clearDeletedVideoMedia(rawValues, removedImageNames, removedVideoNames)
+ );
didChange ||= withoutVideoMedia !== project;
return withoutVideoMedia;