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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): budget the reference-extend tail window against the frame count
Lincoln Steinb76d981fbe36
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex ed1267fee4..237b103703 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3165,7 +3165,7 @@"referenceDetailMax": "Max detail (2048px, slower)","referenceExtendCapFull": "No continuity reference added","referenceExtendCapFullDescription": "All 3 video reference slots are in use, so the extension has no reference sampling the initial video. Remove a video reference to add one.",- "referenceExtendHelp": "The generated video is appended to this clip at its End Frame. A linked video reference samples the last ~5 seconds of the clip (141 frames at 24 fps, scaled to its frame rate) before that cutpoint for continuity — its trim re-derives whenever the cutpoints change.",+ "referenceExtendHelp": "The generated video is appended to this clip at its End Frame. A linked video reference samples up to the last ~5 seconds before that cutpoint for continuity — never more than the generated clip's own length, since the model discards the overrun at the seam. Its trim re-derives whenever the cutpoints or the frame count change.","referenceFromInitialVideo": "Initial video","references": "References","referencesHelp": "Up to 3 videos and 9 images condition the generation, in order — reordering references changes the result. A video reference can contribute its image track, its soundtrack, or both.",diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex bc0f042a6b..24cb085fff 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest';import type { VideoSettings } from './types';+import { MINIMAX_H3_NUM_FRAMES_CHOICES } from './dimensions';import {applyReferenceExtendSourceVideo,+ applyReferenceExtendNumFrames,clearDeletedVideoMedia,cloneVideoWidgetValues,createVideoSourceClip,@@ -384,28 +386,71 @@ describe('references', () => {});describe('reference-extend linkage', () => {- const longSource = { ...SOURCE_VIDEO, endFrame: 400, fps: 24, numFrames: 402, video_name: 'long.mp4' };-- it('derives the tail trim: 141 frames at 24 fps ending at the cutpoint, clamped at 0', () => {- expect(deriveReferenceExtendClip(longSource)).toMatchObject({ endFrame: 400, startFrame: 260 });+ // H3 generates at a fixed 24 fps; SOURCE_VIDEO runs at 16, so the two rates+ // are exercised separately.+ const longSource = { ...SOURCE_VIDEO, endFrame: 400, numFrames: 402, video_name: 'long.mp4' };+ const source24 = { ...longSource, fps: 24 };+ // The panel's default; every choice is on the 17n+5 grid.+ const FRAMES = 141;++ it('derives the tail trim: the window ending at the cutpoint, clamped at 0', () => {+ expect(deriveReferenceExtendClip(source24, FRAMES)).toMatchObject({ endFrame: 400, startFrame: 260 });// Shorter than the tail window: sample from the clip's own start.- expect(deriveReferenceExtendClip(SOURCE_VIDEO)).toMatchObject({ endFrame: 79, startFrame: 0 });+ expect(deriveReferenceExtendClip({ ...SOURCE_VIDEO, fps: 24 }, FRAMES)).toMatchObject({+ endFrame: 79,+ startFrame: 0,+ });+ });++ it('budgets the window against the generated frame count', () => {+ // `normalize_reference_video_frames` truncates a reference to the generated+ // frame count keeping the FRONT, so a window longer than the generation+ // loses its tail — the frames at the seam. It must never outrun the count.+ expect(deriveReferenceExtendClip(source24, 124)).toMatchObject({ endFrame: 400, startFrame: 277 });+ expect(deriveReferenceExtendClip(source24, 90)).toMatchObject({ endFrame: 400, startFrame: 311 });+ // Above the tail window the budget stops binding: ~5s of lead-in is the cap.+ expect(deriveReferenceExtendClip(source24, 345)).toMatchObject({ endFrame: 400, startFrame: 260 });+ });++ it('lands the window ON the 17n+5 grid the backend keeps, at every source rate', () => {+ // The real test of the window: run it through ALL THREE backend rules.+ // `resample_video_frame_repeats` onto 24 fps, `frames[:num_frames]`, then+ // `snap_reference_num_frames` DOWN to 17n+5 — every one of which cuts the+ // seam end. Rounding the fps conversion DOWN satisfied the first two and+ // failed the third, losing 17 frames at 23.976 fps at every frame count.+ const resample = (n: number, fps: number) => Math.floor((n * 24) / fps + 0.5);+ const snapDown = (n: number) => Math.max(1, Math.floor((n - 5) / 17)) * 17 + 5;++ for (const fps of [10, 12, 15, 16, 18, 20, 23.976, 24, 25, 29.97, 30, 60]) {+ for (const numFrames of MINIMAX_H3_NUM_FRAMES_CHOICES) {+ const clip = deriveReferenceExtendClip({ ...longSource, fps }, numFrames);+ const budget = Math.min(141, numFrames);+ const kept = snapDown(Math.min(resample(clip.endFrame - clip.startFrame + 1, fps), numFrames));++ expect({ fps, kept, numFrames }).toEqual({ fps, kept: budget, numFrames });+ }+ }});- it('scales the tail window to the source frame rate — a constant duration, not a constant frame count', () => {- // 16 fps: round(141/24 * 16) = 94 frames of the same ~5.9 s.- expect(deriveReferenceExtendClip({ ...longSource, fps: 16 })).toMatchObject({ endFrame: 400, startFrame: 307 });- // 30 fps: round(141/24 * 30) = 176 frames.- expect(deriveReferenceExtendClip({ ...longSource, fps: 30 })).toMatchObject({ endFrame: 400, startFrame: 225 });- // A degenerate recorded rate falls back to the 24 fps window.- expect(deriveReferenceExtendClip({ ...longSource, fps: 0 })).toMatchObject({ endFrame: 400, startFrame: 260 });+ it('converts the window into the source clip fps', () => {+ // 141 frames of 24 fps material is 94 frames of a 16 fps clip — the same+ // 5.875s of wall time, which is what the tail window actually means.+ expect(deriveReferenceExtendClip(longSource, FRAMES)).toMatchObject({ endFrame: 400, startFrame: 307 });+ // A clip whose probe recorded no usable rate falls back to a no-op+ // conversion rather than collapsing to the 2-frame floor.+ expect(deriveReferenceExtendClip({ ...longSource, fps: 0 }, FRAMES)).toMatchObject({ startFrame: 260 });+ expect(deriveReferenceExtendClip({ ...longSource, fps: -30 }, FRAMES)).toMatchObject({ startFrame: 260 });});- it('prepends a linked video+audio reference and re-derives it on cutpoint changes', () => {- const added = applyReferenceExtendSourceVideo([IMAGE_REFERENCE], longSource, 3);+ it('appends a linked video+audio reference and re-derives it on cutpoint changes', () => {+ // Appended, not prepended: request order is rotary order and the generated+ // rows continue from the LAST reference block, so the continuity anchor+ // has to be the final entry.+ const added = applyReferenceExtendSourceVideo([IMAGE_REFERENCE], source24, 3, FRAMES);expect(added).toHaveLength(2);- expect(added[0]).toMatchObject({+ expect(added[0]).toBe(IMAGE_REFERENCE);+ expect(added[1]).toMatchObject({clip: { endFrame: 400, startFrame: 260, video_name: 'long.mp4' },conditioning: 'video_audio',fromSourceVideo: true,@@ -415,31 +460,31 @@ describe('reference-extend linkage', () => {// The user tunes the conditioning, then moves the cutpoint: the trim// re-derives, the position and conditioning survive.const tuned = added.map((entry, index) =>- index === 0 && entry.kind === 'video' ? { ...entry, conditioning: 'video' as const } : entry+ index === 1 && entry.kind === 'video' ? { ...entry, conditioning: 'video' as const } : entry);- const retrimmed = applyReferenceExtendSourceVideo(tuned, { ...longSource, endFrame: 300 }, 3);+ const retrimmed = applyReferenceExtendSourceVideo(tuned, { ...source24, endFrame: 300 }, 3, FRAMES);- expect(retrimmed[0]).toMatchObject({+ expect(retrimmed[1]).toMatchObject({clip: { endFrame: 300, startFrame: 160 },conditioning: 'video',fromSourceVideo: true,});- expect(retrimmed[1]).toBe(added[1]);+ expect(retrimmed[0]).toBe(added[0]);});it('clearing the initial video removes only the linked reference (identity-preserving when none)', () => {- const list = applyReferenceExtendSourceVideo([VIDEO_REFERENCE, IMAGE_REFERENCE], longSource, 3);+ const list = applyReferenceExtendSourceVideo([VIDEO_REFERENCE, IMAGE_REFERENCE], source24, 3, FRAMES);- expect(applyReferenceExtendSourceVideo(list, null, 3)).toEqual([VIDEO_REFERENCE, IMAGE_REFERENCE]);+ expect(applyReferenceExtendSourceVideo(list, null, 3, FRAMES)).toEqual([VIDEO_REFERENCE, IMAGE_REFERENCE]);const unlinked = [VIDEO_REFERENCE, IMAGE_REFERENCE];- expect(applyReferenceExtendSourceVideo(unlinked, null, 3)).toBe(unlinked);+ expect(applyReferenceExtendSourceVideo(unlinked, null, 3, FRAMES)).toBe(unlinked);});it('adopts an unflagged reference for the same clip instead of duplicating it (recall shape)', () => {const recalled = { ...VIDEO_REFERENCE, clip: { ...VIDEO_REFERENCE.clip, video_name: 'long.mp4' } };- const result = applyReferenceExtendSourceVideo([IMAGE_REFERENCE, recalled], longSource, 3);+ const result = applyReferenceExtendSourceVideo([IMAGE_REFERENCE, recalled], source24, 3, FRAMES);expect(result).toHaveLength(2);expect(result[1]).toMatchObject({@@ -452,13 +497,13 @@ describe('reference-extend linkage', () => {// User: linked ref for clip A, plus their OWN hand-trimmed reference for// clip B sitting above it. Swapping the Initial Video to clip B must// update the FLAGGED entry — not rewrite the user's B reference.- const linkedA = applyReferenceExtendSourceVideo([], longSource, 3)[0];+ const linkedA = applyReferenceExtendSourceVideo([], source24, 3, FRAMES)[0];const handTrimmedB = {...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, endFrame: 200, numFrames: 300, startFrame: 100, video_name: 'b.mp4' },};- const sourceB = { ...longSource, endFrame: 290, numFrames: 300, video_name: 'b.mp4' };- const result = applyReferenceExtendSourceVideo([handTrimmedB, linkedA!], sourceB, 3);+ const sourceB = { ...source24, endFrame: 290, numFrames: 300, video_name: 'b.mp4' };+ const result = applyReferenceExtendSourceVideo([handTrimmedB, linkedA!], sourceB, 3, FRAMES);expect(result[0]).toBe(handTrimmedB);expect(result[1]).toMatchObject({@@ -475,6 +520,40 @@ describe('reference-extend linkage', () => {{ ...VIDEO_REFERENCE, clip: { ...VIDEO_REFERENCE.clip, video_name: 'c.mp4' } },];- expect(applyReferenceExtendSourceVideo(full, longSource, 3)).toBe(full);+ expect(applyReferenceExtendSourceVideo(full, source24, 3, FRAMES)).toBe(full);+ });++ it('applyReferenceExtendNumFrames re-derives the window and is idempotent', () => {+ const linked = applyReferenceExtendSourceVideo([IMAGE_REFERENCE], source24, 3, FRAMES);++ expect(linked[1]).toMatchObject({ clip: { startFrame: 260 } });++ const at124 = applyReferenceExtendNumFrames(linked, 124);++ expect(at124[1]).toMatchObject({ clip: { endFrame: 400, startFrame: 277 }, fromSourceVideo: true });+ expect(at124[0]).toBe(linked[0]);+ // Idempotent, and identity-preserving when nothing moves.+ expect(applyReferenceExtendNumFrames(at124, 124)).toBe(at124);+ expect(applyReferenceExtendNumFrames(linked, FRAMES)).toBe(linked);+ });++ it('applyReferenceExtendNumFrames does not ratchet: the window re-widens', () => {+ // The Frames number input emits a value per keystroke, unclamped, so typing+ // "345" arrives as 3, then 34, then 345. A shrink-only rule would pin the+ // window at the 3-frame budget for the rest of the session.+ const linked = applyReferenceExtendSourceVideo([], source24, 3, 345);+ const typed = [3, 34, 345].reduce(applyReferenceExtendNumFrames, linked);++ expect(typed[0]).toMatchObject({ clip: { endFrame: 400, startFrame: 260 } });+ // And a slider dragged down and back up ends where it started.+ expect([90, 124, 345].reduce(applyReferenceExtendNumFrames, linked)[0]).toMatchObject({+ clip: { startFrame: 260 },+ });+ });++ it('applyReferenceExtendNumFrames leaves unlinked references alone', () => {+ const unlinked = [VIDEO_REFERENCE, IMAGE_REFERENCE];++ expect(applyReferenceExtendNumFrames(unlinked, 90)).toBe(unlinked);});});diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 0822cca15c..de4da8cca4 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -26,6 +26,8 @@ import type {WanTargetResolution,} from './types';+import { MINIMAX_H3_FPS } from './dimensions';+const isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object';const hasFiniteNumber = (record: Record<string, unknown>, key: string): boolean =>@@ -387,34 +389,99 @@ export const createVideoSourceClip = (item: {export const MIN_VIDEO_TRIM_FRAMES = 2;/**- * Frames the reference-extend tail reference samples ahead of the cutpoint,- * expressed at 24 fps: ~5s of lead-in, and exactly on the 17n+5 frame grid- * (17*8+5) so the backend's 24 fps resample + snap-down keeps all of it. The- * window is a DURATION — `deriveReferenceExtendClip` scales it to the source- * clip's own frame rate, so a 16 fps source samples 94 frames of the same- * ~5.9 s rather than 141 frames of ~8.8 s.+ * The MAXIMUM lead-in the reference-extend tail reference samples ahead of the+ * cutpoint, expressed at 24 fps: ~5s, and exactly on the 17n+5 frame grid+ * (17*8+5) so the backend's 24 fps resample + snap-down keeps all of it.+ *+ * The window is a DURATION — `deriveReferenceExtendClip` scales it to the+ * source clip's own frame rate, so a 16 fps source samples 94 frames of the+ * same ~5.9 s rather than 141 frames of ~8.8 s. It is also a CEILING, not a+ * fixed size: the generated frame count is the other bound, and the smaller of+ * the two wins.*/export const VIDEO_REFERENCE_EXTEND_TAIL_FRAMES = 141;-const VIDEO_REFERENCE_EXTEND_TAIL_FPS = 24;+/**+ * The tail reference's default trim: the frames right before the cutpoint,+ * sized so the backend keeps ALL of them.+ *+ * Three backend rules bound the window, and every one of them discards from+ * the END — the frames adjacent to the cutpoint, the only ones continuity+ * depends on. `normalize_reference_video_frames` resamples onto H3's fixed+ * 24 fps and truncates to the GENERATED frame count keeping the FRONT+ * (`frames[:num_frames]`); `encode_reference_video` then snaps what survives+ * DOWN to the `17n + 5` grid the video VAE encodes without padding.+ *+ * The budget is therefore `min(TAIL, numFrames)` frames of 24 fps material,+ * and both of those sit ON that grid already (141 = 17*8+5; every frame choice+ * is 90 + 17i). The conversion into the source clip's own frame space rounds+ * UP: overshooting is free, because the truncation cuts the window back to+ * exactly `numFrames` and the snap then keeps it whole, while undershooting+ * lands OFF the grid and the snap eats up to 16 frames at the seam. Rounding+ * down looks safer and is not — it cost 17 frames at 23.976 fps (NTSC film) at+ * every frame count on offer, and 17 at 16 fps at the 124-frame default.+ */+export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip, numFrames: number): VideoSourceClip => ({+ ...sourceVideo,+ endFrame: sourceVideo.endFrame,+ // Deliberately unclamped by the Initial Video's START cutpoint: the+ // reference samples the original clip for continuity, independent of which+ // portion the extension keeps.+ startFrame: referenceExtendStartFrame(sourceVideo, numFrames),+});-/** The tail reference's default trim: the `VIDEO_REFERENCE_EXTEND_TAIL_FRAMES`-at-24fps window before the cutpoint, in source frames. */-export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip): VideoSourceClip => {- const fps =- Number.isFinite(sourceVideo.fps) && sourceVideo.fps > 0 ? sourceVideo.fps : VIDEO_REFERENCE_EXTEND_TAIL_FPS;- const tailFrames = Math.max(- 1,- Math.round((VIDEO_REFERENCE_EXTEND_TAIL_FRAMES / VIDEO_REFERENCE_EXTEND_TAIL_FPS) * fps)- );+/** The tail window's start index — see `deriveReferenceExtendClip`. */+const referenceExtendStartFrame = (clip: VideoSourceClip, numFrames: number): number => {+ const budget = Number.isFinite(numFrames)+ ? Math.min(VIDEO_REFERENCE_EXTEND_TAIL_FRAMES, Math.trunc(numFrames))+ : VIDEO_REFERENCE_EXTEND_TAIL_FRAMES;+ // A clip whose probe recorded no usable rate: the backend resamples at the+ // rate it probes, so 24 — a no-op conversion — is the only safe assumption.+ // A zero or negative rate would otherwise collapse the window to the 2-frame+ // floor, which is below the 13 frames text conditioning needs.+ const fps = Number.isFinite(clip.fps) && clip.fps > 0 ? clip.fps : MINIMAX_H3_FPS;+ const tail = Math.max(MIN_VIDEO_TRIM_FRAMES, Math.ceil((budget * fps) / MINIMAX_H3_FPS));++ return Math.max(0, clip.endFrame - (tail - 1));+};- return {- ...sourceVideo,- endFrame: sourceVideo.endFrame,- // Deliberately unclamped by the Initial Video's START cutpoint: the- // reference samples the original clip for continuity, independent of- // which portion the extension keeps.- startFrame: Math.max(0, sourceVideo.endFrame - (tailFrames - 1)),- };+/**+ * Re-derives the linked tail reference's window for a generated frame count.+ *+ * The window is a function of that count, so a frame-count change has to move+ * it. This RE-DERIVES rather than shrinks-to-fit: a shrink-only rule ratchets.+ * The Frames number input emits a value per keystroke, unclamped, so typing+ * "345" passes through 3 — and a shrink-only window would collapse to 3 frames+ * and never come back, silently, for the rest of the session. Dragging the+ * slider down and back up does the same. Re-deriving is idempotent in+ * `numFrames`, so the values a keystroke or a drag passes through leave no+ * trace.+ *+ * The cost is that a hand-tuned linked trim resets on a frame-count change as+ * well as on a cutpoint change — the same bargain the section's help text+ * already describes, and the backend leaves no alternative: a window that does+ * not fit the budget loses its seam end.+ */+export const applyReferenceExtendNumFrames = (+ references: VideoReferenceItem[],+ numFrames: number+): VideoReferenceItem[] => {+ let changed = false;+ const next = references.map((entry) => {+ if (entry.kind !== 'video' || entry.fromSourceVideo !== true) {+ return entry;+ }+ const startFrame = referenceExtendStartFrame(entry.clip, numFrames);++ if (startFrame === entry.clip.startFrame) {+ return entry;+ }+ changed = true;++ return { ...entry, clip: { ...entry.clip, startFrame } };+ });++ return changed ? next : references;};/**@@ -423,19 +490,28 @@ export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip): VideoSo** - clearing the Initial Video removes its linked reference;* - setting or re-trimming it re-derives the linked reference's default trim- * (`[end - 140, end]`) — a manually tuned trim therefore holds only until- * the next cutpoint change, which the section's help text says;+ * (the tail window ending on the cutpoint) — a manually tuned trim+ * therefore holds only until the next cutpoint change, which the section's+ * help text says;* - with no linked entry yet, an existing video reference for the same clip* is adopted (recall restores the pair without the linkage flag; adopting- * avoids a duplicate), else a new one is PREPENDED — the continuity anchor- * leads the request order — unless the video cap is already full, in which- * case the list is returned unchanged and the extension simply runs without- * a tail reference.+ * avoids a duplicate), else a new one is APPENDED — unless the video cap is+ * already full, in which case the list is returned unchanged and the+ * extension simply runs without a tail reference.+ *+ * Appended, not prepended, because request order IS rotary order:+ * `build_ref2va_packed_sequence` lays the reference blocks out in order, each+ * advancing a shared clock, and the generated rows then start at the position+ * the LAST block left behind. The reference the model continues from is+ * therefore the final one, so the continuity anchor belongs at the end. (The+ * entry stays reorderable and keeps its place on a re-derive; only the+ * default position is fixed here.)*/export const applyReferenceExtendSourceVideo = (references: VideoReferenceItem[],sourceVideo: VideoSourceClip | null,- maxVideos: number+ maxVideos: number,+ numFrames: number): VideoReferenceItem[] => {if (!sourceVideo) {const kept = references.filter((entry) => !(entry.kind === 'video' && entry.fromSourceVideo === true));@@ -444,7 +520,7 @@ export const applyReferenceExtendSourceVideo = (}const linked: VideoReferenceItem = {- clip: deriveReferenceExtendClip(sourceVideo),+ clip: deriveReferenceExtendClip(sourceVideo, numFrames),conditioning: 'video_audio',fromSourceVideo: true,kind: 'video',@@ -467,7 +543,7 @@ export const applyReferenceExtendSourceVideo = (const videoCount = references.filter((entry) => entry.kind === 'video').length;- return videoCount >= maxVideos ? references : [linked, ...references];+ return videoCount >= maxVideos ? references : [...references, linked];};/**diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.tsindex b3bd80442b..6758cae4b6 100644--- a/invokeai/frontend/webv2/src/features/video/core/types.ts+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts@@ -47,10 +47,11 @@ export type VideoReferenceItem =/*** True on the reference the panel derives from the Initial Video in* Ref2VA extend mode: it tracks that clip's identity, and its trim- * defaults re-derive from the cutpoint (`[end - 140, end]`, ~5s of- * lead-in at 24 fps) whenever the Initial Video trim changes. It is an- * ordinary reference otherwise — reorderable, trimmable, removable —- * and the flag is panel state only, never recorded in metadata.+ * defaults re-derive from the cutpoint (up to ~5s of lead-in at 24 fps,+ * capped at the generated frame count so the backend keeps the whole+ * window) whenever the Initial Video trim or the frame count changes.+ * It is an ordinary reference otherwise — reorderable, trimmable,+ * removable — and the flag is panel state only, never in metadata.*/fromSourceVideo?: boolean;}diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex 505c57bba1..5435c60545 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -1279,6 +1279,28 @@ describe('reference-extend policy', () => {expect(reasons).toContainEqual(expect.stringContaining('cannot be combined with an initial video on this model'));});+ it('a Wan -> Ref2VA switch snaps the frame count BEFORE sizing the tail window', () => {+ // Wan's grid starts at 5 frames. Deriving the window before the snap sized+ // it for that count, and the repair only ever shrank — so the panel landed+ // on a 90-frame H3 generation with a 5-frame anchor, below the 13 frames+ // `sample_text_conditioning_frames` needs. Generate failed outright.+ for (const wanFrames of [5, 9, 21, 81]) {+ const wan = wanModel('i2v-14b');+ const toRef = getVideoModelSelectionResult({+ currentSettings: settingsFor(wan, { modelKey: wan.key, numFrames: wanFrames, sourceVideo: initialVideo }),+ model: ref2vaTransformer(),+ models: [wan],+ });+ const linked = toRef.settings.references.find(+ (entry) => entry.kind === 'video' && entry.fromSourceVideo === true+ );++ expect(toRef.settings.numFrames).toBe(90);+ // 90 frames of 24 fps material off a 24 fps clip, whatever Wan was on.+ expect(linked).toMatchObject({ clip: { endFrame: 400, startFrame: 311 } });+ }+ });+it('an FL2VA -> Ref2VA switch keeps the initial video and derives its linked tail reference', () => {const fl2va = h3Model();const toRef = getVideoModelSelectionResult({@@ -1289,8 +1311,12 @@ describe('reference-extend policy', () => {expect(toRef.settings.sourceVideo).toEqual(initialVideo);expect(toRef.clearedLabels).not.toContain('Initial video');+ // The window is budgeted against the frame count the switch lands on+ // (H3's 124-frame default, snapped AFTER the derivation): a reference+ // longer than the generation is truncated at its seam end.+ expect(toRef.settings.numFrames).toBe(124);expect(toRef.settings.references[0]).toMatchObject({- clip: { endFrame: 400, startFrame: 260, video_name: 'long.mp4' },+ clip: { endFrame: 400, startFrame: 277, video_name: 'long.mp4' },conditioning: 'video_audio',fromSourceVideo: true,kind: 'video',diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 3e04ecd3ca..873d77622e 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -40,6 +40,7 @@ import {} from './dimensions';import {applyReferenceExtendSourceVideo,+ applyReferenceExtendNumFrames,MIN_VIDEO_TRIM_FRAMES,resolveVideoMode,VIDEO_ASPECT_RATIO_IDS,@@ -1413,6 +1414,18 @@ export const getVideoModelSelectionResult = ({addClearedLabel(clearedLabels, 'Initial video');}+ // The frame count is snapped BEFORE the tail reference is derived: the window+ // is budgeted against it, and deriving first left a Wan panel's count (as low+ // as 5) sizing a window for a 90-frame H3 generation — under the 13 frames+ // text conditioning needs, so Generate failed outright.+ const snappedFrames = snapVideoNumFrames(model, next.numFrames);+ const framesChanged = snappedFrames !== next.numFrames;++ if (framesChanged) {+ next.numFrames = snappedFrames;+ addClearedLabel(clearedLabels, 'Frames');+ }+// Reference-extend: a surviving Initial Video (e.g. carried over from an// FL2VA extend setup) gets its linked tail reference derived, so the switch// lands on a generatable panel. Only when none exists yet: the transition@@ -1424,7 +1437,19 @@ export const getVideoModelSelectionResult = ({next.sourceVideo &&!next.references.some((entry) => entry.kind === 'video' && entry.fromSourceVideo === true)) {- next.references = applyReferenceExtendSourceVideo(next.references, next.sourceVideo, config.references.maxVideos);+ next.references = applyReferenceExtendSourceVideo(+ next.references,+ next.sourceVideo,+ config.references.maxVideos,+ next.numFrames+ );+ }++ // A tail reference carried in from another model keeps a window budgeted for+ // that model's frame count. Only when the count actually moved: otherwise a+ // task-neutral re-selection would reset a hand-tuned trim.+ if (config.references?.extend && framesChanged) {+ next.references = applyReferenceExtendNumFrames(next.references, next.numFrames);}if (next.firstFrameImage && !modes.includes('first-frame') && !modes.includes('first-last')) {@@ -1449,13 +1474,6 @@ export const getVideoModelSelectionResult = ({addClearedLabel(clearedLabels, 'Target resolution');}- const snappedFrames = snapVideoNumFrames(model, next.numFrames);-- if (snappedFrames !== next.numFrames) {- next.numFrames = snappedFrames;- addClearedLabel(clearedLabels, 'Frames');- }-const clampedFps =config.fps.editable && Number.isFinite(next.fps)? Math.min(config.fps.max, Math.max(config.fps.min, Math.round(next.fps)))diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex c80189f38b..4aa586b2df 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -10,6 +10,7 @@ import { ModelSelect } from '@features/models/react';import { getVideoDurationSeconds, invertVideoAspectRatioId } from '@features/video/core/dimensions';import {applyReferenceExtendSourceVideo,+ applyReferenceExtendNumFrames,normalizeVideoWidgetValues,resolveVideoMode,VIDEO_ASPECT_RATIO_IDS,@@ -214,7 +215,6 @@ export const VideoWidgetView = () => {cfgScale: (cfgScale: number) => patch({ cfgScale }),cfgScaleLowNoise: (cfgScaleLowNoise: number) => patch({ cfgScaleLowNoise }),fps: (fps: number) => patch({ fps }),- numFrames: (numFrames: number) => patch({ numFrames }),randomizeSeed: (details: { checked: boolean }) => patch({ shouldRandomizeSeed: details.checked }),seed: ({ valueAsNumber }: NumberInput.ValueChangeDetails) =>Number.isFinite(valueAsNumber) && patch({ seed: valueAsNumber }),@@ -251,10 +251,31 @@ export const VideoWidgetView = () => {[patch]);const setLastFrame = useCallback((lastFrameImage: ImageWithDims | null) => patch({ lastFrameImage }), [patch]);+ // Not part of `set`: that object is memoized on `patch` alone so the field+ // setters keep the children's `memo` intact, and this one has to track the+ // reference list. The linked tail reference's window is budgeted against the+ // generated frame count — the backend discards an ill-fitting window at its+ // SEAM end — so the count and the window move together. The re-derive is+ // idempotent: this fires once per keystroke of the Frames input, unclamped,+ // so typing "345" arrives as 3, then 34, then 345.+ const setNumFrames = useCallback(+ (numFrames: number) =>+ patch(+ referenceExtend+ ? { numFrames, references: applyReferenceExtendNumFrames(values.references, numFrames) }+ : { numFrames }+ ),+ [patch, referenceExtend, values.references]+ );const setSourceVideo = useCallback((sourceVideo: VideoSourceClip | null) => {if (referenceExtend) {- const references = applyReferenceExtendSourceVideo(values.references, sourceVideo, maxVideoReferences);+ const references = applyReferenceExtendSourceVideo(+ values.references,+ sourceVideo,+ maxVideoReferences,+ values.numFrames+ );// Unchanged identity with a clip set means the video cap is full and// no same-clip entry could be adopted: the extension would run with@@ -271,7 +292,7 @@ export const VideoWidgetView = () => {}patch({ sourceVideo, ...(sourceVideo ? { firstFrameImage: null } : {}) });},- [maxVideoReferences, patch, referenceExtend, t, values.references]+ [maxVideoReferences, patch, referenceExtend, t, values.numFrames, values.references]);const setReferences = useCallback((references: VideoReferenceItem[]) =>@@ -530,7 +551,7 @@ export const VideoWidgetView = () => {min={framesSlider.min}step={framesSlider.step}value={values.numFrames}- onChange={set.numFrames}+ onChange={setNumFrames}/></Field>{policy.ui.fpsVisible ? (