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
feat(webv2): frame scrubber for video-frame-index fields
Lincoln Stein08663615f54c
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tsindex 301ff44054..660e9843fc 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -30,7 +30,7 @@ export interface FieldInputTemplate {default?: unknown;uiHidden: boolean;uiOrder: number | null;- uiComponent: 'slider' | 'textarea' | null;+ uiComponent: 'slider' | 'textarea' | 'video-frame-index' | null;uiChoiceLabels: Record<string, string> | null;/** Enum choices when the field is an EnumField. */options: string[] | null;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.tsindex 29ae6b8e6a..bfe435ddee 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts@@ -30,6 +30,7 @@ const openApiFixture = {orig_required: false,title: 'B',type: 'integer',+ ui_component: 'video-frame-index',ui_hidden: false,},id: { field_kind: 'internal', title: 'Id', type: 'string' },@@ -126,6 +127,9 @@ describe('parseOpenApiToTemplates', () => {expect(Object.keys(add?.inputs ?? {}).sort()).toEqual(['a', 'b']);expect(add?.inputs.b?.minimum).toBe(0);expect(add?.inputs.a?.type).toEqual({ batch: false, cardinality: 'SINGLE', name: 'IntegerField' });+ // Unknown ui_component values collapse to null; known ones pass through.+ expect(add?.inputs.a?.uiComponent).toBeNull();+ expect(add?.inputs.b?.uiComponent).toBe('video-frame-index');});it('parses ref, nullable-anyOf, single-or-collection, and enum field types', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex 87f1425f9b..7474f00973 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -227,7 +227,11 @@ const buildInputTemplate = (name: string, property: JsonObject, type: FieldType)type,uiChoiceLabels,uiComponent:- property.ui_component === 'slider' || property.ui_component === 'textarea' ? property.ui_component : null,+ property.ui_component === 'slider' ||+ property.ui_component === 'textarea' ||+ property.ui_component === 'video-frame-index'+ ? property.ui_component+ : null,uiHidden: property.ui_hidden === true,uiModelBase: getStringArrayOrNull(property.ui_model_base),uiModelType: getStringArrayOrNull(property.ui_model_type),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex 4087216d00..4ae456fbd2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -463,6 +463,7 @@ const InputFieldRow = ({<WorkflowFieldInputid={`${node.id}-${template.name}-value`}invalid={isInvalid}+ nodeId={node.id}template={template}value={instance?.value}onChange={(value) =>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsxindex d34a8ebe67..70b987316b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx@@ -27,11 +27,12 @@ vi.mock('@features/gallery', () => ({}));const galleryValues: Record<string, unknown> = {};-const projectSnapshot = { galleryValues, id: 'project-1' };+const graphNodes: unknown[] = [];+const graphEdges: unknown[] = [];+const projectSnapshot = { galleryValues, id: 'project-1', projectGraph: { edges: graphEdges, nodes: graphNodes } };vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({- useWorkflowProjectSelector: (selector: (project: { galleryValues: Record<string, unknown> }) => unknown) =>- selector(projectSnapshot),+ useWorkflowProjectSelector: (selector: (project: typeof projectSnapshot) => unknown) => selector(projectSnapshot),useWorkflowUi: () => ({ project: { getSnapshot: () => projectSnapshot } }),}));@@ -48,6 +49,25 @@ const VIDEO_TEMPLATE = {type: { name: 'VideoField' },} as unknown as FieldInputTemplate;+const FRAME_INDEX_TEMPLATE = {+ name: 'frame_index',+ title: 'Frame Index',+ type: { cardinality: 'SINGLE', name: 'IntegerField' },+ uiComponent: 'video-frame-index',+} as unknown as FieldInputTemplate;++const makeFrameNode = (videoValue: { video_name: string } | undefined) => ({+ data: {+ inputs: {+ frame_index: { label: '', name: 'frame_index', value: -1 },+ video: { label: '', name: 'video', value: videoValue },+ },+ type: 'video_frame_extract',+ },+ id: 'frame-node',+ type: 'invocation',+});+const SELECTED_GALLERY_VIDEO = {boardId: 'none',category: 'general',@@ -76,6 +96,8 @@ beforeEach(() => {resolveItemMock.mockResolvedValue(SELECTED_GALLERY_VIDEO);queryClient.clear();delete galleryValues.selectedImage;+ graphNodes.length = 0;+ graphEdges.length = 0;});afterEach(async () => {@@ -85,13 +107,18 @@ afterEach(async () => {const queryClient = new QueryClient();-const renderField = async (template: FieldInputTemplate, value: unknown, onChange: (value: unknown) => void) => {+const renderField = async (+ template: FieldInputTemplate,+ value: unknown,+ onChange: (value: unknown) => void,+ nodeId?: string+) => {await act(() => {root.render(<ChakraProvider value={system}><QueryClientProvider client={queryClient}><DndContext>- <WorkflowFieldInput template={template} value={value} onChange={onChange} />+ <WorkflowFieldInput nodeId={nodeId} template={template} value={value} onChange={onChange} /></DndContext></QueryClientProvider></ChakraProvider>@@ -219,6 +246,118 @@ describe('WorkflowFieldInput media inputs', () => {expect(uploadVideoMock.mock.calls[0]?.[1]).toBe('none');});+ it('renders the frame scrubber for video-frame-index integer fields', async () => {+ resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, fps: 30 });+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));++ // Default of -1 (= last frame) resolves against duration * fps = 150 frames.+ await renderField(FRAME_INDEX_TEMPLATE, -1, vi.fn(), 'frame-node');++ await vi.waitFor(() => {+ expect(host.querySelector('video')?.src).toContain('/api/v1/videos/i/clip.mp4/full');+ });+ expect(host.textContent).toContain('149 / 149');+ expect(host.querySelector('input[type="number"]')).not.toBeNull();+ expect(host.querySelector('[role="slider"]')).not.toBeNull();+ });++ it('scrubs frames with the slider, writing the resolved index to the field', async () => {+ resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, fps: 30 });+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));+ const onChange = vi.fn();++ await renderField(FRAME_INDEX_TEMPLATE, 10, onChange, 'frame-node');++ await vi.waitFor(() => {+ expect(host.querySelector('[role="slider"]')).not.toBeNull();+ });++ const thumb = host.querySelector<HTMLElement>('[role="slider"]')!;++ thumb.focus();+ await act(() => thumb.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' })));+ expect(onChange).toHaveBeenCalledWith(11);+ });++ it('falls back to a hint when the companion video field is unset', async () => {+ graphNodes.push(makeFrameNode(undefined));++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ expect(host.querySelector('input[type="number"]')).not.toBeNull();+ expect(host.querySelector('video')).toBeNull();+ expect(host.textContent).toContain("Set this node's Video field to preview frames.");+ });++ it('falls back to a hint when the video has no probed frame rate', async () => {+ // SELECTED_GALLERY_VIDEO has no fps, so frames cannot be mapped onto time.+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ await vi.waitFor(() => {+ expect(host.textContent).toContain('no probed frame rate');+ });+ expect(host.querySelector('video')).toBeNull();+ });++ it('ignores the stored video value while the video field is connection-driven', async () => {+ resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, fps: 30 });+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }), {+ data: { inputs: {}, type: 'video' },+ id: 'upstream',+ type: 'invocation',+ });+ graphEdges.push({+ id: 'e1',+ source: 'upstream',+ sourceHandle: 'video',+ target: 'frame-node',+ targetHandle: 'video',+ });++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ expect(host.textContent).toContain('comes from a graph connection');+ expect(host.querySelector('video')).toBeNull();+ expect(resolveItemMock).not.toHaveBeenCalled();+ });++ it('shows the preview without a slider for a single-frame video', async () => {+ // min === max would render a broken (NaN%) zag slider.+ resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, durationSeconds: 0.02, fps: 30 });+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ await vi.waitFor(() => {+ expect(host.querySelector('video')).not.toBeNull();+ });+ expect(host.textContent).toContain('0 / 0');+ expect(host.querySelector('[role="slider"]')).toBeNull();+ });++ it('reports a deleted video instead of a frame-rate story', async () => {+ resolveItemMock.mockRejectedValue(new Error('404'));+ graphNodes.push(makeFrameNode({ video_name: 'gone.mp4' }));++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ await vi.waitFor(() => {+ expect(host.textContent).toContain('could not be loaded');+ });+ expect(host.querySelector('video')).toBeNull();+ });++ it('treats an empty-string video name as unset without firing a lookup', async () => {+ graphNodes.push(makeFrameNode({ video_name: '' }));++ await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');++ expect(host.textContent).toContain("Set this node's Video field to preview frames.");+ expect(resolveItemMock).not.toHaveBeenCalled();+ });+it('keeps the image field on the image upload path', async () => {uploadImageMock.mockResolvedValue({ imageName: 'uploaded.png' });const onChange = vi.fn();diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex bcb6395e82..cfa6490ed0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -9,17 +9,20 @@ import {galleryItems,galleryTransfers,type GalleryBoard,+ type GalleryItem,} from '@features/gallery';import { getSelectedGalleryImageFromValues, getSelectedGalleryItemFromValues } from '@features/gallery/contracts';import { invalidateGallery } from '@features/gallery/queries';import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';import { SCHEDULER_OPTIONS } from '@features/generation/settings';+import { isInvocationNode } from '@features/workflow/contracts';import {getWorkflowMediaFieldDropId,getWorkflowMediaFieldDropItem,type WorkflowMediaKind,} from '@features/workflow/ui/fields/mediaFieldDnd';import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { getResolvedWorkflowEdges } from '@features/workflow/utility';import {assertAccountScopeCurrent,captureAccountScope,@@ -36,6 +39,7 @@ import {parseHexColor,ResizableTextarea,Select,+ Slider,toaster,} from '@platform/ui';import { useQuery, useQueryClient } from '@tanstack/react-query';@@ -61,6 +65,8 @@ export const getWorkflowSelectedGalleryItem = getSelectedGalleryItemFromValues;export interface WorkflowFieldInputProps {id?: string;invalid?: boolean;+ /** Owning invocation node, when known — lets widgets read sibling fields (e.g. the frame scrubber's companion video). */+ nodeId?: string;template: FieldInputTemplate;value: unknown;onChange: (value: unknown) => void;@@ -553,7 +559,7 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr// editor's widget shows the same). Best-effort: the preview works from the// name alone, so a failed lookup just drops the badge.const { data: mediaItem } = useQuery({- enabled: mediaName !== null,+ enabled: mediaName !== null && mediaName !== '',queryFn: ({ signal }) => galleryItems.resolve({ kind, name: mediaName ?? '' }, signal),queryKey: ['workflow-media-field-item', kind, mediaName],retry: false,@@ -692,6 +698,198 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr);};+/**+ * Convention shared with the legacy editor: a `video-frame-index` field's+ * source video lives on a sibling field named `video` on the same node.+ */+const COMPANION_VIDEO_FIELD_NAME = 'video';++/**+ * Integer input for `ui_component=video-frame-index` fields (`frame_index` on+ * Frame from Video; `start_frame`/`end_frame` on Frame Range from Video): the+ * standard number input plus a live frame preview and a scrubber slider, all+ * writing the same field value. The preview is a muted `<video>` element+ * seeked to `frame / fps` — browsers display the frame natively without a+ * canvas roundtrip.+ *+ * Degrades to the plain number input (plus a hint) when the companion video+ * field is unset/connection-driven or the video has no probed frame rate.+ */+const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {+ const { nodeId, onChange, value } = props;++ // A connected `video` field keeps its stored value in the document, so the+ // sibling value alone would preview a stale video while invoke uses the+ // upstream one. Resolved edges are the same "connected" signal the editor+ // and Linear panel use to hide the video widget itself.+ const isVideoConnected = useWorkflowProjectSelector(+ (project) =>+ nodeId !== undefined &&+ getResolvedWorkflowEdges(project.projectGraph.nodes, project.projectGraph.edges).some(+ (edge) => edge.target === nodeId && edge.targetHandle === COMPANION_VIDEO_FIELD_NAME+ )+ );+ const siblingVideoName = useWorkflowProjectSelector((project) => {+ const node = nodeId ? project.projectGraph.nodes.find((candidate) => candidate.id === nodeId) : undefined;++ if (!node || !isInvocationNode(node)) {+ return null;+ }++ const sibling = node.data.inputs[COMPANION_VIDEO_FIELD_NAME]?.value as Record<string, unknown> | undefined;++ return typeof sibling?.video_name === 'string' && sibling.video_name !== '' ? sibling.video_name : null;+ });+ const videoName = isVideoConnected ? null : siblingVideoName;++ // Same query key as the media widget's badge lookup, so the two share a cache+ // entry when a frame field sits next to a populated video field (the common case).+ const { data, isError } = useQuery({+ enabled: videoName !== null,+ queryFn: ({ signal }) => galleryItems.resolve({ kind: 'video', name: videoName ?? '' }, signal),+ queryKey: ['workflow-media-field-item', 'video', videoName],+ retry: false,+ staleTime: 60_000,+ });+ // Rebind: useQuery's NoInfer-wrapped `data` defeats discriminant narrowing.+ const videoItem: GalleryItem | undefined = data;+ const video = videoItem && videoItem.kind === 'video' && videoItem.name === videoName ? videoItem : null;++ // Frame count is the slider's upper bound. duration*fps can be off-by-one for+ // VFR containers, but the slider is for visual scrubbing — the backend+ // re-resolves indices against the authoritative decoder count at invoke time.+ const fps = video?.fps ?? null;+ const frameCount =+ video && fps && video.durationSeconds > 0 ? Math.max(1, Math.round(video.durationSeconds * fps)) : null;++ // Resolve negative indices (-1 = last frame) for display only — the field+ // value is preserved verbatim so users can still type "-1" and have the+ // backend resolve it against the actual frame count.+ const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : 0;+ const resolvedIndex =+ frameCount === null+ ? 0+ : Math.max(0, Math.min(frameCount - 1, numericValue < 0 ? frameCount + numericValue : numericValue));++ return (+ <Flex direction="column" gap="1" w="full">+ <NumericInput {...props} />+ {video && fps !== null && frameCount !== null ? (+ <FrameScrubber+ fps={fps}+ frameCount={frameCount}+ resolvedIndex={resolvedIndex}+ videoUrl={video.fullUrl}+ onChange={onChange}+ />+ ) : (+ <Flex borderStyle="dashed" borderWidth="1px" justifyContent="center" px="2" py="2" rounded="sm">+ <Text color="fg.subtle" fontSize="xs" textAlign="center">+ {isVideoConnected+ ? 'Frame preview unavailable while the video comes from a graph connection.'+ : videoName === null+ ? "Set this node's Video field to preview frames."+ : isError+ ? 'Frame preview unavailable — the video could not be loaded (it may have been deleted).'+ : video === null+ ? 'Loading frame preview…'+ : 'Frame preview unavailable — the video has no probed frame rate.'}+ </Text>+ </Flex>+ )}+ </Flex>+ );+};++const FRAME_SLIDER_ARIA_LABEL = ['Frame'];+const FRAME_VIDEO_STYLE = { height: '100%', objectFit: 'contain', width: '100%' } as const;++const FrameScrubber = ({+ fps,+ frameCount,+ onChange,+ resolvedIndex,+ videoUrl,+}: {+ fps: number;+ frameCount: number;+ onChange: (value: unknown) => void;+ resolvedIndex: number;+ videoUrl: string;+}) => {+ const videoRef = useRef<HTMLVideoElement>(null);++ // Seek whenever the resolved index changes. The half-frame nudge lands the+ // seek inside the frame's display window — some codecs decode the exact+ // boundary as black on first paint without it.+ useEffect(() => {+ const el = videoRef.current;++ if (!el) {+ return;+ }++ const setTime = () => {+ try {+ el.currentTime = (resolvedIndex + 0.5) / fps;+ } catch {+ // Some browsers throw when seeking an element that isn't ready; the+ // preview keeps its previous frame and the next effect run re-seeks.+ }+ };++ if (el.readyState >= 1) {+ setTime();+ } else {+ el.addEventListener('loadedmetadata', setTime, { once: true });++ return () => el.removeEventListener('loadedmetadata', setTime);+ }+ }, [fps, resolvedIndex, videoUrl]);++ const onSliderChange = useCallback(+ ({ value: next }: { value: number[] }) => {+ if (next[0] !== undefined) {+ onChange(next[0]);+ }+ },+ [onChange]+ );+ const sliderValue = useMemo(() => [resolvedIndex], [resolvedIndex]);++ return (+ <Flex className="nodrag" direction="column" gap="1" w="full">+ <Box borderWidth="1px" h="32" overflow="hidden" position="relative" rounded="sm" w="full">+ <video ref={videoRef} muted playsInline preload="auto" src={videoUrl} style={FRAME_VIDEO_STYLE} />+ <Badge+ bottom="1"+ fontVariantNumeric="tabular-nums"+ insetInlineEnd="1"+ pointerEvents="none"+ position="absolute"+ size="xs"+ variant="solid"+ >+ {`${resolvedIndex} / ${frameCount - 1}`}+ </Badge>+ </Box>+ {/* A single-frame video would give the slider min === max, which zag renders as NaN% CSS. */}+ {frameCount > 1 ? (+ <Slider+ aria-label={FRAME_SLIDER_ARIA_LABEL}+ max={frameCount - 1}+ min={0}+ size="sm"+ step={1}+ value={sliderValue}+ withThumbTooltip+ onValueChange={onSliderChange}+ />+ ) : null}+ </Flex>+ );+};+/*** Workflow `ColorField` values carry alpha as a `[0, 255]` integer, unlike* every other color in the app (and unlike `RgbaColor`, whose alpha is a unit@@ -752,6 +950,11 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {case 'StringField':return <StringInput {...props} />;case 'IntegerField':+ if (props.template.uiComponent === 'video-frame-index' && props.template.type.cardinality === 'SINGLE') {+ return <VideoFrameIndexInput {...props} />;+ }++ return <NumericInput {...props} />;case 'FloatField':return <NumericInput {...props} />;case 'BooleanField':diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex 7e81cd692c..8c93f6c329 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -166,6 +166,7 @@ export const NodeFieldControl = ({<WorkflowFieldInputid={valueInputId}invalid={isInvalid}+ nodeId={nodeId}template={template}value={instance?.value}onChange={onValueChange}