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.

feat(webv2): direct-input media widgets for ImageField and VideoField workflow fields

Lincoln Steine550eace82ef
diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.ts
index 043eba1d7d..154cf09f49 100644
--- a/invokeai/frontend/webv2/src/features/gallery/index.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts
@@ -63,6 +63,7 @@ import {
type GalleryItemOrganizationTransportResult,
unstarGalleryImages,
uploadGalleryImage,
+ uploadGalleryVideo,
} from './data/backend';
/** Resolve backend Gallery images without exposing transport DTOs or endpoints. */
@@ -87,6 +88,7 @@ export const galleryVideos = {
export const galleryTransfers = {
downloadArchive: downloadGalleryArchive,
upload: uploadGalleryImage,
+ uploadVideo: uploadGalleryVideo,
} as const;
/** Durability transitions for intermediate results. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/utility.ts b/invokeai/frontend/webv2/src/features/gallery/utility.ts
index 4eef91f783..951a94ef24 100644
--- a/invokeai/frontend/webv2/src/features/gallery/utility.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/utility.ts
@@ -19,8 +19,14 @@ export {
} from './ui/galleryDnd';
import { getGalleryImageFullUrl, getGalleryImageThumbnailUrl } from './data/imageUrls';
+import { getGalleryVideoFullUrl, getGalleryVideoThumbnailUrl } from './data/videoUrls';
export const galleryImageUrls = {
full: getGalleryImageFullUrl,
thumbnail: getGalleryImageThumbnailUrl,
} as const;
+
+export const galleryVideoUrls = {
+ full: getGalleryVideoFullUrl,
+ thumbnail: getGalleryVideoThumbnailUrl,
+} as const;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index b1d9ac5270..68f38b8e13 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -83,6 +83,21 @@ describe('workflow field validation', () => {
expect(isWorkflowFieldValueValid(input({ type: single('ImageField') }), { image_name: '' })).toBe(false);
});
+ it('validates video fields like image fields (direct-input media)', () => {
+ expect(isWorkflowFieldValueValid(input({ type: single('VideoField') }), { video_name: 'clip.mp4' })).toBe(true);
+ expect(isWorkflowFieldValueValid(input({ type: single('VideoField') }), { video_name: '' })).toBe(false);
+ expect(isWorkflowFieldValueValid(input({ type: single('VideoField') }), {})).toBe(false);
+ });
+
+ it('keeps COLLECTION media values on the generic non-null check (persisted arrays stay valid)', () => {
+ const videos = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'VideoField' } });
+ const images = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' } });
+
+ expect(isWorkflowFieldValueValid(videos, [{ video_name: 'a.mp4' }, { video_name: 'b.mp4' }])).toBe(true);
+ expect(isWorkflowFieldValueValid(videos, undefined)).toBe(false);
+ expect(isWorkflowFieldValueValid(images, [{ image_name: 'a.png' }])).toBe(true);
+ });
+
it('treats empty board values as the Auto sentinel', () => {
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), undefined)).toBe(true);
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), { board_id: 'board-id' })).toBe(true);
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index 0d2430b85a..23d542d731 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -18,6 +18,7 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'ModelIdentifierField',
'SchedulerField',
'StringField',
+ 'VideoField',
]);
export const isStatefulFieldType = (type: FieldType): boolean => STATEFUL_FIELD_TYPE_NAMES.has(type.name);
@@ -139,7 +140,20 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
hasNonEmptyStringProp(value, 'board_id')
);
case 'ImageField':
+ // COLLECTION media values are arrays the direct-input widget never
+ // authors; keep the generic non-null check for them so persisted array
+ // values (imported workflows) stay exactly as valid as before.
+ if (template.type.cardinality === 'COLLECTION') {
+ return value !== undefined && value !== null;
+ }
+
return hasNonEmptyStringProp(value, 'image_name');
+ case 'VideoField':
+ if (template.type.cardinality === 'COLLECTION') {
+ return value !== undefined && value !== null;
+ }
+
+ return hasNonEmptyStringProp(value, 'video_name');
case 'ColorField':
return isColorValueValid(value);
default:
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.tsx
index 524d406abd..9c717f2e5d 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
@@ -1,6 +1,8 @@
import type { FieldInputTemplate } from '@features/workflow/contracts';
import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -10,6 +12,26 @@ import { WorkflowFieldInput } from './WorkflowFieldInput';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const uploadImageMock = vi.fn();
+const uploadVideoMock = vi.fn();
+
+vi.mock('@features/gallery', () => ({
+ galleryDestinations: { list: () => Promise.resolve([]) },
+ galleryTransfers: {
+ upload: (...args: unknown[]) => uploadImageMock(...args),
+ uploadVideo: (...args: unknown[]) => uploadVideoMock(...args),
+ },
+}));
+
+const galleryValues: Record<string, unknown> = {};
+const projectSnapshot = { galleryValues, id: 'project-1' };
+
+vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({
+ useWorkflowProjectSelector: (selector: (project: { galleryValues: Record<string, unknown> }) => unknown) =>
+ selector(projectSnapshot),
+ useWorkflowUi: () => ({ project: { getSnapshot: () => projectSnapshot } }),
+}));
+
const TEXTAREA_TEMPLATE = {
name: 'prompt',
title: 'Prompt',
@@ -17,29 +39,73 @@ const TEXTAREA_TEMPLATE = {
uiComponent: 'textarea',
} as unknown as FieldInputTemplate;
-describe('WorkflowFieldInput textarea', () => {
- let host: HTMLDivElement;
- let root: Root;
+const VIDEO_TEMPLATE = {
+ name: 'video',
+ title: 'Video',
+ type: { name: 'VideoField' },
+} as unknown as FieldInputTemplate;
- beforeEach(() => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- });
+const SELECTED_GALLERY_VIDEO = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-01-01T00:00:00Z',
+ durationSeconds: 5,
+ fullUrl: '/api/v1/videos/i/clip.mp4/full',
+ height: 480,
+ isIntermediate: false,
+ kind: 'video',
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/api/v1/videos/i/clip.mp4/thumbnail',
+ width: 640,
+};
+
+let host: HTMLDivElement;
+let root: Root;
- afterEach(async () => {
- await act(() => root.unmount());
- host.remove();
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ uploadImageMock.mockReset();
+ uploadVideoMock.mockReset();
+ delete galleryValues.selectedImage;
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+const queryClient = new QueryClient();
+
+const renderField = async (template: FieldInputTemplate, value: unknown, onChange: (value: unknown) => void) => {
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <DndContext>
+ <WorkflowFieldInput template={template} value={value} onChange={onChange} />
+ </DndContext>
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
});
+};
+
+const findButton = (label: string): HTMLButtonElement => {
+ const button = Array.from(host.querySelectorAll('button')).find((el) => el.textContent?.includes(label));
+
+ if (!button) {
+ throw new Error(`Button "${label}" not found`);
+ }
+ return button;
+};
+
+describe('WorkflowFieldInput textarea', () => {
it('uses the accessible unbounded resizable textarea for prompt-like string fields', async () => {
- await act(() => {
- root.render(
- <ChakraProvider value={system}>
- <WorkflowFieldInput template={TEXTAREA_TEMPLATE} value="hello" onChange={vi.fn()} />
- </ChakraProvider>
- );
- });
+ await renderField(TEXTAREA_TEMPLATE, 'hello', vi.fn());
const textarea = host.querySelector<HTMLTextAreaElement>('textarea')!;
const handle = host.querySelector<HTMLElement>('[role="separator"]')!;
@@ -54,3 +120,120 @@ describe('WorkflowFieldInput textarea', () => {
expect(getComputedStyle(textarea).height).toBe('108px');
});
});
+
+describe('WorkflowFieldInput media inputs', () => {
+ it('renders a direct-input widget for VideoField instead of falling back to connection-only', async () => {
+ await renderField(VIDEO_TEMPLATE, undefined, vi.fn());
+
+ expect(host.textContent).not.toContain('Connection only');
+ expect(host.textContent).toContain('No video set');
+ expect(findButton('Use gallery selection').disabled).toBe(true);
+ expect(findButton('Upload').disabled).toBe(false);
+ expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.accept).toBe('video/*');
+ });
+
+ it('adopts a selected gallery video and clears it', async () => {
+ galleryValues.selectedImage = SELECTED_GALLERY_VIDEO;
+ const onChange = vi.fn();
+
+ await renderField(VIDEO_TEMPLATE, undefined, onChange);
+
+ const useSelection = findButton('Use gallery selection');
+
+ expect(useSelection.disabled).toBe(false);
+ await act(() => useSelection.click());
+ expect(onChange).toHaveBeenCalledWith({ video_name: 'clip.mp4' });
+
+ await renderField(VIDEO_TEMPLATE, { video_name: 'clip.mp4' }, onChange);
+ expect(host.textContent).toContain('clip.mp4');
+ expect(host.querySelector('img')?.src).toContain('/api/v1/videos/i/clip.mp4/thumbnail');
+
+ await act(() => findButton('Clear').click());
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('does not offer a selected gallery image to a video field', async () => {
+ galleryValues.selectedImage = { ...SELECTED_GALLERY_VIDEO, kind: 'image' };
+
+ await renderField(VIDEO_TEMPLATE, undefined, vi.fn());
+
+ expect(findButton('Use gallery selection').disabled).toBe(true);
+ });
+
+ it('keeps COLLECTION media fields connection-only (the widget would write a bare object into a list)', async () => {
+ const collectionTemplate = {
+ name: 'videos',
+ title: 'Videos',
+ type: { cardinality: 'COLLECTION', name: 'VideoField' },
+ } as unknown as FieldInputTemplate;
+
+ await renderField(collectionTemplate, undefined, vi.fn());
+
+ expect(host.textContent).toContain('Connection only');
+ expect(host.querySelector('input[type="file"]')).toBeNull();
+ });
+
+ it('rejects a file whose type does not match the field kind', async () => {
+ const onChange = vi.fn();
+
+ await renderField(VIDEO_TEMPLATE, undefined, onChange);
+
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(new File(['data'], 'a.png', { type: 'image/png' }));
+ fileInput.files = transfer.files;
+ await act(() => fileInput.dispatchEvent(new Event('change', { bubbles: true })));
+
+ expect(uploadVideoMock).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('uploads a picked file and adopts the uploaded video', async () => {
+ uploadVideoMock.mockResolvedValue({ kind: 'video', name: 'uploaded.mp4' });
+ const onChange = vi.fn();
+
+ await renderField(VIDEO_TEMPLATE, undefined, onChange);
+ await act(() => findButton('Upload').click());
+
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(new File(['data'], 'clip.mp4', { type: 'video/mp4' }));
+ fileInput.files = transfer.files;
+ await act(() => fileInput.dispatchEvent(new Event('change', { bubbles: true })));
+
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith({ video_name: 'uploaded.mp4' });
+ });
+ expect(uploadVideoMock).toHaveBeenCalledTimes(1);
+ expect(uploadVideoMock.mock.calls[0]?.[1]).toBe('none');
+ });
+
+ it('keeps the image field on the image upload path', async () => {
+ uploadImageMock.mockResolvedValue({ imageName: 'uploaded.png' });
+ const onChange = vi.fn();
+ const imageTemplate = {
+ name: 'image',
+ title: 'Image',
+ type: { name: 'ImageField' },
+ } as unknown as FieldInputTemplate;
+
+ await renderField(imageTemplate, undefined, onChange);
+
+ expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.accept).toBe('image/*');
+ await act(() => findButton('Upload').click());
+
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(new File(['data'], 'a.png', { type: 'image/png' }));
+ fileInput.files = transfer.files;
+ await act(() => fileInput.dispatchEvent(new Event('change', { bubbles: true })));
+
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith({ image_name: 'uploaded.png' });
+ });
+ expect(uploadVideoMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 95ccc50cf2..007e3facb3 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -1,19 +1,39 @@
import type { ModelConfig, ModelTaxonomyType } from '@features/models/react';
import type { FieldInputTemplate } from '@features/workflow/contracts';
-import { createListCollection, HStack, Input, Switch, Text } from '@chakra-ui/react';
-import { galleryDestinations, type GalleryBoard } from '@features/gallery';
-import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
+import { Box, createListCollection, HStack, Image, Input, Switch, Text } from '@chakra-ui/react';
+import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent } from '@dnd-kit/core';
+import { galleryDestinations, galleryTransfers, type GalleryBoard } 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 { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';
+import {
+ getWorkflowMediaFieldDropId,
+ getWorkflowMediaFieldDropItem,
+ type WorkflowMediaKind,
+} from '@features/workflow/ui/fields/mediaFieldDnd';
+import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
import {
assertAccountScopeCurrent,
captureAccountScope,
+ isAccountScopeCurrent,
registerAccountOwnedResource,
type AccountScope,
} from '@platform/state/accountLifecycle';
-import { Button, ColorPicker, Combobox, formatHexColor, parseHexColor, ResizableTextarea, Select } from '@platform/ui';
-import { lazy, Suspense, useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react';
+import {
+ Button,
+ ColorPicker,
+ Combobox,
+ DropZone,
+ formatHexColor,
+ parseHexColor,
+ ResizableTextarea,
+ Select,
+ toaster,
+} from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
+import { lazy, Suspense, useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';
const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));
const MODEL_SELECT_FALLBACK = (
@@ -23,6 +43,7 @@ const MODEL_SELECT_FALLBACK = (
);
export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;
+export const getWorkflowSelectedGalleryItem = getSelectedGalleryItemFromValues;
/**
* Direct-input controls for workflow fields, shared between the node editor
@@ -367,56 +388,243 @@ const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInp
);
};
-const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
- const gallerySelection = useWorkflowProjectSelector((project) =>
- getWorkflowSelectedGalleryImage(project.galleryValues)
+const MEDIA_FIELD_CONFIG = {
+ image: {
+ fileAccept: 'image/*',
+ getThumbnailUrl: (name: string) => galleryImageUrls.thumbnail(name),
+ nameKey: 'image_name',
+ noun: 'image',
+ },
+ video: {
+ fileAccept: 'video/*',
+ getThumbnailUrl: (name: string) => galleryVideoUrls.thumbnail(name),
+ nameKey: 'video_name',
+ noun: 'video',
+ },
+} as const satisfies Record<
+ WorkflowMediaKind,
+ { fileAccept: string; getThumbnailUrl: (name: string) => string; nameKey: string; noun: string }
+>;
+
+const HIDDEN_FILE_INPUT_STYLE = { display: 'none' } as const;
+
+/**
+ * Direct input for `ImageField` / `VideoField`: shows the current item with a
+ * thumbnail, adopts the gallery selection, accepts a single-item gallery drag
+ * onto the row, and uploads a local file to the gallery's selected board.
+ */
+const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputProps & { kind: WorkflowMediaKind }) => {
+ const config = MEDIA_FIELD_CONFIG[kind];
+ const selectedGalleryItem = useWorkflowProjectSelector((project) =>
+ getWorkflowSelectedGalleryItem(project.galleryValues)
+ );
+ const gallerySelection = selectedGalleryItem?.kind === kind ? selectedGalleryItem : null;
+ const uploadBoardId = useWorkflowProjectSelector((project) =>
+ typeof project.galleryValues.selectedBoardId === 'string' ? project.galleryValues.selectedBoardId : 'none'
);
- const imageName =
- typeof (value as { image_name?: unknown } | null)?.image_name === 'string'
- ? (value as { image_name: string }).image_name
+ const mediaName =
+ typeof (value as Record<string, unknown> | null | undefined)?.[config.nameKey] === 'string'
+ ? ((value as Record<string, string>)[config.nameKey] ?? null)
: null;
const invalidAriaProps = useMemo(() => (invalid ? { 'aria-invalid': true } : {}), [invalid]);
+
+ // dnd: the whole input row is a drop target for a single gallery item of the
+ // matching kind. The instance-unique suffix keeps ids distinct when the node
+ // editor and the Linear UI panel render the same field at once.
+ const instanceId = useId();
+ const dropId = getWorkflowMediaFieldDropId(`${id ?? 'field'}:${instanceId}`);
+ const { active } = useDndContext();
+ const acceptsActiveDrag = getWorkflowMediaFieldDropItem(active?.data.current, kind) !== null;
+ const { isOver, setNodeRef } = useDroppable({ disabled: !acceptsActiveDrag, id: dropId });
+ const onDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ if (event.over?.id !== dropId) {
+ return;
+ }
+
+ const item = getWorkflowMediaFieldDropItem(event.active.data.current, kind);
+
+ if (item) {
+ onChange({ [config.nameKey]: item.name });
+ }
+ },
+ [config.nameKey, dropId, kind, onChange]
+ );
+
+ useDndMonitor({ onDragEnd });
+
+ // Upload: file picker -> gallery upload -> adopt the uploaded item. The
+ // adoption is pinned to this widget instance AND the project it started in:
+ // `onChange` dispatches into the *active* project, so a completion arriving
+ // after a project switch (or after this node was deleted, which unmounts the
+ // widget) must not be applied - the upload itself still succeeded, so the
+ // gallery is refreshed and the user is pointed there instead.
+ const { project } = useWorkflowUi();
+ const queryClient = useQueryClient();
+ const isMountedRef = useRef(true);
+
+ useEffect(
+ () => () => {
+ isMountedRef.current = false;
+ },
+ []
+ );
+
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [isUploading, setIsUploading] = useState(false);
+ const onUploadClick = useCallback(() => fileInputRef.current?.click(), []);
+ const onFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ // Reset so picking the same file again re-fires the change event.
+ event.currentTarget.value = '';
+
+ if (!file) {
+ return;
+ }
+
+ // `accept` on the input is advisory only ("All Files" bypasses it); an
+ // unknown type (empty string) is left for the server to judge.
+ if (file.type && !file.type.startsWith(`${kind}/`)) {
+ toaster.create({ title: `Please choose a ${config.noun} file`, type: 'error' });
+
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const projectId = project.getSnapshot().id;
+
+ setIsUploading(true);
+ void (async () => {
+ try {
+ const name =
+ kind === 'image'
+ ? (await galleryTransfers.upload(file, uploadBoardId, { signal: owner.signal })).imageName
+ : (await galleryTransfers.uploadVideo(file, uploadBoardId, { signal: owner.signal })).name;
+
+ assertAccountScopeCurrent(owner);
+ void invalidateGallery(queryClient, owner);
+
+ if (isMountedRef.current && project.getSnapshot().id === projectId) {
+ onChange({ [config.nameKey]: name });
+ } else {
+ toaster.create({
+ description: `The workflow changed while ${name} uploaded - find it in the gallery.`,
+ title: 'Upload finished',
+ type: 'info',
+ });
+ }
+ } catch {
+ if (isAccountScopeCurrent(owner)) {
+ toaster.create({ title: `Failed to upload ${config.noun}`, type: 'error' });
+ }
+ } finally {
+ if (isAccountScopeCurrent(owner) && isMountedRef.current) {
+ setIsUploading(false);
+ }
+ }
+ })();
+ },
+ [config.nameKey, config.noun, kind, onChange, project, queryClient, uploadBoardId]
+ );
+
const onUseGallerySelectionClick = useCallback(() => {
if (gallerySelection) {
- onChange({ image_name: gallerySelection.imageName });
+ onChange({ [config.nameKey]: gallerySelection.name });
}
- }, [gallerySelection, onChange]);
+ }, [config.nameKey, gallerySelection, onChange]);
const onClearClick = useCallback(() => onChange(undefined), [onChange]);
+ // A stale value (media deleted since the workflow was saved) 404s the
+ // thumbnail; hide the broken-image glyph and keep showing the name. A new
+ // value retries.
+ const [failedThumbnail, setFailedThumbnail] = useState<string | null>(null);
+ const onThumbnailError = useCallback(() => setFailedThumbnail(mediaName), [mediaName]);
+
return (
- <HStack
- boxShadow={invalid ? '0 0 0 1px {colors.red.solid}' : undefined}
- gap="1.5"
- minW="0"
- rounded="sm"
- w="full"
- {...invalidAriaProps}
- >
- {imageName ? (
- <Text color="fg.muted" flex="1" fontSize="2xs" minW="0" title={imageName} truncate>
- {imageName}
- </Text>
- ) : (
- <Text color="fg.subtle" flex="1" fontSize="2xs">
- No image set
- </Text>
- )}
- <Button
- className="nodrag"
- disabled={!gallerySelection}
- size="2xs"
- title={gallerySelection ? `Use ${gallerySelection.imageName}` : 'Select an image in the Gallery first.'}
- variant="outline"
- onClick={onUseGallerySelectionClick}
+ <Box ref={setNodeRef} position="relative" w="full">
+ <HStack
+ boxShadow={invalid ? '0 0 0 1px {colors.red.solid}' : undefined}
+ gap="1.5"
+ minW="0"
+ rounded="sm"
+ w="full"
+ {...invalidAriaProps}
>
- Use gallery selection
- </Button>
- {imageName ? (
- <Button className="nodrag" size="2xs" variant="ghost" onClick={onClearClick}>
- Clear
+ {mediaName ? (
+ <>
+ {failedThumbnail !== mediaName ? (
+ <Image
+ alt=""
+ boxSize="6"
+ flexShrink={0}
+ objectFit="cover"
+ rounded="xs"
+ src={config.getThumbnailUrl(mediaName)}
+ onError={onThumbnailError}
+ />
+ ) : null}
+ <Text color="fg.muted" flex="1" fontSize="2xs" minW="0" title={mediaName} truncate>
+ {mediaName}
+ </Text>
+ </>
+ ) : (
+ <Text color="fg.subtle" flex="1" fontSize="2xs">
+ {`No ${config.noun} set`}
+ </Text>
+ )}
+ <Button
+ className="nodrag"
+ disabled={!gallerySelection}
+ size="2xs"
+ title={gallerySelection ? `Use ${gallerySelection.name}` : `Select a ${config.noun} in the Gallery first.`}
+ variant="outline"
+ onClick={onUseGallerySelectionClick}
+ >
+ Use gallery selection
+ </Button>
+ <Button
+ className="nodrag"
+ disabled={isUploading}
+ size="2xs"
+ title={`Upload a ${config.noun} and use it here`}
+ variant="outline"
+ onClick={onUploadClick}
+ >
+ {isUploading ? 'Uploading…' : 'Upload'}
</Button>
+ {mediaName ? (
+ <Button className="nodrag" size="2xs" variant="ghost" onClick={onClearClick}>
+ Clear
+ </Button>
+ ) : null}
+ <input
+ ref={fileInputRef}
+ accept={config.fileAccept}
+ aria-label={`Upload ${config.noun} file`}
+ style={HIDDEN_FILE_INPUT_STYLE}
+ type="file"
+ onChange={onFileChange}
+ />
+ </HStack>
+ {acceptsActiveDrag ? (
+ <DropZone
+ alignItems="center"
+ display="flex"
+ inset="0"
+ isOver={isOver}
+ justifyContent="center"
+ pointerEvents="none"
+ position="absolute"
+ variant="overlay"
+ >
+ <Text fontSize="2xs" fontWeight="700">
+ {`Drop ${config.noun}`}
+ </Text>
+ </DropZone>
) : null}
- </HStack>
+ </Box>
);
};
@@ -458,7 +666,24 @@ const ColorInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
);
};
+const CONNECTION_ONLY_FALLBACK = (
+ <Text color="fg.subtle" fontSize="2xs">
+ Connection only
+ </Text>
+);
+
export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
+ // COLLECTION media fields (e.g. Concatenate Videos' list input) hold arrays;
+ // the single-value media widget would write a bare object into them. The
+ // node editor never shows a control for COLLECTION fields, but linear-form
+ // elements migrated from legacy `exposedFields` can reach here directly.
+ if (
+ (props.template.type.name === 'ImageField' || props.template.type.name === 'VideoField') &&
+ props.template.type.cardinality === 'COLLECTION'
+ ) {
+ return CONNECTION_ONLY_FALLBACK;
+ }
+
switch (props.template.type.name) {
case 'StringField':
return <StringInput {...props} />;
@@ -476,14 +701,12 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
case 'BoardField':
return <BoardInput {...props} />;
case 'ImageField':
- return <ImageInput {...props} />;
+ return <MediaInput {...props} kind="image" />;
+ case 'VideoField':
+ return <MediaInput {...props} kind="video" />;
case 'ColorField':
return <ColorInput {...props} />;
default:
- return (
- <Text color="fg.subtle" fontSize="2xs">
- Connection only
- </Text>
- );
+ return CONNECTION_ONLY_FALLBACK;
}
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts
new file mode 100644
index 0000000000..b594f1b117
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWorkflowMediaFieldDropId, getWorkflowMediaFieldDropItem } from './mediaFieldDnd';
+
+const drag = (items: { kind: string; name: string }[]) => ({ items, kind: 'gallery-item' });
+
+describe('getWorkflowMediaFieldDropItem', () => {
+ it('accepts a single gallery item of the matching kind', () => {
+ expect(getWorkflowMediaFieldDropItem(drag([{ kind: 'video', name: 'clip.mp4' }]), 'video')).toEqual({
+ kind: 'video',
+ name: 'clip.mp4',
+ });
+ expect(getWorkflowMediaFieldDropItem(drag([{ kind: 'image', name: 'a.png' }]), 'image')).toEqual({
+ kind: 'image',
+ name: 'a.png',
+ });
+ });
+
+ it('rejects kind mismatches', () => {
+ expect(getWorkflowMediaFieldDropItem(drag([{ kind: 'image', name: 'a.png' }]), 'video')).toBeNull();
+ expect(getWorkflowMediaFieldDropItem(drag([{ kind: 'video', name: 'clip.mp4' }]), 'image')).toBeNull();
+ });
+
+ it('rejects multi-item drags outright rather than keeping the first item', () => {
+ expect(
+ getWorkflowMediaFieldDropItem(
+ drag([
+ { kind: 'video', name: 'a.mp4' },
+ { kind: 'video', name: 'b.mp4' },
+ ]),
+ 'video'
+ )
+ ).toBeNull();
+ });
+
+ it('rejects payloads that are not gallery item drags', () => {
+ expect(getWorkflowMediaFieldDropItem(null, 'video')).toBeNull();
+ expect(getWorkflowMediaFieldDropItem({ kind: 'gallery-board' }, 'video')).toBeNull();
+ expect(getWorkflowMediaFieldDropItem(drag([]), 'video')).toBeNull();
+ });
+});
+
+describe('getWorkflowMediaFieldDropId', () => {
+ it('namespaces ids so they cannot collide with other droppables', () => {
+ expect(getWorkflowMediaFieldDropId('node-1-video:r1')).toBe('workflow-media-field:node-1-video:r1');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts
new file mode 100644
index 0000000000..d7e97f602e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts
@@ -0,0 +1,34 @@
+import { isGalleryItemDragData } from '@features/gallery/utility';
+
+/**
+ * Drop plumbing for the media (image/video) workflow field inputs: a gallery
+ * item dragged onto a field's input row sets that field's value.
+ */
+
+export type WorkflowMediaKind = 'image' | 'video';
+
+export interface WorkflowMediaDropItem {
+ kind: WorkflowMediaKind;
+ name: string;
+}
+
+export const getWorkflowMediaFieldDropId = (fieldKey: string): string => `workflow-media-field:${fieldKey}`;
+
+/**
+ * Resolves a gallery drag payload to the single item a media field can accept,
+ * or null. Multi-item drags are rejected outright: a single-value field
+ * silently keeping only the first of several dragged items would misread the
+ * user's intent.
+ */
+export const getWorkflowMediaFieldDropItem = (
+ activeData: unknown,
+ kind: WorkflowMediaKind
+): WorkflowMediaDropItem | null => {
+ if (!isGalleryItemDragData(activeData) || activeData.items.length !== 1) {
+ return null;
+ }
+
+ const item = activeData.items[0];
+
+ return item && item.kind === kind ? { kind: item.kind, name: item.name } : null;
+};