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: make prompt template image updates lossless

joshistoast6c14606f57ed
diff --git a/invokeai/app/api/routers/style_presets.py b/invokeai/app/api/routers/style_presets.py
index 91acf8e7a6..7fee46e643 100644
--- a/invokeai/app/api/routers/style_presets.py
+++ b/invokeai/app/api/routers/style_presets.py
@@ -99,6 +99,9 @@ async def get_style_preset(
async def update_style_preset(
current_user: CurrentUserOrDefault,
image: Optional[UploadFile] = File(description="The image file to upload", default=None),
+ preserve_image: bool = Form(
+ description="Preserve the existing image when no replacement image is supplied", default=False
+ ),
style_preset_id: str = Path(description="The id of the style preset to update"),
data: str = Form(description="The data of the style preset to update"),
) -> StylePresetRecordWithImage:
@@ -121,6 +124,9 @@ async def update_style_preset(
record = _load_record_or_404(style_preset_id)
_assert_preset_write(record, current_user)
+ if image is not None and preserve_image:
+ raise HTTPException(status_code=400, detail="Cannot preserve and replace an image in the same request")
+
if image is not None:
if not image.content_type or not image.content_type.startswith("image"):
raise HTTPException(status_code=415, detail="Not an image")
@@ -137,7 +143,7 @@ async def update_style_preset(
ApiDependencies.invoker.services.style_preset_image_files.save(style_preset_id, pil_image)
except ValueError as e:
raise HTTPException(status_code=409, detail=str(e))
- else:
+ elif not preserve_image:
try:
ApiDependencies.invoker.services.style_preset_image_files.delete(style_preset_id)
except StylePresetImageFileNotFoundException:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index f85f80e4c2..663020400f 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -14097,6 +14097,12 @@
"title": "Image",
"description": "The image file to upload"
},
+ "preserve_image": {
+ "type": "boolean",
+ "title": "Preserve Image",
+ "description": "Preserve the existing image when no replacement image is supplied",
+ "default": false
+ },
"data": {
"type": "string",
"title": "Data",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index e11de96618..1822ff3960 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -4647,6 +4647,12 @@ export type components = {
* @description The image file to upload
*/
image?: Blob | null;
+ /**
+ * Preserve Image
+ * @description Preserve the existing image when no replacement image is supplied
+ * @default false
+ */
+ preserve_image?: boolean;
/**
* Data
* @description The data of the style preset to update
diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.test.ts b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.test.ts
new file mode 100644
index 0000000000..d828063ebc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.test.ts
@@ -0,0 +1,101 @@
+import { QueryClient } from '@tanstack/react-query';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const transport = vi.hoisted(() => ({
+ apiFetch: vi.fn(),
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', () => ({
+ absolutizeApiUrl: (path: string) => path,
+ apiFetch: transport.apiFetch,
+ apiFetchJson: transport.apiFetchJson,
+}));
+
+vi.mock('@platform/state/accountLifecycle', () => ({
+ assertAccountScopeCurrent: vi.fn(),
+ captureAccountScope: () => ({ signal: new AbortController().signal }),
+}));
+
+import { fetchPromptTemplateImage, updatePromptTemplate, type PromptTemplateUpdateDraft } from './promptTemplates';
+
+const dto = {
+ id: 'template-1',
+ image: '/api/v1/style_presets/i/template-1/image',
+ is_public: false,
+ name: 'Cinematic',
+ preset_data: { negative_prompt: '', positive_prompt: '{prompt}, cinematic' },
+ type: 'user' as const,
+ user_id: 'user-1',
+};
+
+const getFormData = (): FormData => {
+ const init = transport.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined;
+
+ expect(init?.method).toBe('PATCH');
+ expect(init?.body).toBeInstanceOf(FormData);
+ return init?.body as FormData;
+};
+
+const update = async (image: PromptTemplateUpdateDraft['image']): Promise<FormData> => {
+ transport.apiFetchJson.mockResolvedValue(dto);
+
+ await updatePromptTemplate('template/1', {
+ image,
+ name: 'Cinematic',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, cinematic',
+ });
+
+ expect(transport.apiFetchJson.mock.calls[0]?.[0]).toBe('/api/v1/style_presets/i/template%2F1');
+ return getFormData();
+};
+
+beforeEach(() => {
+ transport.apiFetch.mockReset();
+ transport.apiFetchJson.mockReset();
+});
+
+describe('prompt template image updates', () => {
+ it('sends preserve_image without re-uploading an unchanged image', async () => {
+ const body = await update({ kind: 'preserve' });
+
+ expect(body.get('preserve_image')).toBe('true');
+ expect(body.get('image')).toBeNull();
+ });
+
+ it('omits both image fields to explicitly remove an image', async () => {
+ const body = await update({ kind: 'remove' });
+
+ expect(body.get('preserve_image')).toBeNull();
+ expect(body.get('image')).toBeNull();
+ });
+
+ it('uploads the replacement image without preserve_image', async () => {
+ const replacement = new Blob(['replacement'], { type: 'image/png' });
+ const body = await update({ blob: replacement, kind: 'replace' });
+
+ expect(body.get('preserve_image')).toBeNull();
+ const uploaded = body.get('image');
+ expect(uploaded).toBeInstanceOf(Blob);
+ expect((uploaded as Blob).type).toBe('image/png');
+ await expect((uploaded as Blob).text()).resolves.toBe('replacement');
+ });
+});
+
+it('fetches template images through the authenticated relative-path transport', async () => {
+ const image = new Blob(['image'], { type: 'image/png' });
+ transport.apiFetch.mockResolvedValue(new Response(image));
+ const queryClient = new QueryClient();
+
+ await expect(
+ queryClient.fetchQuery({
+ queryFn: ({ signal }) => fetchPromptTemplateImage('folder/template', signal),
+ queryKey: ['template-image'],
+ })
+ ).resolves.toEqual(image);
+
+ expect(transport.apiFetch).toHaveBeenCalledWith('/api/v1/style_presets/i/folder%2Ftemplate/image', {
+ signal: expect.any(AbortSignal),
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts
index 437aa99cf9..83315cdbac 100644
--- a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts
+++ b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts
@@ -15,7 +15,7 @@ import type { PromptTemplateSnapshot } from '@features/generation/core/promptTem
import type { QueryClient } from '@tanstack/react-query';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
-import { absolutizeApiUrl, apiFetch, apiFetchJson } from '@platform/transport/http';
+import { apiFetch, apiFetchJson } from '@platform/transport/http';
import { queryOptions } from '@tanstack/react-query';
const PROMPT_TEMPLATES_BASE = '/api/v1/style_presets';
@@ -34,20 +34,20 @@ interface PromptTemplateDTO {
export interface PromptTemplateRecord extends PromptTemplateSnapshot {
/** `default` templates ship with the backend and are read-only here. */
isDefault: boolean;
- /** Absolute URL of the preview image, or null when the template has none. */
- imageUrl: string | null;
+ /** Whether the authenticated image resource should be requested. */
+ hasImage: boolean;
+ isPublic: boolean;
+ userId: string;
}
/**
* The four fields a record shares with a snapshot, and no more.
*
* A record is assignable to a snapshot, so applying one type-checks and keeps
- * `isDefault` and `imageUrl` along for the ride. Both then land in persisted
- * project state and in every queue item's widget snapshot — an absolute,
- * host-specific image URL among them, stale the moment the server moves. It
- * also puts five keys on an object `isCanonicalPromptTemplateSnapshot` requires
- * to have exactly four, so the identity short-circuits built around it in
- * `normalizeGenerateSettings` and `isGenerateSettings` never fired.
+ * catalog-only fields such as `isDefault` and `hasImage` along for the ride.
+ * They then land in persisted project state and every queue item's widget
+ * snapshot. Extra keys also make `isCanonicalPromptTemplateSnapshot` reject the
+ * object, so the identity short-circuits in settings normalization never fire.
*/
export const toPromptTemplateSnapshot = ({
id,
@@ -56,30 +56,37 @@ export const toPromptTemplateSnapshot = ({
positivePrompt,
}: PromptTemplateSnapshot): PromptTemplateSnapshot => ({ id, name, negativePrompt, positivePrompt });
-export interface PromptTemplateDraft {
+interface PromptTemplateDraftFields {
name: string;
negativePrompt: string;
positivePrompt: string;
- /**
- * The image the template should end up with, always stated outright. The
- * backend replaces the whole record, so an absent image part *deletes* the
- * stored one — there is no "leave it as it was". The editor therefore loads
- * the current image up front with `fetchPromptTemplateImage`.
- */
+}
+
+export interface PromptTemplateCreateDraft extends PromptTemplateDraftFields {
image: Blob | null;
}
+export type PromptTemplateImageUpdate = { kind: 'preserve' } | { kind: 'remove' } | { blob: Blob; kind: 'replace' };
+
+export interface PromptTemplateUpdateDraft extends PromptTemplateDraftFields {
+ image: PromptTemplateImageUpdate;
+}
+
export const promptTemplateKeys = {
all: ['generation', 'promptTemplates'] as const,
+ image: (id: string) => [...promptTemplateKeys.all, 'image', id] as const,
+ list: () => [...promptTemplateKeys.all, 'list'] as const,
};
const mapPromptTemplate = (dto: PromptTemplateDTO): PromptTemplateRecord => ({
+ hasImage: dto.image !== null,
id: dto.id,
- imageUrl: dto.image ? absolutizeApiUrl(dto.image) : null,
isDefault: dto.type === 'default',
+ isPublic: dto.is_public,
name: dto.name,
negativePrompt: dto.preset_data.negative_prompt,
positivePrompt: dto.preset_data.positive_prompt,
+ userId: dto.user_id,
});
export const promptTemplatesQueryOptions = () =>
@@ -96,7 +103,7 @@ export const promptTemplatesQueryOptions = () =>
assertAccountScopeCurrent(owner);
return templates.map(mapPromptTemplate);
},
- queryKey: promptTemplateKeys.all,
+ queryKey: promptTemplateKeys.list(),
staleTime: 30_000,
});
})();
@@ -106,7 +113,7 @@ export const promptTemplatesQueryOptions = () =>
* models admin-owned `default` templates and an `is_public` share flag; neither
* is authored from here, so both are pinned rather than exposed.
*/
-const toFormData = (draft: PromptTemplateDraft): FormData => {
+const toFormData = (draft: PromptTemplateDraftFields): FormData => {
const body = new FormData();
body.append(
@@ -120,41 +127,62 @@ const toFormData = (draft: PromptTemplateDraft): FormData => {
})
);
+ return body;
+};
+
+export const createPromptTemplate = async (draft: PromptTemplateCreateDraft): Promise<PromptTemplateRecord> => {
+ const body = toFormData(draft);
+
if (draft.image) {
body.append('image', draft.image);
}
- return body;
+ return mapPromptTemplate(
+ await apiFetchJson<PromptTemplateDTO>(`${PROMPT_TEMPLATES_BASE}/`, { body, method: 'POST' })
+ );
};
-export const createPromptTemplate = async (draft: PromptTemplateDraft): Promise<PromptTemplateRecord> =>
- mapPromptTemplate(
- await apiFetchJson<PromptTemplateDTO>(`${PROMPT_TEMPLATES_BASE}/`, { body: toFormData(draft), method: 'POST' })
- );
+export const updatePromptTemplate = async (
+ id: string,
+ draft: PromptTemplateUpdateDraft
+): Promise<PromptTemplateRecord> => {
+ const body = toFormData(draft);
-export const updatePromptTemplate = async (id: string, draft: PromptTemplateDraft): Promise<PromptTemplateRecord> =>
- mapPromptTemplate(
+ if (draft.image.kind === 'preserve') {
+ body.append('preserve_image', 'true');
+ } else if (draft.image.kind === 'replace') {
+ body.append('image', draft.image.blob);
+ }
+
+ return mapPromptTemplate(
await apiFetchJson<PromptTemplateDTO>(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}`, {
- body: toFormData(draft),
+ body,
method: 'PATCH',
})
);
+};
-/**
- * Reads a template's existing preview image back as a blob so an edit that does
- * not touch the image can resend it. Returns null if it cannot be read — losing
- * the image is a smaller failure than blocking the edit.
- */
-export const fetchPromptTemplateImage = async (imageUrl: string): Promise<Blob | null> => {
- try {
- const response = await apiFetch(imageUrl);
+export const fetchPromptTemplateImage = async (id: string, signal?: AbortSignal): Promise<Blob> => {
+ const response = await apiFetch(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}/image`, { signal });
- return await response.blob();
- } catch {
- return null;
- }
+ return await response.blob();
};
+export const promptTemplateImageQueryOptions = (id: string) =>
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: ({ signal }): Promise<Blob> =>
+ fetchPromptTemplateImage(id, AbortSignal.any([signal, owner.signal])).then((image) => {
+ assertAccountScopeCurrent(owner);
+ return image;
+ }),
+ queryKey: promptTemplateKeys.image(id),
+ staleTime: Number.POSITIVE_INFINITY,
+ });
+ })();
+
export const deletePromptTemplate = async (id: string): Promise<void> => {
await apiFetch(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}`, { method: 'DELETE' });
};
@@ -178,6 +206,14 @@ export const exportPromptTemplates = async (): Promise<Blob> => {
return await response.blob();
};
-export const invalidatePromptTemplates = async (queryClient: QueryClient): Promise<void> => {
- await queryClient.invalidateQueries({ queryKey: promptTemplateKeys.all });
+export const invalidatePromptTemplates = async (queryClient: QueryClient, id?: string): Promise<void> => {
+ const invalidations: Promise<void>[] = [
+ queryClient.invalidateQueries({ queryKey: promptTemplateKeys.list(), exact: true }),
+ ];
+
+ if (id) {
+ invalidations.push(queryClient.invalidateQueries({ queryKey: promptTemplateKeys.image(id), exact: true }));
+ }
+
+ await Promise.all(invalidations);
};
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 63774059e5..68372f3515 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
@@ -1,13 +1,19 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
-import type { PromptTemplateDraft, PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type {
+ PromptTemplateCreateDraft,
+ PromptTemplateImageUpdate,
+ PromptTemplateRecord,
+ PromptTemplateUpdateDraft,
+} from '@features/generation/data/promptTemplates';
import type { PendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import type { ChangeEvent } from 'react';
-import { HStack, Image, Input, Stack, Text } from '@chakra-ui/react';
+import { HStack, Input, Stack, Text } from '@chakra-ui/react';
import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
+import { PromptTemplateImage } from '@features/generation/ui/promptFields/PromptTemplateImage';
import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';
import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
@@ -16,7 +22,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, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
interface PromptTemplateEditorProps {
@@ -34,18 +40,13 @@ interface EditorDraft {
name: string;
negativePrompt: string;
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;
+ image: PromptTemplateImageUpdate;
+ /** Undefined keeps the stored image, a URL previews a replacement, null removes it. */
+ imagePreviewUrl?: string | null;
}
const MAX_NAME_LENGTH = 128;
+const NEW_TEMPLATE_IMAGE = { hasImage: false, id: 'new' } as const;
export const PromptTemplateEditor = ({
catalog,
@@ -60,9 +61,7 @@ export const PromptTemplateEditor = ({
const nameFieldId = useId();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [draft, setDraft] = useState<EditorDraft>({
- image: null,
- imagePreviewUrl: template?.imageUrl ?? null,
- isExistingImageSettled: !template?.imageUrl,
+ image: { kind: 'preserve' },
name: template?.name ?? '',
negativePrompt: template?.negativePrompt ?? prefill?.negativePrompt ?? '',
positivePrompt: template?.positivePrompt ?? prefill?.positivePrompt ?? '',
@@ -75,9 +74,8 @@ export const PromptTemplateEditor = ({
* 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.
+ * ten images held on to all ten. Stored images are owned by the shared image
+ * resource; only local replacement previews are tracked here.
*/
const takeObjectUrl = useCallback((file: Blob | null): string | null => {
if (objectUrlRef.current) {
@@ -89,53 +87,41 @@ export const PromptTemplateEditor = ({
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
- // draft from then on.
- useMountEffect(() => {
- const imageUrl = template?.imageUrl;
-
- if (!imageUrl) {
- return;
+ useMountEffect(() => () => {
+ if (objectUrlRef.current) {
+ URL.revokeObjectURL(objectUrlRef.current);
}
-
- void catalog.fetchImage(imageUrl).then((image) => {
- if (image) {
- setDraft((current) =>
- current.isExistingImageSettled ? current : { ...current, image, isExistingImageSettled: true }
- );
- }
- });
});
const trimmedName = draft.name.trim();
const isPlaceholderPresent = draft.positivePrompt.includes(PROMPT_TEMPLATE_PLACEHOLDER);
const nameError = trimmedName.length > MAX_NAME_LENGTH ? t('widgets.generate.promptTemplates.nameTooLong') : null;
+ const hasImage = draft.image.kind === 'replace' || (draft.image.kind === 'preserve' && template?.hasImage === true);
const save = useCallback(async () => {
- const nextDraft: PromptTemplateDraft = {
- image: draft.image,
- name: trimmedName,
- negativePrompt: draft.negativePrompt,
- positivePrompt: draft.positivePrompt,
- };
-
setIsSaving(true);
setError(null);
let saved: PromptTemplateRecord;
try {
- saved = template ? await catalog.update(template.id, nextDraft) : await catalog.create(nextDraft);
+ if (template) {
+ const nextDraft: PromptTemplateUpdateDraft = {
+ image: draft.image,
+ name: trimmedName,
+ negativePrompt: draft.negativePrompt,
+ positivePrompt: draft.positivePrompt,
+ };
+ saved = await catalog.update(template, nextDraft);
+ } else {
+ const nextDraft: PromptTemplateCreateDraft = {
+ image: draft.image.kind === 'replace' ? draft.image.blob : null,
+ name: trimmedName,
+ negativePrompt: draft.negativePrompt,
+ positivePrompt: draft.positivePrompt,
+ };
+ saved = await catalog.create(nextDraft);
+ }
} catch (caught) {
// `ApiError.message` is the raw response body, so the backend's own
// explanation only reads properly once it is unwrapped.
@@ -181,7 +167,11 @@ export const PromptTemplateEditor = ({
if (file) {
const imagePreviewUrl = takeObjectUrl(file);
- setDraft((current) => ({ ...current, image: file, imagePreviewUrl, isExistingImageSettled: true }));
+ setDraft((current) => ({
+ ...current,
+ image: { blob: file, kind: 'replace' },
+ imagePreviewUrl,
+ }));
}
// Reset so re-picking the same file still fires a change.
@@ -192,7 +182,7 @@ export const PromptTemplateEditor = ({
const clearImage = useCallback(() => {
takeObjectUrl(null);
- setDraft((current) => ({ ...current, image: null, imagePreviewUrl: null, isExistingImageSettled: true }));
+ setDraft((current) => ({ ...current, image: { kind: 'remove' }, imagePreviewUrl: null }));
}, [takeObjectUrl]);
const reportSaveError = useCallback(
@@ -291,16 +281,28 @@ export const PromptTemplateEditor = ({
<Field label={t('widgets.generate.promptTemplates.image')}>
<HStack gap="2">
- {draft.imagePreviewUrl ? (
- <Image
+ {template ? (
+ <PromptTemplateImage
alt=""
boxSize="12"
borderColor="border.emphasized"
borderWidth="1px"
flexShrink="0"
+ fallback={null}
+ localPreviewUrl={draft.imagePreviewUrl}
+ objectFit="cover"
+ rounded="md"
+ template={template}
+ />
+ ) : draft.imagePreviewUrl ? (
+ <PromptTemplateImage
+ alt=""
+ boxSize="12"
+ fallback={null}
+ localPreviewUrl={draft.imagePreviewUrl}
objectFit="cover"
rounded="md"
- src={draft.imagePreviewUrl}
+ template={NEW_TEMPLATE_IMAGE}
/>
) : null}
<DropZone
@@ -317,12 +319,12 @@ export const PromptTemplateEditor = ({
>
<ImageUpIcon size={14} />
<Text as="span" fontSize="2xs">
- {draft.imagePreviewUrl
+ {hasImage
? t('widgets.generate.promptTemplates.replaceImage')
: t('widgets.generate.promptTemplates.addImage')}
</Text>
</DropZone>
- {draft.imagePreviewUrl ? (
+ {hasImage ? (
<Tooltip content={t('widgets.generate.promptTemplates.removeImage')}>
<IconButton
aria-label={t('widgets.generate.promptTemplates.removeImage')}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateImage.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateImage.tsx
new file mode 100644
index 0000000000..d24620c771
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateImage.tsx
@@ -0,0 +1,67 @@
+import type { ImageProps } from '@chakra-ui/react';
+import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type { ReactNode } from 'react';
+
+import { Image } from '@chakra-ui/react';
+import { promptTemplateImageQueryOptions } from '@features/generation/data/promptTemplates';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { useQuery } from '@tanstack/react-query';
+import { useState } from 'react';
+
+const blobKeys = new WeakMap<Blob, number>();
+let nextBlobKey = 1;
+
+const getBlobKey = (blob: Blob): number => {
+ const existing = blobKeys.get(blob);
+
+ if (existing !== undefined) {
+ return existing;
+ }
+
+ const key = nextBlobKey;
+ nextBlobKey += 1;
+ blobKeys.set(blob, key);
+ return key;
+};
+
+interface PromptTemplateImageProps extends Omit<ImageProps, 'src'> {
+ fallback: ReactNode;
+ /**
+ * Undefined means "show the stored image"; a URL previews a local
+ * replacement, and null explicitly hides a removed image.
+ */
+ localPreviewUrl?: string | null;
+ template: Pick<PromptTemplateRecord, 'hasImage' | 'id'>;
+}
+
+export const PromptTemplateImage = ({
+ fallback,
+ localPreviewUrl,
+ template,
+ ...imageProps
+}: PromptTemplateImageProps) => {
+ const hasLocalOverride = localPreviewUrl !== undefined;
+ const query = useQuery({
+ ...promptTemplateImageQueryOptions(template.id),
+ enabled: template.hasImage && !hasLocalOverride,
+ retry: false,
+ });
+
+ if (hasLocalOverride) {
+ return localPreviewUrl ? <Image {...imageProps} src={localPreviewUrl} /> : fallback;
+ }
+
+ if (!query.data) {
+ return fallback;
+ }
+
+ return <BlobImage key={getBlobKey(query.data)} blob={query.data} imageProps={imageProps} />;
+};
+
+const BlobImage = ({ blob, imageProps }: { blob: Blob; imageProps: Omit<ImageProps, 'src'> }) => {
+ const [src] = useState(() => URL.createObjectURL(blob));
+
+ useMountEffect(() => () => URL.revokeObjectURL(src));
+
+ return <Image {...imageProps} src={src} />;
+};
diff --git a/tests/app/routers/test_style_presets.py b/tests/app/routers/test_style_presets.py
index 5712ec2ef4..7233165120 100644
--- a/tests/app/routers/test_style_presets.py
+++ b/tests/app/routers/test_style_presets.py
@@ -208,6 +208,81 @@ def test_update_with_valid_data_changes_record(client: TestClient, user1_token:
assert refreshed.name == "After"
+def test_update_with_preserve_image_does_not_mutate_image(
+ client: TestClient, user1_token: str, mock_invoker: Invoker
+):
+ mock_invoker.services.style_preset_image_files.get_url.return_value = "/existing.png"
+ user1 = _user_id(mock_invoker, "[email protected]")
+ seeded = _seed(mock_invoker, user1, name="Before")
+
+ r = client.patch(
+ f"/api/v1/style_presets/i/{seeded.id}",
+ data={**_form(name="After"), "preserve_image": "true"},
+ headers=_auth(user1_token),
+ )
+
+ assert r.status_code == status.HTTP_200_OK
+ mock_invoker.services.style_preset_image_files.save.assert_not_called()
+ mock_invoker.services.style_preset_image_files.delete.assert_not_called()
+ assert mock_invoker.services.style_preset_records.get(seeded.id).name == "After"
+
+
+def test_update_without_image_deletes_existing_image(
+ client: TestClient, user1_token: str, mock_invoker: Invoker
+):
+ mock_invoker.services.style_preset_image_files.get_url.return_value = None
+ user1 = _user_id(mock_invoker, "[email protected]")
+ seeded = _seed(mock_invoker, user1)
+
+ r = client.patch(
+ f"/api/v1/style_presets/i/{seeded.id}",
+ data=_form(),
+ headers=_auth(user1_token),
+ )
+
+ assert r.status_code == status.HTTP_200_OK
+ mock_invoker.services.style_preset_image_files.delete.assert_called_once_with(seeded.id)
+ mock_invoker.services.style_preset_image_files.save.assert_not_called()
+
+
+def test_update_with_image_replaces_existing_image(client: TestClient, user1_token: str, mock_invoker: Invoker):
+ mock_invoker.services.style_preset_image_files.get_url.return_value = "/replacement.png"
+ user1 = _user_id(mock_invoker, "[email protected]")
+ seeded = _seed(mock_invoker, user1)
+
+ r = client.patch(
+ f"/api/v1/style_presets/i/{seeded.id}",
+ data=_form(),
+ files={"image": ("x.png", _png_bytes(), "image/png")},
+ headers=_auth(user1_token),
+ )
+
+ assert r.status_code == status.HTTP_200_OK
+ mock_invoker.services.style_preset_image_files.save.assert_called_once()
+ assert mock_invoker.services.style_preset_image_files.save.call_args.args[0] == seeded.id
+ mock_invoker.services.style_preset_image_files.delete.assert_not_called()
+
+
+def test_update_with_image_and_preserve_image_rejects_without_mutation(
+ client: TestClient, user1_token: str, mock_invoker: Invoker
+):
+ mock_invoker.services.style_preset_image_files.get_url.return_value = None
+ user1 = _user_id(mock_invoker, "[email protected]")
+ seeded = _seed(mock_invoker, user1, name="Before")
+
+ r = client.patch(
+ f"/api/v1/style_presets/i/{seeded.id}",
+ data={**_form(name="After"), "preserve_image": "true"},
+ files={"image": ("x.png", _png_bytes(), "image/png")},
+ headers=_auth(user1_token),
+ )
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+ mock_invoker.services.style_preset_image_files.save.assert_not_called()
+ mock_invoker.services.style_preset_image_files.delete.assert_not_called()
+ assert mock_invoker.services.style_preset_records.get(seeded.id).name == "Before"
+
+
def test_update_with_non_image_returns_415(client: TestClient, user1_token: str, mock_invoker: Invoker):
user1 = _user_id(mock_invoker, "[email protected]")
seeded = _seed(mock_invoker, user1, name="X")