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.

fix(webv2): correct the template editor's image lifecycle

joshistoastbc2af2998bb0
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
index 66003a3977..c7b1220ef2 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
@@ -17,7 +17,7 @@ import { DropZone } from '@platform/ui/DropZone';
import { Field } from '@platform/ui/Field';
import { Tooltip } from '@platform/ui/Tooltip';
import { CheckIcon, ImageUpIcon, XIcon } from 'lucide-react';
-import { useCallback, useId, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
interface PromptTemplateEditorProps {
@@ -37,6 +37,13 @@ interface EditorDraft {
positivePrompt: string;
image: Blob | null;
imagePreviewUrl: string | null;
+ /**
+ * Whether the existing image has been dealt with — fetched, replaced, or
+ * removed. Stated outright because `image: null` is both "not loaded yet" and
+ * "the user took it off", and reading it as the former let a removal be undone
+ * by a fetch that landed afterwards.
+ */
+ isExistingImageSettled: boolean;
}
const MAX_NAME_LENGTH = 128;
@@ -56,12 +63,41 @@ export const PromptTemplateEditor = ({
const [draft, setDraft] = useState<EditorDraft>({
image: null,
imagePreviewUrl: template?.imageUrl ?? null,
+ isExistingImageSettled: !template?.imageUrl,
name: template?.name ?? '',
negativePrompt: template?.negativePrompt ?? prefill?.negativePrompt ?? '',
positivePrompt: template?.positivePrompt ?? prefill?.positivePrompt ?? '',
});
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const objectUrlRef = useRef<string | null>(null);
+
+ /**
+ * Swaps in a preview URL for a picked file, releasing the previous one.
+ *
+ * A blob URL pins the whole file for the document's lifetime, so re-picking
+ * ten images held on to all ten. The remote `template.imageUrl` shares this
+ * field but is not ours to revoke, which is why only what we created is
+ * tracked here.
+ */
+ const takeObjectUrl = useCallback((file: Blob | null): string | null => {
+ if (objectUrlRef.current) {
+ URL.revokeObjectURL(objectUrlRef.current);
+ }
+
+ objectUrlRef.current = file ? URL.createObjectURL(file) : null;
+
+ return objectUrlRef.current;
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (objectUrlRef.current) {
+ URL.revokeObjectURL(objectUrlRef.current);
+ }
+ },
+ []
+ );
// The backend replaces the whole record, so saving without resending the
// existing image would drop it. Load it up front and treat it as part of the
@@ -75,7 +111,9 @@ export const PromptTemplateEditor = ({
void fetchPromptTemplateImage(imageUrl).then((image) => {
if (image) {
- setDraft((current) => (current.image ? current : { ...current, image }));
+ setDraft((current) =>
+ current.isExistingImageSettled ? current : { ...current, image, isExistingImageSettled: true }
+ );
}
});
});
@@ -130,18 +168,26 @@ export const PromptTemplateEditor = ({
[]
);
- const handleImageChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
+ const handleImageChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
- if (file) {
- setDraft((current) => ({ ...current, image: file, imagePreviewUrl: URL.createObjectURL(file) }));
- }
+ if (file) {
+ const imagePreviewUrl = takeObjectUrl(file);
- // Reset so re-picking the same file still fires a change.
- event.currentTarget.value = '';
- }, []);
+ setDraft((current) => ({ ...current, image: file, imagePreviewUrl, isExistingImageSettled: true }));
+ }
+
+ // Reset so re-picking the same file still fires a change.
+ event.currentTarget.value = '';
+ },
+ [takeObjectUrl]
+ );
- const clearImage = useCallback(() => setDraft((current) => ({ ...current, image: null, imagePreviewUrl: null })), []);
+ const clearImage = useCallback(() => {
+ takeObjectUrl(null);
+ setDraft((current) => ({ ...current, image: null, imagePreviewUrl: null, isExistingImageSettled: true }));
+ }, [takeObjectUrl]);
const reportSaveError = useCallback(
(caught: unknown) =>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
index dec71459f5..4ca2a6fb73 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
@@ -2,6 +2,7 @@ import type { PromptTemplateRecord } from '@features/generation/data/promptTempl
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import { ChakraProvider } from '@chakra-ui/react';
+import { fetchPromptTemplateImage } from '@features/generation/data/promptTemplates';
import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
import { system } from '@theme/system';
@@ -23,8 +24,8 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>
}));
// The editor loads an existing preview image back so saving does not drop it.
-// No template under test has one, so the fetch never fires; stubbed anyway so a
-// regression shows up as a failed assertion rather than a network error.
+// Stubbed so a template with an image is driven from the test rather than the
+// network, and so a regression shows up as a failed assertion.
vi.mock('@features/generation/data/promptTemplates', async (importOriginal) => ({
...(await importOriginal<object>()),
fetchPromptTemplateImage: vi.fn().mockResolvedValue(null),
@@ -99,6 +100,15 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const templateWithImage: PromptTemplateRecord = {
+ id: 'user-1',
+ imageUrl: 'http://host/image.png',
+ isDefault: false,
+ name: 'Cinematic',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, cinematic',
+};
+
const userTemplate: PromptTemplateRecord = {
id: 'user-1',
imageUrl: null,
@@ -297,6 +307,46 @@ describe('the prompt template editor', () => {
});
});
+ // Regression: the existing image is fetched on mount so that saving does not
+ // drop it, and `image: null` was read as "still loading". Removing it before
+ // that landed therefore looked identical to not having loaded yet, and the
+ // arriving blob put the image the user had just taken off straight back.
+ it('does not resurrect an image removed while it was still loading', async () => {
+ const catalog = createCatalog();
+ let resolveImage: (image: Blob) => void = () => {};
+
+ vi.mocked(fetchPromptTemplateImage).mockReturnValueOnce(
+ new Promise<Blob | null>((resolve) => {
+ resolveImage = resolve;
+ })
+ );
+
+ await render(
+ <PromptTemplateEditor
+ catalog={catalog}
+ showSyntaxHighlighting
+ template={templateWithImage}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Remove image"]')!);
+ });
+
+ await act(async () => {
+ resolveImage(new Blob(['old'], { type: 'image/png' }));
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await userEvent.click(buttonWithText('Save'));
+ });
+
+ expect(catalog.update).toHaveBeenCalledWith('user-1', expect.objectContaining({ image: null }));
+ });
+
it('keeps Save out of reach until the template is named', async () => {
await render(
<PromptTemplateEditor
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx
index 51c35663e3..d9e3ea930b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx
@@ -124,6 +124,12 @@ export const PromptTemplatesButton = ({
<Popover.Body p="2.5">
{editorTarget ? (
<PromptTemplateEditor
+ // The editor seeds its draft on mount. Every other way in goes
+ // through the panel first, which unmounts it — but the gallery
+ // handover swaps the target in place, so without this a draft
+ // opened over an existing template kept that template's text
+ // and saved a duplicate of it.
+ key={editorTarget.record?.id ?? 'new'}
catalog={catalog}
prefill={editorTarget.prefill}
showSyntaxHighlighting={showSyntaxHighlighting}