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: pick gallery media from every image and video slot
Josh Corbett27fabbe93d5b
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 35a0aa177d..6c87afd0c3 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1709,6 +1709,7 @@"addConcept": "Add concept","addConceptsHelp": "Add LoRAs/concepts here to blend them into this generation.","addPromptTrigger": "Add prompt trigger",+ "addReferenceImage": "Add reference image","advanced": "Advanced","aspectRatio": "Aspect ratio","cfgRescale": "CFG rescale",@@ -2005,7 +2006,6 @@"referenceImage": "Reference Image","referenceImageModel": "Reference image model","referenceImages": "Reference images",- "referenceImagesHelp": "Upload an image or drag images from Gallery here.","referenceImagesUnsupported": "Reference images are not supported by the selected model.","referencesMax": "References ×{{count}}","removeConcept": "Remove concept",@@ -2087,11 +2087,9 @@"creativity": "Creativity","creativityHelp": "Higher values invent more detail and increase prompt influence.","detailGuidance": "Detail guidance",- "dropImage": "Drop Image","enableNegativePrompt": "Enable negative prompt","generation": "Generation","inputSize": "Input",- "inputImageAlt": "Upscale input image","largeOutput": "Large output","largeOutputDescription": "This output may take substantially longer and require more VRAM. Check tile settings before queueing.","lorasRemoved": "Removed {{count}} incompatible LoRA model(s).",@@ -2123,10 +2121,7 @@"random": "Random","ready": "Ready","readyDescription": "The upscale graph is ready to queue.",- "removeImage": "Remove image","removeLora": "Remove {{name}}",- "replaceImage": "Replace upscale input image",- "replaceOrDrop": "Replace or drop another image","scale": "Scale","scaleHelp": "Output dimensions are the source dimensions multiplied by this value.","scheduler": "Scheduler",@@ -2153,11 +2148,7 @@"tileOverlapHelp": "More overlap reduces seams but increases processing and memory use.","tileSize": "Tile size","tileSizeHelp": "Larger tiles may improve continuity but require more VRAM.",- "unsupportedFile": "Upscale accepts PNG, JPEG, and WebP images.","upscale": "Upscale",- "uploadImage": "Upload upscale input image",- "uploadOrDrop": "Upload a PNG, JPEG, or WebP, or drop one image from Gallery",- "uploadingImage": "Uploading image…","vae": "VAE","vaeCleared": "The incompatible VAE was cleared.","vaePrecision": "VAE precision"@@ -3119,11 +3110,10 @@"positivePrompt": "Positive prompt","positivePromptPlaceholder": "Region positive prompt","referenceImage": "Reference image",- "referenceImageHelp": "Upload or drag an image from the gallery.",+ "referenceImageHelp": "Choose an image from the gallery, drop one here, or upload a file.","referenceImages": "Reference images","removeReferenceImage": "Remove reference image","selectModel": "Select a model",- "setReferenceImage": "Set reference image","weight": "Weight"},"types": {@@ -3466,6 +3456,7 @@"cfg": "CFG","cfgLowNoise": "CFG (Low Noise)","cfgLowNoiseHelp": "Guidance for the low-noise half of the A14B expert schedule.",+ "chooseReference": "Choose from Gallery","derivedSize": "Output size: {{width}} × {{height}}","derivedSizeUnavailable": "Output size unavailable for the current settings.","dimensions": "Dimensions",@@ -3506,23 +3497,15 @@"lastFrameExtendHelp": "Optional destination: the extension ends on this image.","lastFrameHelp": "Optional: the video ends on this image (interpolates from the first frame).","removeClip": "Remove video",- "removeFrame": "Remove",- "replaceClip": "Replace the initial video",- "replaceFrame": "Replace the frame image","trim": "Trim","trimEnd": "End Frame","trimEndShort": "End","trimHelp": "The kept range of the source clip. The extension continues from the end frame.","trimStart": "Start Frame","trimStartShort": "Start",- "unsupportedImageFile": "Please choose a PNG, JPEG, or WebP image.","unsupportedVideoFile": "Please choose a video file.",- "uploadClip": "Upload a video",- "uploadFrame": "Upload a frame image",- "uploadOrDropClip": "Upload or drop a video from the Gallery",- "uploadOrDropFrame": "Upload or drop an image from the Gallery",+ "uploadImageReference": "Upload image","uploadingClip": "Uploading video…",- "uploadingFrame": "Uploading image…","clearStaleMedia": "Clear","staleFirstFrame": "A first frame is set, but this model does not support starting from one.","staleLastFrame": "A last frame is set, but this model does not support ending on one.",@@ -3547,9 +3530,7 @@"swap": "Swap experts","swapped": "The filename tags suggest these two experts are swapped. The wiring is authoritative — swap if unintended."},- "addImageReference": "Add image ({{count}}/{{max}})","addReference": "Add reference",- "addVideoReference": "Add video ({{count}}/{{max}})","dropReference": "Drop Reference","moveReferenceDown": "Move reference down","moveReferenceUp": "Move reference up",@@ -3567,7 +3548,8 @@"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.","removeReference": "Remove reference",- "staleReferences": "References are set but the selected model cannot use them."+ "staleReferences": "References are set but the selected model cannot use them.",+ "uploadVideoReference": "Upload video"}},"workflowLibrary": {diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsxindex de4e5afc94..5345ef0cc2 100644--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx@@ -1,10 +1,8 @@import type { UpscaleUiAdapter } from '@features/upscale';import type { ReactNode } from 'react';-import { invalidateGallery } from '@features/gallery/queries';import { areProjectPromptDraftsEqual, getPromptDraftFromValues } from '@features/generation/settings';import { UpscaleUiProvider } from '@features/upscale';-import { useQueryClient } from '@tanstack/react-query';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';@@ -36,7 +34,6 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })(preferences) => preferences.showPromptSyntaxHighlighting);const commands = useWorkbenchCommands();- const queryClient = useQueryClient();// The port's callbacks are keyed to the project, not to its contents: rebuilding// them whenever `rawValues` changes would hand every consumer new function// identities on each keystroke, re-rendering memoized fields that did not change.@@ -53,7 +50,6 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })(message) => commands.notifications.reportError({ area: 'upscale', message, namespace: 'generation' }),[commands]);- const touchGalleryImages = useCallback(() => void invalidateGallery(queryClient), [queryClient]);const adapter = useMemo<UpscaleUiAdapter>(() => ({...project,@@ -61,9 +57,8 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })patchValues,reportError,showPromptSyntaxHighlighting,- touchGalleryImages,}),- [patchPromptDraft, patchValues, project, reportError, showPromptSyntaxHighlighting, touchGalleryImages]+ [patchPromptDraft, patchValues, project, reportError, showPromptSyntaxHighlighting]);return <UpscaleUiProvider adapter={adapter}>{children}</UpscaleUiProvider>;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex 2da782df56..a83258592c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -1,3 +1,5 @@+import type { GalleryItem } from '@features/gallery';+import type { GalleryPickerSelection } from '@features/gallery/picker';import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type {GenerateModelConfig,@@ -8,9 +10,10 @@ import type {import type { GenerateSettingsUpdate } from '@features/generation/ui/generateDebounce';import type { ChangeEvent } from 'react';-import { HStack, Input, Stack, Text } from '@chakra-ui/react';+import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';import { useDndMonitor } from '@dnd-kit/core';-import { galleryImages, galleryTransfers } from '@features/gallery';+import { galleryImages, galleryTransfers, toGalleryItemKey } from '@features/gallery';+import { GalleryPickerPopover } from '@features/gallery/picker';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import {createReferenceImageId,@@ -28,13 +31,14 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { Button, DropTargetOverlay, DropZone } from '@platform/ui';-import { UploadIcon } from 'lucide-react';-import { useCallback, useRef } from 'react';+import { ChevronDownIcon, ImagePlusIcon, UploadIcon } from 'lucide-react';+import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { ReferenceImageCard } from './ReferenceImageCard';const UPLOAD_ZONE_HOVER_STYLES = { bg: 'bg.muted', color: 'fg' };+const IMAGE_ONLY = ['image'] as const;interface GenerateReferenceImagesContentProps {models: readonly ModelConfig[];@@ -118,6 +122,30 @@ export const GenerateReferenceImagesContent = ({const clearReferenceImages = useCallback(() => onCommitImmediate({ referenceImages: [] }), [onCommitImmediate]);+ const pickerSelection = useMemo<GalleryPickerSelection>(+ () => ({+ addedKeys: new Set(+ referenceImages.flatMap(({ config }) =>+ config.image ? [toGalleryItemKey({ kind: 'image', name: config.image.original.image.image_name })] : []+ )+ ),+ mode: 'multiple',+ remaining: { image: Math.max(0, maxReferenceImages - referenceImageCount) },+ }),+ [maxReferenceImages, referenceImageCount, referenceImages]+ );++ const handlePick = useCallback(+ (item: GalleryItem) => {+ if (item.kind === 'image') {+ appendReferenceImages([+ generatedImageToReferenceImage({ height: item.height, imageName: item.name, width: item.width }),+ ]);+ }+ },+ [appendReferenceImages]+ );+const applyReferenceImageSize = useCallback((image: GenerateReferenceImageAsset) => {if (!selectedModel) {@@ -236,28 +264,46 @@ export const GenerateReferenceImagesContent = ({isOver={isOver}label={t('widgets.generate.dropReferenceImages')}/>- <HStack align="stretch" gap="2">+ <GalleryPickerPopover+ accept={IMAGE_ONLY}+ label={t('widgets.generate.addReferenceImage')}+ selection={pickerSelection}+ onPick={handlePick}+ ><DropZoneas="button"alignItems="center"cursor={canAdd ? undefined : 'not-allowed'}+ disabled={!canAdd}display="flex"- flex="1"+ flexDirection="column"fontSize="2xs"- gap="2"+ gap="1"isDisabled={!canAdd}isOver={isOver}justifyContent="center"- minH="12"+ minH="14"minW="0"opacity={canAdd ? 1 : 0.6}px="3"+ w="full"_hover={canAdd ? UPLOAD_ZONE_HOVER_STYLES : undefined}- onClick={handleUploadZoneClick}>- <UploadIcon size="14" />- {t('widgets.generate.referenceImagesHelp')}+ <HStack as="span" color="fg" fontSize="xs" fontWeight="600" gap="1.5">+ <Icon as={ImagePlusIcon} boxSize="4" />+ {t('widgets.generate.addReferenceImage')}+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />+ </HStack>+ <Text as="span" color="fg.subtle">+ {t('widgets.gallery.picker.dropHint')}+ </Text></DropZone>+ </GalleryPickerPopover>+ <HStack justify="end">+ <Button disabled={!canAdd} size="xs" variant="ghost" onClick={handleUploadZoneClick}>+ <Icon as={UploadIcon} boxSize="3" />+ {t('widgets.gallery.picker.upload')}+ </Button></HStack>{referenceImageCount > 0 ? (diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsxindex 15d4781b5c..2d5d5ec7ec 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx@@ -1,58 +1,16 @@-import type { DragEndEvent } from '@dnd-kit/core';+import type { GalleryItem } from '@features/gallery';+import type { GalleryMediaSlotValue } from '@features/gallery/picker';import type { UpscaleWidgetValues } from '@features/upscale/core/types';-import type { ChangeEvent } from 'react';-import { Box, HStack, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';-import { useDndMonitor } from '@dnd-kit/core';-import { galleryImages, galleryTransfers } from '@features/gallery';-import {- galleryImageUrls,- isGalleryImageDragData,- isSingleGalleryImageDragData,- useGalleryItemDroppable,-} from '@features/gallery/utility';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { Button } from '@platform/ui/Button';-import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';-import { DropZone } from '@platform/ui/DropZone';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { ImagePlusIcon, UploadIcon, XIcon } from 'lucide-react';-import { memo, useCallback, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';+import { GalleryMediaSlot } from '@features/gallery/picker';+import { memo, useCallback, useMemo } from 'react';import { areInputImagesEquivalent } from './upscaleComparators';-import { useUpscaleUiActions } from './UpscaleUiContext';--/**- * The Upscale widget's source image: gallery drop target, file upload, and the- * chosen image's row.- *- * Split from the widget body because it is the one section that owns async- * work and local state -- resolving a dropped gallery item, uploading a file,- * and the loading and error states both of those produce. Everything else in- * the widget is a controlled field over project state, and keeping this beside- * them made it easy to mistake its local `useState` for form state.- */const DROP_ID = 'upscale-input-image';-const UPLOAD_ACCEPT_TYPES = ['image/png', 'image/jpeg', 'image/webp'];-const UPLOAD_ACCEPT_ATTR = [...UPLOAD_ACCEPT_TYPES, '.png', '.jpg', '.jpeg', '.webp'].join(',');-const DROP_ZONE_FOCUS_PROPS = {- outlineColor: 'accent.focusRing',- outlineOffset: '2px',- outlineStyle: 'solid',- outlineWidth: '2px',-};-const DROP_ZONE_DISABLED_PROPS = { cursor: 'wait', opacity: 0.7 };-// `DropZone` types its props as `BoxProps`, which has no `disabled`; spreading a-// typed object keeps the cast in one place.-const DROP_ZONE_BUSY_PROPS = { disabled: true };-const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };+const ACCEPT = ['image'] as const;+/** The Upscale widget's source image: pick from the gallery, drop from it, or upload. */export const UpscaleImageField = memo(function UpscaleImageField({inputImage,@@ -61,185 +19,21 @@ export const UpscaleImageField = memo(inputImage: UpscaleWidgetValues['inputImage'];onChange: (image: UpscaleWidgetValues['inputImage']) => void;}) {- const { t } = useTranslation();- const { reportError, touchGalleryImages } = useUpscaleUiActions();- const fileInputRef = useRef<HTMLInputElement | null>(null);- const [isLoading, setIsLoading] = useState(false);- const [errorMessage, setErrorMessage] = useState<string | null>(null);- // Advertise single-image drags only (the drop handler below consumes- // exactly one), but stay armed for ANY image drag: a multi-image release- // here must remain a dead drop, not fall through to a target underneath.- const { acceptsActiveDrag, isOver, setNodeRef } = useGalleryItemDroppable(- isSingleGalleryImageDragData,- { data: { kind: DROP_ID }, disabled: isLoading, id: DROP_ID },- isGalleryImageDragData- );-- const setGalleryImage = useCallback(- async (imageName: string) => {- setErrorMessage(null);- setIsLoading(true);-- try {- const [image] = await galleryImages.resolveMany([imageName]);-- if (image) {- onChange({ height: image.height, image_name: image.imageName, width: image.width });- }- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- setErrorMessage(message);- reportError(message);- } finally {- setIsLoading(false);- }- },- [onChange, reportError]+ const value = useMemo<GalleryMediaSlotValue | null>(+ () =>+ inputImage+ ? { height: inputImage.height, kind: 'image', name: inputImage.image_name, width: inputImage.width }+ : null,+ [inputImage]);-- const handleDragEnd = useCallback(- (event: DragEndEvent) => {- const data = event.active.data.current;-- if (!isLoading && event.over?.id === DROP_ID && isGalleryImageDragData(data) && data.items.length === 1) {- const imageName = data.items[0]?.name;-- if (imageName) {- void setGalleryImage(imageName);- }- }- },- [isLoading, setGalleryImage]- );-- useDndMonitor({ onDragEnd: handleDragEnd });-- const uploadFile = useCallback(- async (file: File) => {- setErrorMessage(null);-- if (!UPLOAD_ACCEPT_TYPES.includes(file.type)) {- setErrorMessage(t('widgets.upscale.unsupportedFile'));- reportError(t('widgets.upscale.unsupportedFile'));- return;- }-- const owner = captureAccountScope();- setIsLoading(true);-- try {- const image = await galleryTransfers.upload(file, 'none', { signal: owner.signal });-- assertAccountScopeCurrent(owner);- onChange({ height: image.height, image_name: image.imageName, width: image.width });- touchGalleryImages();- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- const message = error instanceof Error ? error.message : String(error);- setErrorMessage(message);- reportError(message);- } finally {- setIsLoading(false);- }- },- [onChange, reportError, t, touchGalleryImages]- );-- const handleFileChange = useCallback(- (event: ChangeEvent<HTMLInputElement>) => {- const file = event.currentTarget.files?.[0];-- if (file) {- void uploadFile(file);- }- event.currentTarget.value = '';- },- [uploadFile]+ const handleChange = useCallback(+ (item: GalleryItem | null) =>+ onChange(item?.kind === 'image' ? { height: item.height, image_name: item.name, width: item.width } : null),+ [onChange]);- const handlePickFile = useCallback(() => fileInputRef.current?.click(), []);- const handleClear = useCallback(() => onChange(null), [onChange]);return (- <Stack gap="2">- <DropZone- ref={setNodeRef}- as="button"- aria-busy={isLoading}- aria-label={inputImage ? t('widgets.upscale.replaceImage') : t('widgets.upscale.uploadImage')}- isDisabled={isLoading}- isOver={isOver}- {...(isLoading ? DROP_ZONE_BUSY_PROPS : undefined)}- minH="24"- overflow="hidden"- position="relative"- _focusVisible={DROP_ZONE_FOCUS_PROPS}- _disabled={DROP_ZONE_DISABLED_PROPS}- _hover={isLoading ? undefined : DROP_ZONE_HOVER_PROPS}- onClick={handlePickFile}- >- {inputImage ? (- <HStack align="stretch" gap="3" h="24" p="2">- <Box bg="blackAlpha.300" boxSize="20" flexShrink="0" overflow="hidden" rounded="sm">- <Image- alt={t('widgets.upscale.inputImageAlt')}- boxSize="full"- objectFit="contain"- outline="1px solid"- outlineColor="border.image"- outlineOffset="-1px"- rounded="sm"- src={galleryImageUrls.thumbnail(inputImage.image_name)}- />- </Box>- <Stack align="start" flex="1" gap="1" justify="center" minW="0">- <MiddleTruncate color="fg" fontSize="xs" fontWeight="semibold" text={inputImage.image_name} />- <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums">- {inputImage.width} × {inputImage.height}- </Text>- <HStack color="fg.muted" gap="1">- {isLoading ? <Spinner size="xs" /> : <UploadIcon aria-hidden="true" size="12" />}- <Text fontSize="2xs">- {isLoading ? t('widgets.upscale.uploadingImage') : t('widgets.upscale.replaceOrDrop')}- </Text>- </HStack>- </Stack>- </HStack>- ) : (- <Stack align="center" color="fg.muted" gap="2" justify="center" minH="24" px="4">- {isLoading ? <Spinner size="sm" /> : <ImagePlusIcon aria-hidden="true" size="20" />}- <Text fontSize="xs" textAlign="center">- {isLoading ? t('widgets.upscale.uploadingImage') : t('widgets.upscale.uploadOrDrop')}- </Text>- </Stack>- )}- <DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={t('widgets.upscale.dropImage')} />- </DropZone>- <HStack justify="end">- {inputImage ? (- <Button disabled={isLoading} size="xs" variant="ghost" onClick={handleClear}>- <XIcon aria-hidden="true" size="12" />- {t('widgets.upscale.removeImage')}- </Button>- ) : null}- </HStack>- {errorMessage ? (- <Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">- {errorMessage}- </Text>- ) : null}- <Input- ref={fileInputRef}- accept={UPLOAD_ACCEPT_ATTR}- aria-hidden="true"- display="none"- tabIndex={-1}- type="file"- onChange={handleFileChange}- />- </Stack>+ <GalleryMediaSlot accept={ACCEPT} dropId={DROP_ID} uploadBoardId="none" value={value} onChange={handleChange} />);},(previous, next) =>diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsxindex 9a71e76ea1..0b649cf09d 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx@@ -16,14 +16,10 @@ export interface UpscaleUiAdapter {rawValues: Record<string, unknown>;reportError(message: string): void;showPromptSyntaxHighlighting: boolean;- touchGalleryImages(): void;}/** The adapter's callbacks, which are stable for the lifetime of a project. */-export type UpscaleUiActions = Pick<- UpscaleUiAdapter,- 'patchPromptDraft' | 'patchValues' | 'reportError' | 'touchGalleryImages'->;+export type UpscaleUiActions = Pick<UpscaleUiAdapter, 'patchPromptDraft' | 'patchValues' | 'reportError'>;const UpscaleUiContext = createContext<UpscaleUiAdapter | null>(null);/**@@ -35,10 +31,10 @@ const UpscaleUiContext = createContext<UpscaleUiAdapter | null>(null);const UpscaleUiActionsContext = createContext<UpscaleUiActions | null>(null);export const UpscaleUiProvider = ({ adapter, children }: { adapter: UpscaleUiAdapter; children: ReactNode }) => {- const { patchPromptDraft, patchValues, reportError, touchGalleryImages } = adapter;+ const { patchPromptDraft, patchValues, reportError } = adapter;const actions = useMemo<UpscaleUiActions>(- () => ({ patchPromptDraft, patchValues, reportError, touchGalleryImages }),- [patchPromptDraft, patchValues, reportError, touchGalleryImages]+ () => ({ patchPromptDraft, patchValues, reportError }),+ [patchPromptDraft, patchValues, reportError]);return (diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsxindex 3a7e4fea48..05fad5e90a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx@@ -1,52 +1,18 @@-import type { DragEndEvent } from '@dnd-kit/core';+import type { GalleryItem } from '@features/gallery';+import type { GalleryMediaSlotLabels, GalleryMediaSlotValue } from '@features/gallery/picker';import type { ImageWithDims } from '@features/generation/contracts';-import type { ChangeEvent } from 'react';-import { Box, HStack, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';-import { useDndMonitor } from '@dnd-kit/core';-import { galleryImages, galleryTransfers } from '@features/gallery';-import {- galleryImageUrls,- isGalleryImageDragData,- isSingleGalleryImageDragData,- useGalleryItemDroppable,-} from '@features/gallery/utility';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { Button } from '@platform/ui/Button';-import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';-import { DropZone } from '@platform/ui/DropZone';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { ImagePlusIcon, XIcon } from 'lucide-react';-import { memo, useCallback, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';+import { GalleryMediaSlot } from '@features/gallery/picker';+import { memo, useCallback, useMemo } from 'react';import { useVideoUiActions } from './VideoUiContext';-/**- * A conditioning keyframe (first or last frame): gallery drop target, file- * upload, and the chosen image's row. Same async-ownership pattern as the- * Upscale input image — this is the section that owns loading/error state.- */--const UPLOAD_ACCEPT_TYPES = ['image/png', 'image/jpeg', 'image/webp'];-const UPLOAD_ACCEPT_ATTR = [...UPLOAD_ACCEPT_TYPES, '.png', '.jpg', '.jpeg', '.webp'].join(',');-const DROP_ZONE_FOCUS_PROPS = {- outlineColor: 'accent.focusRing',- outlineOffset: '2px',- outlineStyle: 'solid',- outlineWidth: '2px',-};-const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };-const DROP_ZONE_BUSY_PROPS = { disabled: true };-const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };+const ACCEPT = ['image'] as const;const areFrameImagesEquivalent = (left: ImageWithDims | null, right: ImageWithDims | null): boolean =>(left === null && right === null) || left?.image_name === right?.image_name;+/** A conditioning keyframe (first or last frame): pick from the gallery, drop from it, or upload. */export const VideoFrameImageField = memo(function VideoFrameImageField({disabled = false,@@ -66,198 +32,29 @@ export const VideoFrameImageField = memo(image: ImageWithDims | null;onChange: (image: ImageWithDims | null) => void;}) {- const { t } = useTranslation();- const { getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();- const fileInputRef = useRef<HTMLInputElement | null>(null);- const [isLoading, setIsLoading] = useState(false);- const [errorMessage, setErrorMessage] = useState<string | null>(null);- const isInert = disabled || isLoading;- // Advertise single-image drags only (the drop handler below consumes- // exactly one), but stay armed for ANY image drag: a multi-image release- // here must remain a dead drop, not fall through to a target underneath.- const { acceptsActiveDrag, isOver, setNodeRef } = useGalleryItemDroppable(- isSingleGalleryImageDragData,- { data: { kind: dropId }, disabled: isInert, id: dropId },- isGalleryImageDragData- );-- const setGalleryImage = useCallback(- async (imageName: string) => {- setErrorMessage(null);- setIsLoading(true);-- try {- const [resolved] = await galleryImages.resolveMany([imageName]);-- if (resolved) {- onChange({ height: resolved.height, image_name: resolved.imageName, width: resolved.width });- }- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- setErrorMessage(message);- reportError(message);- } finally {- setIsLoading(false);- }- },- [onChange, reportError]+ const { getUploadBoardId } = useVideoUiActions();+ const value = useMemo<GalleryMediaSlotValue | null>(+ () => (image ? { height: image.height, kind: 'image', name: image.image_name, width: image.width } : null),+ [image]);-- const handleDragEnd = useCallback(- (event: DragEndEvent) => {- const data = event.active.data.current;-- if (!isInert && event.over?.id === dropId && isGalleryImageDragData(data) && data.items.length === 1) {- const imageName = data.items[0]?.name;-- if (imageName) {- void setGalleryImage(imageName);- }- }- },- [dropId, isInert, setGalleryImage]- );-- useDndMonitor({ onDragEnd: handleDragEnd });-- const uploadFile = useCallback(- async (file: File) => {- setErrorMessage(null);-- if (!UPLOAD_ACCEPT_TYPES.includes(file.type)) {- setErrorMessage(t('widgets.video.unsupportedImageFile'));- reportError(t('widgets.video.unsupportedImageFile'));- return;- }-- const owner = captureAccountScope();- setIsLoading(true);-- try {- const uploaded = await galleryTransfers.upload(file, getUploadBoardId(), { signal: owner.signal });-- assertAccountScopeCurrent(owner);- onChange({ height: uploaded.height, image_name: uploaded.imageName, width: uploaded.width });- touchGalleryImages();- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- const message = error instanceof Error ? error.message : String(error);- setErrorMessage(message);- reportError(message);- } finally {- setIsLoading(false);- }- },- [getUploadBoardId, onChange, reportError, t, touchGalleryImages]- );-- const handleFileChange = useCallback(- (event: ChangeEvent<HTMLInputElement>) => {- const file = event.currentTarget.files?.[0];-- if (file) {- void uploadFile(file);- }- event.currentTarget.value = '';- },- [uploadFile]+ const labels = useMemo<Partial<GalleryMediaSlotLabels>>(() => ({ drop: dropLabel }), [dropLabel]);+ const handleChange = useCallback(+ (item: GalleryItem | null) =>+ onChange(item?.kind === 'image' ? { height: item.height, image_name: item.name, width: item.width } : null),+ [onChange]);- const handlePickFile = useCallback(() => {- if (!isInert) {- fileInputRef.current?.click();- }- }, [isInert]);- const handleClear = useCallback(() => onChange(null), [onChange]);return (- <Stack gap="2">- <DropZone- ref={setNodeRef}- as="button"- aria-busy={isLoading}- aria-disabled={disabled}- aria-label={image ? t('widgets.video.replaceFrame') : t('widgets.video.uploadFrame')}- cursor={disabled ? 'not-allowed' : undefined}- isDisabled={isInert}- isOver={isOver}- {...(isLoading ? DROP_ZONE_BUSY_PROPS : undefined)}- minH="20"- overflow="hidden"- position="relative"- _focusVisible={DROP_ZONE_FOCUS_PROPS}- _disabled={DROP_ZONE_DISABLED_PROPS}- _hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}- opacity={disabled ? 0.6 : undefined}- onClick={handlePickFile}- >- {image ? (- <HStack align="stretch" gap="3" h="20" p="2">- <Box bg="blackAlpha.300" boxSize="16" flexShrink="0" overflow="hidden" rounded="sm">- <Image- alt=""- boxSize="full"- objectFit="contain"- outline="1px solid"- outlineColor="border.image"- outlineOffset="-1px"- rounded="sm"- src={galleryImageUrls.thumbnail(image.image_name)}- />- </Box>- <Stack align="start" flex="1" gap="1" justify="center" minW="0">- <MiddleTruncate color="fg" fontSize="xs" fontWeight="semibold" text={image.image_name} />- <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums">- {image.width} × {image.height}- </Text>- </Stack>- </HStack>- ) : (- <Stack align="center" color="fg.muted" gap="1.5" justify="center" minH="20" px="4">- {isLoading ? <Spinner size="sm" /> : <ImagePlusIcon aria-hidden="true" size="18" />}- <Text fontSize="2xs" textAlign="center">- {disabled && disabledReason- ? disabledReason- : isLoading- ? t('widgets.video.uploadingFrame')- : t('widgets.video.uploadOrDropFrame')}- </Text>- </Stack>- )}- <DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={dropLabel} />- </DropZone>- <HStack justify="space-between">- {disabled && disabledReason && image ? (- <Text color="fg.muted" fontSize="2xs">- {disabledReason}- </Text>- ) : (- <Box />- )}- {image ? (- <Button disabled={isLoading} size="xs" variant="ghost" onClick={handleClear}>- <XIcon aria-hidden="true" size="12" />- {t('widgets.video.removeFrame')}- </Button>- ) : null}- </HStack>- {errorMessage ? (- <Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">- {errorMessage}- </Text>- ) : null}- <Input- ref={fileInputRef}- accept={UPLOAD_ACCEPT_ATTR}- aria-hidden="true"- display="none"- tabIndex={-1}- type="file"- onChange={handleFileChange}- />- </Stack>+ <GalleryMediaSlot+ accept={ACCEPT}+ disabled={disabled}+ disabledReason={disabledReason}+ dropId={dropId}+ labels={labels}+ uploadBoardId={getUploadBoardId}+ value={value}+ onChange={handleChange}+ />);},(previous, next) =>diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsxindex 8d86b25a06..0cb7091a1a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx@@ -1,4 +1,6 @@import type { DragEndEvent } from '@dnd-kit/core';+import type { GalleryItem, GalleryVideoItem } from '@features/gallery';+import type { GalleryPickerSelection } from '@features/gallery/picker';import type {VideoReferenceConditioning,VideoReferenceImageDetail,@@ -6,9 +8,10 @@ import type {} from '@features/video/core/types';import type { ChangeEvent } from 'react';-import { Badge, Box, createListCollection, HStack, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';+import { Badge, Box, createListCollection, HStack, Icon, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';import { useDndContext, useDndMonitor, useDroppable } from '@dnd-kit/core';-import { galleryImages, galleryItems, galleryTransfers } from '@features/gallery';+import { galleryItems, galleryTransfers, toGalleryItemKey } from '@features/gallery';+import { GalleryPickerPopover } from '@features/gallery/picker';import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';import { createVideoSourceClip } from '@features/video/core/settings';import {@@ -23,7 +26,7 @@ import { Field } from '@platform/ui/Field';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Select } from '@platform/ui/Select';import { SliderNumberField } from '@platform/ui/SliderNumberField';-import { ArrowDownIcon, ArrowUpIcon, FilmIcon, ImagePlusIcon, XIcon } from 'lucide-react';+import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, FilmIcon, ImagePlusIcon, UploadIcon, XIcon } from 'lucide-react';import { memo, useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -47,6 +50,7 @@ const DROP_ZONE_FOCUS_PROPS = {};const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };const DROP_ZONE_BUSY_PROPS = { disabled: true };+const ACCEPT_MEDIA = ['image', 'video'] as const;const getSingleGalleryDragItem = (data: unknown): { kind: 'image' | 'video'; name: string } | null => {if (!isGalleryItemDragData(data) || data.items.length !== 1) {@@ -312,40 +316,48 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({const handlePickVideo = useCallback(() => videoInputRef.current?.click(), []);const addImageReference = useCallback(- async (imageName: string) => {+ (image: { height: number; name: string; width: number }) => {setErrorMessage(null);++ // Re-check the cap against the LIVE list: the render-time gate can be+ // stale by the time a drop resolves or an upload lands, and another+ // writer (a second drop, the Initial Video placing its anchor) can fill+ // the slots meanwhile. An over-cap write would survive to normalization,+ // whose overflow rule then has to delete SOMETHING the user placed.+ let declined = false;++ onChange((current) => {+ if (current.filter((entry) => entry.kind === 'image').length >= maxImages) {+ declined = true;++ return current;+ }++ return [+ ...current,+ {+ detail: 'max',+ image: { height: image.height, image_name: image.name, width: image.width },+ kind: 'image',+ },+ ];+ });+ if (declined) {+ setErrorMessage(t('widgets.video.referenceImageCapRace', { max: maxImages }));+ }+ },+ [maxImages, onChange, t]+ );++ const adoptImageByName = useCallback(+ async (imageName: string) => {setIsLoading(true);try {- const [resolved] = await galleryImages.resolveMany([imageName]);-- if (resolved) {- // Re-check the cap against the LIVE list: the render-time gate was- // evaluated before the await, and another writer (a second drop, or- // the Initial Video placing its anchor) can fill the slots meanwhile.- // An over-cap write would survive to normalization, whose overflow- // rule then has to delete SOMETHING the user placed.- let declined = false;-- onChange((current) => {- if (current.filter((entry) => entry.kind === 'image').length >= maxImages) {- declined = true;-- return current;- }-- return [- ...current,- {- detail: 'max',- image: { height: resolved.height, image_name: resolved.imageName, width: resolved.width },- kind: 'image',- },- ];- });- if (declined) {- setErrorMessage(t('widgets.video.referenceImageCapRace', { max: maxImages }));- }+ const item = await galleryItems.resolve({ kind: 'image', name: imageName });++ if (item?.kind === 'image') {+ addImageReference(item);}} catch (error) {const message = error instanceof Error ? error.message : String(error);@@ -355,7 +367,40 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({setIsLoading(false);}},- [maxImages, onChange, reportError, t]+ [addImageReference, reportError]+ );++ const addVideoItem = useCallback(+ (item: GalleryVideoItem) => {+ const clip = createVideoSourceClip(item);+ // Same live cap re-check as the image path -- the Initial Video's+ // anchor is the writer that most easily fills the slots mid-await.+ let declined = false;++ setErrorMessage(null);+ onChange((current) => {+ if (current.filter((entry) => entry.kind === 'video').length >= maxVideos) {+ declined = true;++ return current;+ }++ return [+ ...current,+ {+ // References are truncated to the generated duration, not joined: default to+ // the whole clip rather than the extend-mode 2-frame-tail trim.+ clip: { ...clip, endFrame: Math.max(0, clip.numFrames - 1), startFrame: 0 },+ conditioning: 'video_audio',+ kind: 'video',+ },+ ];+ });+ if (declined) {+ setErrorMessage(t('widgets.video.referenceVideoCapRace', { max: maxVideos }));+ }+ },+ [maxVideos, onChange, t]);const addVideoReference = useCallback(@@ -367,39 +412,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({const item = await galleryItems.resolve({ kind: 'video', name: videoName });if (item?.kind === 'video') {- const clip = createVideoSourceClip({- durationSeconds: item.durationSeconds,- fps: item.fps,- height: item.height,- name: item.name,- width: item.width,- });-- // Same live cap re-check as the image path -- the Initial Video's- // anchor is the writer that most easily fills the slots mid-await.- let declined = false;-- onChange((current) => {- if (current.filter((entry) => entry.kind === 'video').length >= maxVideos) {- declined = true;-- return current;- }-- return [- ...current,- {- // References are truncated to the generated duration, not joined: default to- // the whole clip rather than the extend-mode 2-frame-tail trim.- clip: { ...clip, endFrame: Math.max(0, clip.numFrames - 1), startFrame: 0 },- conditioning: 'video_audio',- kind: 'video',- },- ];- });- if (declined) {- setErrorMessage(t('widgets.video.referenceVideoCapRace', { max: maxVideos }));- }+ addVideoItem(item);}} catch (error) {const message = error instanceof Error ? error.message : String(error);@@ -409,7 +422,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({setIsLoading(false);}},- [maxVideos, onChange, reportError, t]+ [addVideoItem, reportError]);const handleDragEnd = useCallback(@@ -422,10 +435,10 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({if (item.kind === 'video' && canAddVideo) {void addVideoReference(item.name);} else if (item.kind === 'image' && canAddImage) {- void addImageReference(item.name);+ void adoptImageByName(item.name);}},- [addImageReference, addVideoReference, canAddImage, canAddVideo, isInert]+ [adoptImageByName, addVideoReference, canAddImage, canAddVideo, isInert]);useDndMonitor({ onDragEnd: handleDragEnd });@@ -446,7 +459,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({const uploaded = await galleryTransfers.upload(file, getUploadBoardId(), { signal: owner.signal });assertAccountScopeCurrent(owner);- await addImageReference(uploaded.imageName);+ addImageReference({ height: uploaded.height, name: uploaded.imageName, width: uploaded.width });}touchGalleryImages();} catch (error) {@@ -487,6 +500,31 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({[uploadFile]);+ const pickerSelection = useMemo<GalleryPickerSelection>(+ () => ({+ addedKeys: new Set(+ references.map((reference) =>+ reference.kind === 'video'+ ? toGalleryItemKey({ kind: 'video', name: reference.clip.video_name })+ : toGalleryItemKey({ kind: 'image', name: reference.image.image_name })+ )+ ),+ mode: 'multiple',+ remaining: { image: Math.max(0, maxImages - imageCount), video: Math.max(0, maxVideos - videoCount) },+ }),+ [imageCount, maxImages, maxVideos, references, videoCount]+ );+ const handlePick = useCallback(+ (item: GalleryItem) => {+ if (item.kind === 'video') {+ addVideoItem(item);+ } else {+ addImageReference(item);+ }+ },+ [addImageReference, addVideoItem]+ );+const updateReference = useCallback((index: number, reference: VideoReferenceItem) => {onChange((current) => current.map((entry, entryIndex) => (entryIndex === index ? reference : entry)));@@ -548,17 +586,30 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({_focusVisible={DROP_ZONE_FOCUS_PROPS}position="relative">- <HStack gap="2" justify="center" p="2">- {isLoading ? <Spinner size="xs" /> : null}- <Button disabled={isInert || !canAddImage} size="xs" variant="outline" onClick={handlePickImage}>- <ImagePlusIcon size={12} />- {t('widgets.video.addImageReference', { count: imageCount, max: maxImages })}- </Button>- <Button disabled={isInert || !canAddVideo} size="xs" variant="outline" onClick={handlePickVideo}>- <FilmIcon size={12} />- {t('widgets.video.addVideoReference', { count: videoCount, max: maxVideos })}- </Button>- </HStack>+ <Stack gap="1.5" p="2">+ <GalleryPickerPopover+ accept={ACCEPT_MEDIA}+ label={t('widgets.video.chooseReference')}+ selection={pickerSelection}+ onPick={handlePick}+ >+ <Button disabled={isInert || (!canAddImage && !canAddVideo)} size="xs" variant="outline" w="full">+ {isLoading ? <Spinner size="xs" /> : <Icon as={ImagePlusIcon} boxSize="3.5" />}+ {t('widgets.video.chooseReference')}+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />+ </Button>+ </GalleryPickerPopover>+ <HStack gap="1" justify="center">+ <Button disabled={isInert || !canAddImage} size="xs" variant="ghost" onClick={handlePickImage}>+ <UploadIcon size={12} />+ {t('widgets.video.uploadImageReference')}+ </Button>+ <Button disabled={isInert || !canAddVideo} size="xs" variant="ghost" onClick={handlePickVideo}>+ <UploadIcon size={12} />+ {t('widgets.video.uploadVideoReference')}+ </Button>+ </HStack>+ </Stack><DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={t('widgets.video.dropReference')} /></DropZone></Field>diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsxindex e51a807e58..865d7efc78 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx@@ -2,9 +2,10 @@ import type { DragEndEvent } from '@dnd-kit/core';import type { VideoSourceClip } from '@features/video/core/types';import type { ChangeEvent } from 'react';-import { Box, HStack, Input, Spinner, Stack, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Input, Spinner, Stack, Text } from '@chakra-ui/react';import { useDndContext, useDndMonitor, useDroppable } from '@dnd-kit/core';-import { galleryItems, galleryTransfers } from '@features/gallery';+import { galleryItems, galleryTransfers, type GalleryItem } from '@features/gallery';+import { GalleryPickerPopover } from '@features/gallery/picker';import { galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';import { createVideoSourceClip } from '@features/video/core/settings';import {@@ -18,7 +19,7 @@ import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';import { DropZone } from '@platform/ui/DropZone';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { SliderNumberField } from '@platform/ui/SliderNumberField';-import { FilmIcon, XIcon } from 'lucide-react';+import { ChevronDownIcon, FilmIcon, UploadIcon, XIcon } from 'lucide-react';import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -33,6 +34,7 @@ import { useVideoUiActions } from './VideoUiContext';*/const DROP_ID = 'video-source-clip';+const VIDEO_ONLY = ['video'] as const;const DROP_ZONE_FOCUS_PROPS = {outlineColor: 'accent.focusRing',outlineOffset: '2px',@@ -40,7 +42,6 @@ const DROP_ZONE_FOCUS_PROPS = {outlineWidth: '2px',};const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };-const DROP_ZONE_BUSY_PROPS = { disabled: true };const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };const getSingleVideoDragName = (data: unknown): string | null => {@@ -189,6 +190,15 @@ export const VideoSourceClipField = memo(}}, [isInert]);const handleClear = useCallback(() => onChange(null), [onChange]);+ const handlePick = useCallback(+ (item: GalleryItem) => {+ if (item.kind === 'video') {+ setErrorMessage(null);+ onChange(createVideoSourceClip(item));+ }+ },+ [onChange]+ );const maxFrameIndex = sourceVideo ? Math.max(0, sourceVideo.numFrames - 1) : 0;// The crossfade join needs a 2-frame tail from the trimmed source, so the@@ -222,47 +232,74 @@ export const VideoSourceClipField = memo(return (<Stack gap="2">- <DropZone- ref={setNodeRef}- as="button"- aria-busy={isLoading}- aria-disabled={disabled}- aria-label={sourceVideo ? t('widgets.video.replaceClip') : t('widgets.video.uploadClip')}- cursor={disabled ? 'not-allowed' : undefined}- isDisabled={isInert}- isOver={isOver}- {...(isLoading ? DROP_ZONE_BUSY_PROPS : undefined)}- minH="24"- overflow="hidden"- position="relative"- _focusVisible={DROP_ZONE_FOCUS_PROPS}- _disabled={DROP_ZONE_DISABLED_PROPS}- _hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}- opacity={disabled ? 0.6 : undefined}- onClick={handlePickFile}+ <GalleryPickerPopover+ accept={VIDEO_ONLY}+ label={t(sourceVideo ? 'widgets.gallery.picker.replaceVideo' : 'widgets.gallery.picker.chooseVideo')}+ onPick={handlePick}>- {sourceVideo && previewSrc ? (- <HStack gap="2" minW="0" p="2">- <FilmIcon aria-hidden="true" size={14} />- <MiddleTruncate color="fg" flex="1" fontSize="xs" fontWeight="semibold" text={sourceVideo.video_name} />- <Text color="fg.muted" flexShrink="0" fontSize="2xs" fontVariantNumeric="tabular-nums">- {sourceVideo.width} × {sourceVideo.height} · {sourceVideo.fps} fps- </Text>- </HStack>- ) : (- <Stack align="center" color="fg.muted" gap="1.5" justify="center" minH="24" px="4">- {isLoading ? <Spinner size="sm" /> : <FilmIcon aria-hidden="true" size="18" />}- <Text fontSize="2xs" textAlign="center">- {disabled && disabledReason- ? disabledReason- : isLoading- ? t('widgets.video.uploadingClip')- : t('widgets.video.uploadOrDropClip')}- </Text>- </Stack>- )}- <DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={t('widgets.video.dropInitialVideo')} />- </DropZone>+ <DropZone+ ref={setNodeRef}+ as="button"+ aria-busy={isLoading}+ aria-disabled={disabled}+ aria-label={t(sourceVideo ? 'widgets.gallery.picker.replaceVideo' : 'widgets.gallery.picker.chooseVideo')}+ cursor={disabled ? 'not-allowed' : undefined}+ disabled={isInert}+ isDisabled={isInert}+ isOver={isOver}+ minH="24"+ overflow="hidden"+ position="relative"+ textAlign="start"+ w="full"+ _focusVisible={DROP_ZONE_FOCUS_PROPS}+ _disabled={DROP_ZONE_DISABLED_PROPS}+ _hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}+ opacity={disabled ? 0.6 : undefined}+ >+ {sourceVideo && previewSrc ? (+ <HStack gap="2" minW="0" p="2">+ <FilmIcon aria-hidden="true" size={14} />+ <MiddleTruncate color="fg" flex="1" fontSize="xs" fontWeight="semibold" text={sourceVideo.video_name} />+ <Text color="fg.muted" flexShrink="0" fontSize="2xs" fontVariantNumeric="tabular-nums">+ {sourceVideo.width} × {sourceVideo.height} · {sourceVideo.fps} fps+ </Text>+ </HStack>+ ) : (+ <Stack align="center" color="fg.muted" gap="1.5" justify="center" minH="24" px="4">+ {isLoading ? (+ <Spinner size="sm" />+ ) : (+ <HStack color="fg" fontSize="xs" fontWeight="600" gap="1.5">+ <Icon as={FilmIcon} boxSize="4" />+ {t('widgets.gallery.picker.chooseVideo')}+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />+ </HStack>+ )}+ <Text color="fg.subtle" fontSize="2xs" textAlign="center">+ {disabled && disabledReason+ ? disabledReason+ : isLoading+ ? t('widgets.video.uploadingClip')+ : t('widgets.gallery.picker.dropHint')}+ </Text>+ </Stack>+ )}+ <DropTargetOverlay+ isActive={acceptsActiveDrag}+ isOver={isOver}+ label={t('widgets.video.dropInitialVideo')}+ />+ </DropZone>+ </GalleryPickerPopover>+ {disabled ? null : (+ <HStack justify="end">+ <Button disabled={isLoading} size="xs" variant="ghost" onClick={handlePickFile}>+ <Icon as={UploadIcon} boxSize="3" />+ {t('widgets.gallery.picker.upload')}+ </Button>+ </HStack>+ )}{sourceVideo && previewSrc ? (<Stack gap="2">{/* The empty-state slot shows the reason when no clip is set; withdiff --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 420c1f3890..5f358550fd 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@@ -4,7 +4,7 @@ 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, useCallback, useState } from 'react';+import { act, cloneElement, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';@@ -17,6 +17,26 @@ const uploadImageMock = vi.fn();const uploadVideoMock = vi.fn();const resolveItemMock = vi.fn();+const pickerState = vi.hoisted(() => ({ accept: null as readonly string[] | null }));++// The real picker needs the gallery data layer; the field's contract with it is+// the accepted kinds it passes and the item it gets back.+vi.mock('@features/gallery/picker', () => ({+ GalleryPickerPopover: ({+ accept,+ children,+ onPick,+ }: {+ accept: readonly string[];+ children: React.ReactElement<{ onClick?: () => void }>;+ onPick: (item: unknown) => void;+ }) => {+ pickerState.accept = accept;++ return cloneElement(children, { onClick: () => onPick(SELECTED_GALLERY_VIDEO) });+ },+}));+vi.mock('@features/gallery', () => ({formatGalleryVideoDuration: (seconds: number) => `${seconds}s`,galleryDestinations: { list: () => Promise.resolve([]) },@@ -245,22 +265,17 @@ describe('WorkflowFieldInput media inputs', () => {await renderField(VIDEO_TEMPLATE, undefined, vi.fn());expect(host.textContent).not.toContain('Connection only');- expect(host.textContent).toContain('Drop a video here');- expect(findButton('Use gallery selection').disabled).toBe(true);+ expect(findButton('widgets.gallery.picker.chooseVideo').disabled).toBe(false);+ expect(pickerState.accept).toEqual(['video']);expect(findButton('Upload').disabled).toBe(false);expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.accept).toBe('video/*,audio/*');});- it('adopts a selected gallery video and clears it', async () => {- galleryValues.selectedImage = SELECTED_GALLERY_VIDEO;+ it('adopts a video picked from the gallery, shows its details, and clears it', async () => {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());+ await act(() => findButton('widgets.gallery.picker.chooseVideo').click());expect(onChange).toHaveBeenCalledWith({ video_name: 'clip.mp4' });await renderField(VIDEO_TEMPLATE, { video_name: 'clip.mp4' }, onChange);@@ -274,14 +289,6 @@ describe('WorkflowFieldInput media inputs', () => {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',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 9256de89b6..9524444ddb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -15,6 +15,7 @@ import {Stack,Switch,Text,+ chakra,} from '@chakra-ui/react';import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent } from '@dnd-kit/core';import {@@ -25,7 +26,8 @@ import {type GalleryBoard,type GalleryItem,} from '@features/gallery';-import { getSelectedGalleryImageFromValues, getSelectedGalleryItemFromValues } from '@features/gallery/contracts';+import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';+import { GalleryPickerPopover } from '@features/gallery/picker';import { invalidateGallery } from '@features/gallery/queries';import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';import { DEFAULT_LORA_WEIGHT_CONFIG, SCHEDULER_OPTIONS } from '@features/generation/settings';@@ -66,6 +68,7 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useQuery, useQueryClient } from '@tanstack/react-query';import { FilmIcon, ImageIcon, Trash2Icon } from 'lucide-react';import { lazy, Suspense, useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';+import { useTranslation } from 'react-i18next';const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));const MODEL_SELECT_FALLBACK = (@@ -75,7 +78,6 @@ const MODEL_SELECT_FALLBACK = ();export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;-export const getWorkflowSelectedGalleryItem = getSelectedGalleryItemFromValues;/*** Direct-input controls for workflow fields, shared between the node editor@@ -451,18 +453,18 @@ const MEDIA_FIELD_CONFIG = {>;const HIDDEN_FILE_INPUT_STYLE = { display: 'none' } as const;+const IMAGE_ONLY = ['image'] as const;+const VIDEO_ONLY = ['video'] as const;+const MEDIA_INPUT_FOCUS_PROPS = { outline: '2px solid {colors.accent.focusRing}', outlineOffset: '2px' } as const;/*** Direct input for `ImageField` / `VideoField`: shows the current item with a- * thumbnail, adopts the gallery selection, accepts a single-item gallery drag+ * thumbnail, opens the gallery picker, 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 { t } = useTranslation();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');@@ -573,11 +575,10 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr[config.nameKey, config.noun, kind, onChange, project, queryClient, uploadBoardId]);- const onUseGallerySelectionClick = useCallback(() => {- if (gallerySelection) {- onChange({ [config.nameKey]: gallerySelection.name });- }- }, [config.nameKey, gallerySelection, onChange]);+ const onPick = useCallback(+ (item: GalleryItem) => onChange({ [config.nameKey]: item.name }),+ [config.nameKey, onChange]+ );const onClearClick = useCallback(() => onChange(undefined), [onChange]);// A stale value (media deleted since the workflow was saved) 404s the@@ -604,6 +605,8 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr: null;const FallbackIcon = kind === 'video' ? FilmIcon : ImageIcon;+ const pickerAccept = kind === 'video' ? VIDEO_ONLY : IMAGE_ONLY;+ const pickerLabel = t(kind === 'video' ? 'widgets.gallery.picker.chooseVideo' : 'widgets.gallery.picker.chooseImage');return (<Box position="relative" w="full" {...invalidAriaProps}>@@ -617,79 +620,84 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPrrounded="sm"w="full">- {mediaName ? (- <>- <Flex- alignItems="center"- borderWidth="1px"- h="full"- justifyContent="center"- overflow="hidden"- rounded="sm"- transition="border-color var(--wb-motion-duration-fast) ease"- w="full"- _hover={MEDIA_INPUT_HOVER_PROPS}- >- {failedThumbnail !== mediaName ? (- <Image- alt=""- maxH="full"- maxW="full"- objectFit="contain"- src={config.getThumbnailUrl(mediaName)}- title={mediaName}- onError={onThumbnailError}- />- ) : (- <Box title={mediaName}>- <Icon as={FallbackIcon} boxSize="10" color="fg.subtle" />- </Box>- )}- </Flex>- {badge !== null ? (- <Badge- bottom="1"- fontVariantNumeric="tabular-nums"- insetInlineEnd="1"- pointerEvents="none"- position="absolute"- size="xs"- variant="solid"- >- {badge}- </Badge>- ) : null}- </>- ) : (- <Flex- alignItems="center"- borderStyle="dashed"- borderWidth="1px"+ <GalleryPickerPopover accept={pickerAccept} label={pickerLabel} onPick={onPick}>+ <chakra.button+ aria-label={pickerLabel}+ className="nodrag"+ display="block"h="full"- justifyContent="center"- rounded="sm"- transition="border-color var(--wb-motion-duration-fast) ease"+ type="button"w="full"- _hover={MEDIA_INPUT_HOVER_PROPS}+ _focusVisible={MEDIA_INPUT_FOCUS_PROPS}+ >+ {mediaName ? (+ <Flex+ alignItems="center"+ borderWidth="1px"+ h="full"+ justifyContent="center"+ overflow="hidden"+ rounded="sm"+ transition="border-color var(--wb-motion-duration-fast) ease"+ w="full"+ _hover={MEDIA_INPUT_HOVER_PROPS}+ >+ {failedThumbnail !== mediaName ? (+ <Image+ alt=""+ maxH="full"+ maxW="full"+ objectFit="contain"+ src={config.getThumbnailUrl(mediaName)}+ title={mediaName}+ onError={onThumbnailError}+ />+ ) : (+ <Box title={mediaName}>+ <Icon as={FallbackIcon} boxSize="10" color="fg.subtle" />+ </Box>+ )}+ </Flex>+ ) : (+ <Flex+ alignItems="center"+ borderStyle="dashed"+ borderWidth="1px"+ direction="column"+ gap="1"+ h="full"+ justifyContent="center"+ rounded="sm"+ transition="border-color var(--wb-motion-duration-fast) ease"+ w="full"+ _hover={MEDIA_INPUT_HOVER_PROPS}+ >+ <Text as="span" color="fg" fontSize="xs" fontWeight="600">+ {pickerLabel}+ </Text>+ <Text as="span" color="fg.subtle" fontSize="2xs">+ {t('widgets.gallery.picker.dropHint')}+ </Text>+ </Flex>+ )}+ </chakra.button>+ </GalleryPickerPopover>+ {mediaName && badge !== null ? (+ <Badge+ bottom="1"+ fontVariantNumeric="tabular-nums"+ insetInlineEnd="1"+ pointerEvents="none"+ position="absolute"+ size="xs"+ variant="solid">- <Text color="fg.subtle" fontSize="xs">- {`Drop a ${config.noun} here`}- </Text>- </Flex>- )}+ {badge}+ </Badge>+ ) : null}<DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={`Drop ${config.noun}`} /></Box><HStack gap="1.5" mt="1" w="full">- <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><ButtonclassName="nodrag"disabled={isUploading}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsxindex 6ebcd9f589..eaaa016ec6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx@@ -10,7 +10,8 @@ import type { ChangeEvent, CSSProperties } from 'react';import { Box, createListCollection, HStack, IconButton, Input, Stack, Text } from '@chakra-ui/react';import { useDndMonitor } from '@dnd-kit/core';-import { galleryImages, galleryTransfers } from '@features/gallery';+import { galleryImageItemToGalleryImage, galleryImages, galleryTransfers, type GalleryItem } from '@features/gallery';+import { GalleryPickerPopover } from '@features/gallery/picker';import { invalidateGallery } from '@features/gallery/queries';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import { FluxReduxControls } from '@features/generation/components';@@ -20,11 +21,11 @@ import {captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';-import { DropZone, Field, Select, Slider } from '@platform/ui';+import { Button, DropZone, Field, Select, Slider } from '@platform/ui';import { useQueryClient } from '@tanstack/react-query';import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { ImageIcon, XIcon } from 'lucide-react';+import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -49,6 +50,7 @@ const IP_ADAPTER_METHODS: readonly RegionalGuidanceIPAdapterMethod[] = [const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;const COVER_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'cover', width: '100%' };+const IMAGE_ONLY = ['image'] as const;const formatWeight = (value: number): string => value.toFixed(2);@@ -265,6 +267,15 @@ const ReferenceImageEditor = ({[editing, referenceImage.id]);+ const handlePick = useCallback(+ (item: GalleryItem) => {+ if (item.kind === 'image') {+ editing.setReferenceImageAsset(referenceImage.id, galleryImageItemToGalleryImage(item));+ }+ },+ [editing, referenceImage.id]+ );+const handleModel = useCallback(({ value }: SelectValueChangeDetails) => {if (config.type !== 'ip_adapter' && config.type !== 'flux_redux') {@@ -350,24 +361,29 @@ const ReferenceImageEditor = ({position="relative"w="16">- <Box- as="button"- alignItems="center"- aria-label={t('widgets.layers.regionalGuidance.setReferenceImage')}- bg="bg.muted"- color="fg.muted"- display="flex"- h="full"- justifyContent="center"- w="full"- onClick={openUpload}+ <GalleryPickerPopover+ accept={IMAGE_ONLY}+ label={t(image ? 'widgets.gallery.picker.replaceImage' : 'widgets.gallery.picker.chooseImage')}+ onPick={handlePick}>- {image ? (- <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />- ) : (- <ImageIcon size="20" />- )}- </Box>+ <Box+ as="button"+ alignItems="center"+ aria-label={t(image ? 'widgets.gallery.picker.replaceImage' : 'widgets.gallery.picker.chooseImage')}+ bg="bg.muted"+ color="fg.muted"+ display="flex"+ h="full"+ justifyContent="center"+ w="full"+ >+ {image ? (+ <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />+ ) : (+ <ImageIcon size="20" />+ )}+ </Box>+ </GalleryPickerPopover>{image ? (<IconButtonaria-label={t('widgets.layers.regionalGuidance.clearReferenceImage')}@@ -383,9 +399,15 @@ const ReferenceImageEditor = ({</IconButton>) : null}</DropZone>- <Text color="fg.muted" flex="1" fontSize="2xs" minW="0">- {t('widgets.layers.regionalGuidance.referenceImageHelp')}- </Text>+ <Stack align="start" flex="1" gap="1" minW="0">+ <Text color="fg.muted" fontSize="2xs">+ {t('widgets.layers.regionalGuidance.referenceImageHelp')}+ </Text>+ <Button size="xs" variant="ghost" onClick={openUpload}>+ <UploadIcon size="12" />+ {t('widgets.gallery.picker.upload')}+ </Button>+ </Stack><Input ref={fileInputRef} accept="image/*" display="none" type="file" onChange={handleFileChange} /></HStack>