Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): keep a queued reference-image reorder from being dropped
Lincoln Stein5c78b2d21770
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex cdbb313295..21ca6a5261 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -345,7 +345,8 @@ export const cloneReferenceImages = (* conditioning order — the graph builders chain `reference_images` in it — so* this is the whole of what reordering means. Returns the same array identity* when the move is a no-op (unknown id, or already at the end it is moving- * toward) so callers can skip the write.+ * toward), so an updater built on it leaves the settings untouched and the+ * committed patch comes out empty.*/export const moveReferenceImage = (referenceImages: readonly GenerateReferenceImage[],diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.tsnew file mode 100644index 0000000000..f145f113ca--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.ts@@ -0,0 +1,71 @@+import type { GenerateReferenceImage, GenerateSettings } from '@features/generation/core/types';++import { moveReferenceImage } from '@features/generation/core/settings';+import { describe, expect, it } from 'vitest';++import { applyGenerateSettingsUpdate, mergeGenerateSettingsUpdate } from './generateDebounce';++/**+ * A pending update is an updater FUNCTION, and the form runs it twice: once+ * against the draft the user sees (`commit`), then again against the freshly+ * committed settings when the debounce flushes. That is what lets a pending+ * edit survive a concurrent external write — but it also means an updater has+ * to be pure. An updater that mints an id inside its own body produces a+ * DIFFERENT id on each run, so the entry the user is looking at is not the+ * entry that gets committed, and any later edit keyed to the rendered id is+ * silently dropped at flush.+ */+const buildSettings = (referenceImages: GenerateReferenceImage[] = []): GenerateSettings =>+ ({ referenceImages }) as unknown as GenerateSettings;++const entry = (id: string): GenerateReferenceImage => ({+ config: { image: null, type: 'external_reference_image' },+ id,+ isEnabled: true,+});++const idsOf = (settings: GenerateSettings) => settings.referenceImages.map(({ id }) => id);++describe('pending generate settings updates', () => {+ it('applies a pending updater twice, so an id minted inside one diverges between draft and commit', () => {+ let minted = 0;+ const appendWithIdInsideUpdater = (settings: GenerateSettings): GenerateSettings => ({+ ...settings,+ referenceImages: [...settings.referenceImages, entry(`minted-${String((minted += 1))}`)],+ });++ const pending = mergeGenerateSettingsUpdate(null, appendWithIdInsideUpdater);+ const draft = applyGenerateSettingsUpdate(buildSettings([entry('a')]), pending);+ const committed = applyGenerateSettingsUpdate(buildSettings([entry('a')]), pending);++ expect(idsOf(draft)).toEqual(['a', 'minted-1']);+ expect(idsOf(committed)).toEqual(['a', 'minted-2']);++ // The hazard this guards: a reorder queued behind that append is keyed to+ // the id the CARD renders under, which no longer exists at flush time.+ const chained = mergeGenerateSettingsUpdate(pending, (settings) => ({+ ...settings,+ referenceImages: [...moveReferenceImage(settings.referenceImages, 'minted-1', -1)],+ }));++ expect(idsOf(applyGenerateSettingsUpdate(buildSettings([entry('a')]), chained))).toEqual(['a', 'minted-3']);+ });++ it('keeps the reorder when the appended ids are minted outside the updater', () => {+ const ids = ['hoisted'];+ const appendWithHoistedId = (settings: GenerateSettings): GenerateSettings => ({+ ...settings,+ referenceImages: [...settings.referenceImages, entry(ids[0] ?? '')],+ });++ const chained = mergeGenerateSettingsUpdate(mergeGenerateSettingsUpdate(null, appendWithHoistedId), (settings) => ({+ ...settings,+ referenceImages: [...moveReferenceImage(settings.referenceImages, 'hoisted', -1)],+ }));++ // Same chain, applied to draft and to the committed settings: both agree,+ // and the queued reorder actually lands.+ expect(idsOf(applyGenerateSettingsUpdate(buildSettings([entry('a')]), chained))).toEqual(['hoisted', 'a']);+ expect(idsOf(applyGenerateSettingsUpdate(buildSettings([entry('a')]), chained))).toEqual(['hoisted', 'a']);+ });+});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 0aa530a45d..76d2e07e8e 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@@ -75,6 +75,14 @@ export const GenerateReferenceImagesContent = ({const appendReferenceImages = useCallback((images: GenerateReferenceImageAsset[]) => {+ // Ids are minted HERE rather than inside the updater. A pending updater+ // is applied twice — once against the draft the user sees, then again+ // against the freshly committed settings when the debounce flushes — so+ // an id created inside it differs between the two. Any later edit keyed+ // to the id the card renders under (a reorder, a patch) would then find+ // nothing at flush and be silently dropped.+ const ids = images.map(() => createReferenceImageId());+onCommit((currentSettings) => {const remaining = getMaxReferenceImages(selectedModel) - currentSettings.referenceImages.length;@@ -86,9 +94,9 @@ export const GenerateReferenceImagesContent = ({...currentSettings,referenceImages: [...currentSettings.referenceImages,- ...images.slice(0, remaining).map((image) => ({+ ...images.slice(0, remaining).map((image, index) => ({config: getDefaultReferenceImageConfig(selectedModel, models, image),- id: createReferenceImageId(),+ id: ids[index] ?? createReferenceImageId(),isEnabled: true,})),],@@ -327,8 +335,7 @@ export const GenerateReferenceImagesContent = ({{referenceImages.map((referenceImage, index) => (<ReferenceImageCardkey={referenceImage.id}- canMoveDown={index < referenceImageCount - 1}- canMoveUp={index > 0}+ count={referenceImageCount}index={index}referenceImage={referenceImage}selectedModel={selectedModel}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxindex ffc3c5e58a..33dc5d7d30 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx@@ -13,7 +13,7 @@ import { getReferenceImageUrls } from '@features/generation/data/referenceImageUimport { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';import { IconButton, ToggleDot, Tooltip } from '@platform/ui';import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, CropIcon, ImageIcon, RulerIcon, Trash2Icon } from 'lucide-react';-import { memo, useCallback, useState } from 'react';+import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { formatWeight, getModeLabelKey } from './referenceImageConfig';@@ -44,8 +44,7 @@ const OVERLAY_GRADIENT_STYLE: CSSProperties = {};interface ReferenceImageCardProps {- canMoveDown: boolean;- canMoveUp: boolean;+ count: number;index: number;referenceImage: GenerateReferenceImage;selectedModel: GenerateModelConfig | undefined;@@ -56,8 +55,7 @@ interface ReferenceImageCardProps {}const ReferenceImageCardBase = ({- canMoveDown,- canMoveUp,+ count,index,onMove,onPatch,@@ -68,6 +66,10 @@ const ReferenceImageCardBase = ({}: ReferenceImageCardProps) => {const { t } = useTranslation();const [isCollapsed, setIsCollapsed] = useState(false);+ const moveUpRef = useRef<HTMLButtonElement>(null);+ const moveDownRef = useRef<HTMLButtonElement>(null);+ const canMoveUp = index > 0;+ const canMoveDown = index < count - 1;const config = referenceImage.config;const isEnabled = referenceImage.isEnabled;const selectedBase = selectedModel?.base;@@ -88,9 +90,26 @@ const ReferenceImageCardBase = ({const handleRemove = useCallback(() => onRemove(referenceImage.id), [onRemove, referenceImage.id]);- const handleMoveUp = useCallback(() => onMove(referenceImage.id, -1), [onMove, referenceImage.id]);+ // A move that lands on either end disables the very button that was just+ // activated, and a disabled element cannot hold focus — a keyboard user+ // would be dropped to <body> on the last step of walking a card to the top.+ // The card's DOM nodes survive the reorder (the list is keyed by id), so+ // handing focus to the arrow that stays live keeps their place in the stack.+ const handleMoveUp = useCallback(() => {+ onMove(referenceImage.id, -1);- const handleMoveDown = useCallback(() => onMove(referenceImage.id, 1), [onMove, referenceImage.id]);+ if (index - 1 === 0) {+ moveDownRef.current?.focus();+ }+ }, [index, onMove, referenceImage.id]);++ const handleMoveDown = useCallback(() => {+ onMove(referenceImage.id, 1);++ if (index + 1 === count - 1) {+ moveUpRef.current?.focus();+ }+ }, [count, index, onMove, referenceImage.id]);const handleCrop = useCallback((image: GenerateReferenceImageAsset) => changeConfig({ ...config, image }),@@ -143,6 +162,7 @@ const ReferenceImageCardBase = ({place — the same arrow pair the video panel's references use. */}<Tooltip content={t('widgets.generate.moveReferenceImageUp')}><IconButton+ ref={moveUpRef}aria-label={t('widgets.generate.moveReferenceImageUp')}color="fg.muted"disabled={!canMoveUp}@@ -155,6 +175,7 @@ const ReferenceImageCardBase = ({</Tooltip><Tooltip content={t('widgets.generate.moveReferenceImageDown')}><IconButton+ ref={moveDownRef}aria-label={t('widgets.generate.moveReferenceImageDown')}color="fg.muted"disabled={!canMoveDown}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsxindex 6793bec8a3..0f3a311fae 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx@@ -71,8 +71,7 @@ const Stack = ({ ids }: { ids: string[] }) => {{referenceImages.map((referenceImage, index) => (<ReferenceImageCardkey={referenceImage.id}- canMoveDown={index < referenceImages.length - 1}- canMoveUp={index > 0}+ count={referenceImages.length}index={index}referenceImage={referenceImage}selectedModel={undefined}@@ -143,6 +142,31 @@ describe('reference image reorder arrows', () => {expect(renderedOrder()).toEqual(['second.png', 'third.png', 'first.png']);});+ it('hands focus to the arrow that stays live when a move lands on an end', async () => {+ await renderStack(['first', 'second', 'third']);++ // Walking the middle card to the top disables the button being activated,+ // so without the handoff a keyboard user is dropped to <body>.+ const up = buttons('Move reference image up')[1];++ await act(() => up?.focus());+ await act(() => up?.click());++ expect(renderedOrder()).toEqual(['second.png', 'first.png', 'third.png']);+ expect(document.activeElement).toBe(buttons('Move reference image down')[0]);+ expect((document.activeElement as HTMLButtonElement).disabled).toBe(false);++ // Same at the far end: the down arrow of the card that lands last.+ const down = buttons('Move reference image down')[1];++ await act(() => down?.focus());+ await act(() => down?.click());++ expect(renderedOrder()).toEqual(['second.png', 'third.png', 'first.png']);+ expect(document.activeElement).toBe(buttons('Move reference image up')[2]);+ expect((document.activeElement as HTMLButtonElement).disabled).toBe(false);+ });+it('leaves a lone reference image with both arrows disabled', async () => {await renderStack(['only']);