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(video): read the panel when a frame or clip drop commits, not when it began
Lincoln Steind79353327923
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsxindex c876190f72..019cb16d47 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx@@ -34,6 +34,8 @@ const revealGalleryItem = vi.fn();/** The regions the project's single gallery instance occupies. */let galleryRegions: string[] = ['right'];+/** The store's projects, read by `queries.getProject` at call time. */+let storedProjects: Record<string, unknown> = {};vi.mock('@features/video', () => ({VideoUiProvider: ({ adapter: next, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {@@ -55,6 +57,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({widgets: { patchValues: vi.fn() },}),useWorkbenchQueries: () => ({+ getProject: (projectId: string) => storedProjects[projectId] ?? null,isActiveProject: (projectId: string) => projectId === activeProjectId,getSnapshot: () => ({activeProject: {@@ -90,6 +93,7 @@ beforeEach(async () => {revealGalleryItem.mockClear();reportError.mockClear();galleryRegions = ['right'];+ storedProjects = {};host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -107,6 +111,34 @@ afterEach(async () => {}});+describe('readValues', () => {+ const videoProject = (values: Record<string, unknown>) => ({+ widgetInstances: { 'video-1': { state: { values }, typeId: 'video' } },+ });++ it("reads the panel's values when called, for drops that commit after the panel changed", () => {+ storedProjects = { 'project-1': videoProject({ positivePrompt: 'before' }) };+ const { readValues } = adapter;++ // No re-render: an async commit holds the adapter it captured, and must still see the store as it is now.+ storedProjects = { 'project-1': videoProject({ positivePrompt: 'after' }) };++ expect(readValues()).toEqual({ positivePrompt: 'after' });+ });++ it('reads the project its writes target, and nothing once that project is gone', async () => {+ storedProjects = { 'project-1': videoProject({ positivePrompt: 'one' }), 'project-2': videoProject({}) };+ const { readValues } = adapter;++ activeProjectId = 'project-2';+ await renderAdapter();++ expect(readValues()).toEqual({ positivePrompt: 'one' });+ storedProjects = {};+ expect(readValues()).toEqual({});+ });+});+describe('videoSpanPlayback', () => {it("hands the panel the player's report and its changes", () => {const listener = vi.fn();diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsxindex 2a79609357..919f7dda56 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx@@ -14,7 +14,7 @@ import {subscribeVideoSpanPlaybackState,} from '@workbench/widgets/preview/spanPlaybackRequest';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useMemo, useRef } from 'react';/** Video owns its prompt in widget values; do not join the draft shared by Generate/Upscale. */@@ -47,6 +47,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>activeProjectIdRef.current = project.projectId;}, [project.projectId, uploadBoardId]);const commands = useWorkbenchCommands();+ const queries = useWorkbenchQueries();const queryClient = useQueryClient();// Key actions by project, not values, to preserve callback identity while typing.const { projectId } = project;@@ -54,6 +55,12 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>(values, origin) => commands.widgets.patchValues('video', values, projectId, origin),[commands, projectId]);+ // The same project patchValues writes to, so an async commit reads and writes one panel.+ const readValues = useCallback<VideoUiAdapter['readValues']>(() => {+ const target = queries.getProject(projectId);++ return target ? getProjectWidgetValues(target, 'video') : {};+ }, [projectId, queries]);const reportError = useCallback<VideoUiAdapter['reportError']>((message) => commands.notifications.reportError({ area: 'video', message, namespace: 'generation' }),[commands]@@ -88,6 +95,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>getUploadBoardId,patchValues,playVideoSpanInPreview,+ readValues,reportError,showPromptSyntaxHighlighting,touchGalleryImages,@@ -99,6 +107,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>patchValues,playVideoSpanInPreview,project,+ readValues,reportError,showPromptSyntaxHighlighting,touchGalleryImages,diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex e96c487e57..5a393857d4 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -25,6 +25,8 @@ import {getInitialVideoPatch,getReferencesPatch,isVideoSettings,+ areFrameImagesHeld,+ createFrameImageSetter,createVideoConditioningClip,getFrameImagePatch,isVideoSourceClip,@@ -538,6 +540,57 @@ describe('getFrameImagePatch', () => {});});+describe('createFrameImageSetter', () => {+ const soundtrack = { clip: CONDITIONING_CLIP, fpsKnown: true, role: 'audio' as const };+ const picture = { ...soundtrack, role: 'video' as const };++ /** A panel whose clip role changes while a frame drop is still resolving, as the gallery drop's await allows. */+ const racePanel = (startRole: typeof soundtrack | typeof picture, endRole: typeof soundtrack | typeof picture) => {+ let raw: Record<string, unknown> = { ...createSettings(), conditioningClip: startRole };+ const patches: Partial<VideoWidgetValues>[] = [];+ // Made once, when the drop begins, exactly as GalleryMediaSlot captures its onChange.+ const setLastFrame = createFrameImageSetter(+ 'lastFrameImage',+ () => raw,+ (values) => patches.push(values)+ );++ raw = { ...raw, conditioningClip: endRole };+ setLastFrame(FIRST_FRAME);++ return patches;+ };++ it('displaces a clip switched to its picture while the frame was resolving', () => {+ expect(racePanel(soundtrack, picture)).toEqual([{ conditioningClip: null, lastFrameImage: FIRST_FRAME }]);+ });++ it('keeps a clip switched to its soundtrack while the frame was resolving', () => {+ expect(racePanel(picture, soundtrack)).toEqual([{ lastFrameImage: FIRST_FRAME }]);+ });++ it('displaces a picture-role clip the first frame hides, so it cannot resurface beside the last frame', () => {+ const raw = { ...createSettings({ firstFrameImage: FIRST_FRAME }), conditioningClip: picture };+ const patches: Partial<VideoWidgetValues>[] = [];++ createFrameImageSetter(+ 'lastFrameImage',+ () => raw,+ (values) => patches.push(values)+ )(FIRST_FRAME);++ expect(patches).toEqual([{ conditioningClip: null, lastFrameImage: FIRST_FRAME }]);+ });+});++describe('areFrameImagesHeld', () => {+ it('reports either frame, so a clip dropped beside one takes the soundtrack role', () => {+ expect(areFrameImagesHeld(createSettings())).toBe(false);+ expect(areFrameImagesHeld(createSettings({ firstFrameImage: FIRST_FRAME }))).toBe(true);+ expect(areFrameImagesHeld(createSettings({ lastFrameImage: FIRST_FRAME }))).toBe(true);+ });+});+describe('normalizeVideoSettings — the conditioning clip', () => {const clip = { clip: CONDITIONING_CLIP, fpsKnown: true, role: 'audio' as const };diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 2c2eb5bbd9..472faf9395 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -991,6 +991,38 @@ export const getFrameImagePatch = (...(image && isConditioningClipExcludingFrames(conditioningClip) ? { conditioningClip: null } : {}),});+/**+ * A first- or last-frame setter that decides what the frame displaces from the panel as it is when called, not as it+ * was when the setter was made. Gallery drops resolve asynchronously and commit through the setter captured at drop+ * time; the clip's role can change in between, and a stale reading would keep a picture-role clip beside the frame.+ *+ * The stored clip, not the normalized one: normalization hides a picture-role clip behind a first frame, and a frame+ * that left it stored would let it resurface beside the last frame once the first is cleared.+ */+export const createFrameImageSetter =+ (+ slot: 'firstFrameImage' | 'lastFrameImage',+ readValues: () => unknown,+ patch: (values: Partial<VideoWidgetValues>) => void+ ) =>+ (image: ImageWithDims | null): void => {+ const values = readValues();+ const storedClip =+ isRecord(values) && isVideoConditioningClip(values.conditioningClip) ? values.conditioningClip : null;++ patch(getFrameImagePatch(slot, image, storedClip));+ };++/**+ * Whether the panel holds a first or last frame right now. A clip dropped while either is held takes the soundtrack+ * role; the drop resolves asynchronously, so this is read when it lands rather than when it began.+ */+export const areFrameImagesHeld = (values: unknown): boolean => {+ const normalized = normalizeVideoWidgetValues(values);++ return Boolean(normalized?.firstFrameImage || normalized?.lastFrameImage);+};+/*** The panel patch that sets the conditioning clip, or clears it. A clip claims a whole modality, so it displaces the* initial video and the references, and in the picture role the frames as well.diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex dcc03db109..463d11afee 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -22,6 +22,8 @@ export {createVideoSourceClip,getDefaultConditioningRole,getDefaultReferenceConditioning,+ areFrameImagesHeld,+ createFrameImageSetter,getConditioningClipPatch,getFrameImagePatch,getInitialVideoPatch,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsxindex d19b81b52a..00e9afee5d 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx@@ -3,7 +3,7 @@ import type { VideoConditioningClip, VideoConditioningRole } from '@features/vidimport { createListCollection, Stack, Text } from '@chakra-ui/react';import { GalleryMediaSlot, type GalleryMediaSlotLabels, type GalleryMediaSlotValue } from '@features/gallery/mediaSlot';-import { createVideoConditioningClip } from '@features/video/core/settings';+import { areFrameImagesHeld, createVideoConditioningClip } from '@features/video/core/settings';import { Field, Select } from '@platform/ui';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -37,12 +37,12 @@ export const VideoConditioningClipField = memo(disabledReason?: string;/** What the clip works out to — length, and the rate it will run at. */derivedText?: string;- /** Set while the picture role is unavailable; a dropped clip then arrives in the soundtrack role. */+ /** Set while the picture role is unavailable because frames are held. */pictureRoleDisabledReason?: string;onChange: (conditioning: VideoConditioningClip | null) => void;}) {const { t } = useTranslation();- const { findInGallery } = useVideoUiActions();+ const { findInGallery, readValues } = useVideoUiActions();const slotLabels = useMemo<Partial<GalleryMediaSlotLabels>>(() => ({ drop: t('widgets.video.dropConditioningClip') }),[t]@@ -80,10 +80,11 @@ export const VideoConditioningClipField = memo(if (item === null) {onChange(null);} else if (item.kind === 'video') {- onChange(createVideoConditioningClip(item, { framesHeld: pictureRoleDisabledReason !== undefined }));+ // Read when the drop lands, not when it began: a frame picked meanwhile must not be cleared by a picture role.+ onChange(createVideoConditioningClip(item, { framesHeld: areFrameImagesHeld(readValues()) }));}},- [onChange, pictureRoleDisabledReason]+ [onChange, readValues]);// The whole premise of this field is what is inside the clip, so it gets the same way back to// the gallery record that every other media slot has.diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsxindex c228167062..1ac27342a2 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx@@ -18,6 +18,8 @@ export interface VideoUiAdapter {playVideoSpanInPreview(span: { endSeconds: number; item: GalleryVideoItem; startSeconds: number }): number | null;projectId: string;rawValues: Record<string, unknown>;+ /** Read this project's raw panel values at call time without subscribing, for writes that complete asynchronously. */+ readValues(): Record<string, unknown>;reportError(message: string): void;showPromptSyntaxHighlighting: boolean;touchGalleryImages(): void;@@ -47,6 +49,7 @@ export type VideoUiActions = Pick<| 'getUploadBoardId'| 'patchValues'| 'playVideoSpanInPreview'+ | 'readValues'| 'reportError'| 'touchGalleryImages'| 'videoSpanPlayback'@@ -62,6 +65,7 @@ export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdaptergetUploadBoardId,patchValues,playVideoSpanInPreview,+ readValues,reportError,touchGalleryImages,videoSpanPlayback,@@ -72,6 +76,7 @@ export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdaptergetUploadBoardId,patchValues,playVideoSpanInPreview,+ readValues,reportError,touchGalleryImages,videoSpanPlayback,@@ -81,6 +86,7 @@ export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdaptergetUploadBoardId,patchValues,playVideoSpanInPreview,+ readValues,reportError,touchGalleryImages,videoSpanPlayback,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 6f2fec856e..1801c67b6a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -1,4 +1,3 @@-import type { ImageWithDims } from '@features/generation/contracts';import type { ModelConfig, ModelTaxonomyType } from '@features/models';import type {VideoConditioningClip,@@ -22,8 +21,8 @@ import {import {applyReferenceExtendNumFrames,canPlaceReferenceExtendAnchor,+ createFrameImageSetter,getConditioningClipPatch,- getFrameImagePatch,getInitialVideoPatch,getReferencesPatch,isConditioningClipExcludingFrames,@@ -129,7 +128,7 @@ export const VideoWidgetView = () => {const selection = useVideoUi();const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);- const { patchValues, projectId, rawValues } = selection;+ const { patchValues, projectId, rawValues, readValues } = selection;// Reconcile only when inputs change; it is expensive and fresh values rerender every section.const values = useMemo(() => {const normalized =@@ -283,16 +282,12 @@ export const VideoWidgetView = () => {const referenceExtend = Boolean(policy.references?.extend);const maxVideoReferences = policy.references?.maxVideos ?? 3;const conditioningClip = values.conditioningClip;- const setFirstFrame = useCallback(- (firstFrameImage: ImageWithDims | null) =>- patch(getFrameImagePatch('firstFrameImage', firstFrameImage, conditioningClip)),- [conditioningClip, patch]- );- const setLastFrame = useCallback(- (lastFrameImage: ImageWithDims | null) =>- patch(getFrameImagePatch('lastFrameImage', lastFrameImage, conditioningClip)),- [conditioningClip, patch]+ // A drop commits through the setter captured when it began, so what the frame displaces is read at commit time.+ const setFirstFrame = useMemo(+ () => createFrameImageSetter('firstFrameImage', readValues, patch),+ [patch, readValues]);+ const setLastFrame = useMemo(() => createFrameImageSetter('lastFrameImage', readValues, patch), [patch, readValues]);// Setting a frame is what clears a clip held for its picture, so the frame fields say so beforehand.const frameClearsClipText = isConditioningClipExcludingFrames(conditioningClip)? t('widgets.video.frameClearsConditioningClip')diff --git a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsxindex 8d2117035c..077e031d15 100644--- a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx@@ -60,6 +60,7 @@ const adapter = {playVideoSpanInPreview: () => null,projectId: 'project-1',rawValues: {},+ readValues: () => ({}),reportError: () => undefined,showPromptSyntaxHighlighting: false,touchGalleryImages: () => undefined,diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsxindex 3d78d4a099..cf16c479ed 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx@@ -58,6 +58,7 @@ const videoAdapter = {playVideoSpanInPreview: () => null,projectId: 'project-1',rawValues: {},+ readValues: () => ({}),reportError: noop,showPromptSyntaxHighlighting: false,touchGalleryImages: noop,