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): close the third review round's findings
Lincoln Steinbfd058947d9c
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 4606edc190..c78b0de5f5 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -638,6 +638,70 @@ describe('reference-extend linkage', () => {expect(unlinked?.references[0]).not.toHaveProperty('fromSourceVideo');});+ it('adopts the LAST same-name entry: the pin invariant records the anchor last', () => {+ // Recorded metadata can hold a user's OWN reference to the source clip+ // ahead of the anchor -- the pin forces the anchor last, so it is always+ // the later same-name entry. A first-match flagged the user's reference:+ // their trim got re-budgeted, the list reordered against the recording,+ // and the true tail window sat unprotected at the seam.+ const userRef = {+ ...VIDEO_REFERENCE,+ clip: { ...VIDEO_REFERENCE.clip, endFrame: 20, startFrame: 0, video_name: 'long.mp4' },+ };+ const tailRef = { ...VIDEO_REFERENCE, clip: { ...VIDEO_REFERENCE.clip, video_name: 'long.mp4' } };+ const normalized = normalizeVideoSettings(+ createSettings({ references: [userRef, tailRef], sourceVideo: source24 })+ );++ expect(normalized?.references[0]).toBe(userRef);+ expect(normalized?.references[1]).toMatchObject({ clip: { endFrame: 47 }, fromSourceVideo: true });+ });++ it('canonicalizes the flag to at most one entry and keeps normalization stable', () => {+ // Two flagged entries (a corrupt or hand-merged record) used to oscillate:+ // the pin moves the FIRST flagged entry last, swapping the pair on every+ // pass -- and the overflow trim exempts every flagged entry, so an+ // over-cap list of them could never come back under the cap.+ const flaggedNamed = (video_name: string) => ({+ ...VIDEO_REFERENCE,+ clip: { ...VIDEO_REFERENCE.clip, video_name },+ fromSourceVideo: true,+ });+ const once = normalizeVideoSettings(createSettings({ references: [flaggedNamed('a.mp4'), flaggedNamed('b.mp4')] }));+ const twice = normalizeVideoSettings(createSettings({ references: once!.references }));++ expect(once?.references.filter((entry) => entry.kind === 'video' && entry.fromSourceVideo === true)).toHaveLength(+ 1+ );+ expect(once?.references.at(-1)).toMatchObject({ clip: { video_name: 'b.mp4' }, fromSourceVideo: true });+ expect(twice?.references).toEqual(once?.references);++ // All-flagged over the cap: the exemption can no longer make the surplus+ // immortal -- the cap holds, and the surviving flag is the last one.+ const overCap = normalizeVideoSettings(+ createSettings({ references: ['a', 'b', 'c', 'd'].map((name) => flaggedNamed(`${name}.mp4`)) })+ );++ expect(overCap?.references).toHaveLength(3);+ expect(+ overCap?.references.filter((entry) => entry.kind === 'video' && entry.fromSourceVideo === true)+ ).toHaveLength(1);+ expect(overCap?.references.at(-1)).toMatchObject({ clip: { video_name: 'd.mp4' }, fromSourceVideo: true });+ });++ it('an absurd probed frame rate falls back to 24 instead of hanging', () => {+ // Past ~2^53 source frames, tailSourceFrames' adjustment loops cannot even+ // step (tail + 1 === tail in floats) -- fps 1e17 froze the tab. Any rate+ // no real container produces now takes the same fallback as a broken one.+ expect(deriveReferenceExtendClip({ ...source24, fps: 1e17 }, 141)).toMatchObject({+ endFrame: 400,+ startFrame: 260,+ });+ expect(deriveReferenceExtendClip({ ...source24, fps: 1001 }, 141)).toMatchObject({ startFrame: 260 });+ // The boundary itself is still a real rate.+ expect(deriveReferenceExtendClip({ ...source24, fps: 1000 }, 141)).not.toMatchObject({ startFrame: 260 });+ });+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], source24, 3, FRAMES);diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 7f0ce0eedd..35fee0cb39 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -122,6 +122,28 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide}let valid = value.filter((entry) => isVideoReferenceItem(entry));+ // Canonicalize the flag to AT MOST ONE entry, keeping the LAST. Only a+ // corrupt or hand-merged record carries two, but two is a poisoned state:+ // the pin moves the FIRST flagged entry last, so normalization oscillates+ // between the pair on alternate passes, and the overflow trim below exempts+ // every flagged entry, so an over-cap list of them could never be brought+ // under the cap again. The last one matches the pin invariant every healthy+ // record was written under.+ let flagged = -1;+ for (let index = valid.length - 1; index >= 0; index -= 1) {+ const entry = valid[index]!;++ if (entry.kind === 'video' && entry.fromSourceVideo === true) {+ flagged = index;+ break;+ }+ }+ valid = valid.map((entry, index) =>+ index !== flagged && entry.kind === 'video' && entry.fromSourceVideo === true+ ? { ...entry, fromSourceVideo: false }+ : entry+ );+// Re-establish the linkage recall drops. `fromSourceVideo` is panel state// and never reaches metadata, so a recalled panel arrives with its anchor// UNFLAGGED beside the source video -- and every invariant keyed on the flag@@ -129,18 +151,24 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide// silently lapses: a Frames change left the recalled window unbudgeted and// the backend cut 2s off the seam. The flag is derivable, not just// storable: the video reference naming the Initial Video's clip IS the- // anchor, the same identity `applyReferenceExtendSourceVideo` adopts by.- // An already-flagged entry stays authoritative.- if (- sourceVideoName !== undefined &&- !valid.some((entry) => entry.kind === 'video' && entry.fromSourceVideo === true)- ) {- const adopt = valid.findIndex((entry) => entry.kind === 'video' && entry.clip.video_name === sourceVideoName);-- if (adopt >= 0) {- valid = valid.map((entry, index) =>- index === adopt && entry.kind === 'video' ? { ...entry, fromSourceVideo: true } : entry- );+ // anchor. An already-flagged entry stays authoritative.+ //+ // Adopt the LAST same-name entry, not the first. The pin invariant means+ // the anchor is always recorded last, and recorded metadata can hold a+ // user's OWN reference to the same clip ahead of it -- a first-match+ // flagged that one instead: the user's trim got re-budgeted, the list+ // reordered against the recording, and the true tail window was left+ // unprotected at the seam.+ if (flagged === -1 && sourceVideoName !== undefined) {+ for (let index = valid.length - 1; index >= 0; index -= 1) {+ const entry = valid[index]!;++ if (entry.kind === 'video' && entry.clip.video_name === sourceVideoName) {+ valid = valid.map((candidate, candidateIndex) =>+ candidateIndex === index && candidate.kind === 'video' ? { ...candidate, fromSourceVideo: true } : candidate+ );+ break;+ }}}@@ -152,26 +180,30 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide// touches the reference list.valid = pinReferenceExtendAnchor(valid);+ // Keyed by INDEX, not object identity: a hand-edited record can alias the+ // same entry object twice, and an identity Set would drop both copies.+ // With the flag canonicalized to at most one entry above, the flag+ // exemption can never leave the surplus undroppable.let videosToDrop = Math.max(0, valid.filter((entry) => entry.kind === 'video').length - VIDEO_REFERENCE_MAX_VIDEOS);- const dropped = new Set<VideoReferenceItem>();+ const dropped = new Set<number>();for (let index = valid.length - 1; index >= 0 && videosToDrop > 0; index -= 1) {const entry = valid[index]!;if (entry.kind === 'video' && entry.fromSourceVideo !== true) {- dropped.add(entry);+ dropped.add(index);videosToDrop -= 1;}}const result: VideoReferenceItem[] = [];let images = 0;- for (const entry of valid) {+ for (const [index, entry] of valid.entries()) {if (entry.kind === 'image') {if (images >= VIDEO_REFERENCE_MAX_IMAGES) {continue;}images += 1;- } else if (dropped.has(entry)) {+ } else if (dropped.has(index)) {continue;}result.push(entry);@@ -483,6 +515,9 @@ export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip, numFramestartFrame: referenceExtendStartFrame(sourceVideo, numFrames),});+/** The highest source frame rate the tail-window math accepts as real; see the fps guard below. */+const MAX_REFERENCE_SOURCE_FPS = 1000;+/** `snap_reference_num_frames`: down to the `17n + 5` grid the video VAE encodes whole. */const snapReferenceFrames = (frames: number): number => Math.max(1, Math.floor((frames - 5) / 17)) * 17 + 5;@@ -495,8 +530,13 @@ const referenceExtendStartFrame = (clip: VideoSourceClip, numFrames: number): nu// 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;+ // floor, which is below the 13 frames text conditioning needs. The upper+ // bound is a hang guard: past ~2^53 source frames, `tailSourceFrames`'+ // adjustment loops cannot even step (`tail + 1 === tail` in floats) and spin+ // forever on the main thread — a hand-edited record with fps 1e17 froze the+ // tab on the first Frames keystroke. No real container exceeds 1000 fps.+ const fps =+ Number.isFinite(clip.fps) && clip.fps > 0 && clip.fps <= MAX_REFERENCE_SOURCE_FPS ? clip.fps : MINIMAX_H3_FPS;const requested = Number.isFinite(numFrames)? Math.min(VIDEO_REFERENCE_EXTEND_TAIL_FRAMES, Math.trunc(numFrames)): VIDEO_REFERENCE_EXTEND_TAIL_FRAMES;diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 70a98da720..ffa06b4db5 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -161,16 +161,30 @@ export const VideoWidgetView = () => {// Synced in an effect rather than during render: this file's react-compiler// rule forbids touching a ref while rendering, and a gallery resolve lands// whole frames later, long after the commit.- // Keyed by PROJECT, not just latest: the widget is reconciled, never- // remounted, across a project switch (the <Activity> key is the panel+ // Keyed by PROJECT, and carrying a LIVENESS bit. The widget is reconciled,+ // never remounted, across a project switch (the <Activity> key is the panel// instance), while `patch` stays bound to the project its render belonged- // to. A bare latest-list ref therefore tracks whichever project is ACTIVE —- // and a gallery resolve landing after a switch would write the new project's- // reference list into the old project, wholesale.- const referencesRef = useRef({ projectId, references: values.references });+ // to — so a bare latest-list ref tracks whichever project is ACTIVE, and a+ // gallery resolve landing after a switch would write the new project's+ // reference list into the old project, wholesale. And a hidden <Activity>+ // destroys effects while promise continuations keep running: the ref then+ // freezes with the projectId still matching, so a same-project guard would+ // happily replay a list the store has since rewritten (a gallery deletion+ // sweep, say) — resurrecting swept references. `live` is true exactly while+ // the sync effect is mounted, which is the only time the ref's contents can+ // be trusted; a write finding it false or mismatched is dropped.+ //+ // "Fresh" here means effect-fresh, not instantaneous: two resolves landing+ // in the same microtask drain still read the same pre-commit list. That+ // window is inherent to reading through React state at all.+ const referencesRef = useRef({ live: true, projectId, references: values.references });useEffect(() => {- referencesRef.current = { projectId, references: values.references };+ referencesRef.current = { live: true, projectId, references: values.references };++ return () => {+ referencesRef.current = { ...referencesRef.current, live: false };+ };}, [projectId, values.references]);// Chakra's `Field.Root` hands its single `ids.control` to EVERY control@@ -292,7 +306,7 @@ export const VideoWidgetView = () => {const setNumFrames = useCallback((numFrames: number) =>patch(- referenceExtend && referencesRef.current.projectId === projectId+ referenceExtend && referencesRef.current.live && referencesRef.current.projectId === projectId? { numFrames, references: applyReferenceExtendNumFrames(referencesRef.current.references, numFrames) }: { numFrames }),@@ -307,11 +321,12 @@ export const VideoWidgetView = () => {const setSourceVideo = useCallback((sourceVideo: VideoSourceClip | null) => {if (referenceExtend) {- // Same project-scoped live read as `setReferences`: the clip field's- // adopt and upload paths call this after an await, and a captured- // list would clobber a reference added meanwhile. A write whose- // project has moved on is dropped.- if (referencesRef.current.projectId !== projectId) {+ // Same guard as `setReferences`: the clip field's adopt and upload+ // paths call this after an await, and a captured list would clobber a+ // reference added meanwhile. Dropped when the project moved on or the+ // sync effect is unmounted — the ref is effect-fresh, not live, and+ // only vouches for its contents while mounted.+ if (!referencesRef.current.live || referencesRef.current.projectId !== projectId) {return;}const current = referencesRef.current.references;@@ -347,14 +362,23 @@ export const VideoWidgetView = () => {// the LAST reference, so the anchor's position is derived, not user-set.const setReferences = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {- // A pending edit whose project has moved on is DROPPED: this callback's- // `patch` still targets the project it rendered for, but that project's- // current list is gone from the ref. Losing one add because the user- // switched projects mid-resolve beats overwriting a list they can see.- if (referencesRef.current.projectId !== projectId) {+ // A pending edit is DROPPED when the ref cannot vouch for the list:+ // the project moved on (this callback's `patch` still targets the one+ // it rendered for), or the sync effect is unmounted (a hidden panel's+ // continuations would replay a frozen list over whatever the store has+ // done since). Losing one add beats overwriting a list the user can see.+ if (!referencesRef.current.live || referencesRef.current.projectId !== projectId) {return;}const updated = update(referencesRef.current.references);++ // Identity return means the updater declined (an apply-time cap check)+ // or had nothing to do: patching anyway would still fire this spread's+ // firstFrameImage/lastFrameImage clearing — a refused add erasing frame+ // slots it never touched — and dirty the project with a no-op write.+ if (updated === referencesRef.current.references) {+ return;+ }const next = referenceExtend ? pinReferenceExtendAnchor(updated) : updated;patch({