Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): add the prompt templates data layer

joshistoasta4cd910f4107
diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts
new file mode 100644
index 0000000000..74aa26ebdb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts
@@ -0,0 +1,165 @@
+/**
+ * The current user's prompt templates, plus the catalog shipped with the backend.
+ *
+ * The route is `/api/v1/style_presets/` — "style preset" is the backend's name
+ * for the same thing, kept for wire compatibility with the legacy client, which
+ * writes to and reads from this exact store. Only this module speaks that
+ * vocabulary; everything above it says "prompt template".
+ *
+ * Create and update are multipart because a template may carry a preview image.
+ * `apiFetchJson` leaves `FormData` bodies alone, so the browser sets its own
+ * boundary while the injected `Authorization` header still rides along.
+ */
+
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
+import type { QueryClient } from '@tanstack/react-query';
+
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { absolutizeApiUrl, apiFetch, apiFetchJson } from '@platform/transport/http';
+import { queryOptions } from '@tanstack/react-query';
+
+const PROMPT_TEMPLATES_BASE = '/api/v1/style_presets';
+
+/** Private snake_case wire shape; never crosses the feature interface. */
+interface PromptTemplateDTO {
+ id: string;
+ name: string;
+ type: 'default' | 'user';
+ is_public: boolean;
+ user_id: string;
+ image: string | null;
+ preset_data: { positive_prompt: string; negative_prompt: string };
+}
+
+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;
+}
+
+export interface PromptTemplateDraft {
+ 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`.
+ */
+ image: Blob | null;
+}
+
+export const promptTemplateKeys = {
+ all: ['generation', 'promptTemplates'] as const,
+};
+
+const mapPromptTemplate = (dto: PromptTemplateDTO): PromptTemplateRecord => ({
+ id: dto.id,
+ imageUrl: dto.image ? absolutizeApiUrl(dto.image) : null,
+ isDefault: dto.type === 'default',
+ name: dto.name,
+ negativePrompt: dto.preset_data.negative_prompt,
+ positivePrompt: dto.preset_data.positive_prompt,
+});
+
+export const promptTemplatesQueryOptions = () =>
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: async ({ signal }): Promise<PromptTemplateRecord[]> => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const templates = await apiFetchJson<PromptTemplateDTO[]>(`${PROMPT_TEMPLATES_BASE}/`, {
+ signal: requestSignal,
+ });
+
+ assertAccountScopeCurrent(owner);
+ return templates.map(mapPromptTemplate);
+ },
+ queryKey: promptTemplateKeys.all,
+ staleTime: 30_000,
+ });
+ })();
+
+/**
+ * Authored templates are always the user's own and private. The backend also
+ * 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 body = new FormData();
+
+ body.append(
+ 'data',
+ JSON.stringify({
+ is_public: false,
+ name: draft.name,
+ negative_prompt: draft.negativePrompt,
+ positive_prompt: draft.positivePrompt,
+ type: 'user',
+ })
+ );
+
+ if (draft.image) {
+ body.append('image', draft.image);
+ }
+
+ return body;
+};
+
+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: PromptTemplateDraft): Promise<PromptTemplateRecord> =>
+ mapPromptTemplate(
+ await apiFetchJson<PromptTemplateDTO>(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}`, {
+ body: toFormData(draft),
+ 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);
+
+ return await response.blob();
+ } catch {
+ return null;
+ }
+};
+
+export const deletePromptTemplate = async (id: string): Promise<void> => {
+ await apiFetch(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}`, { method: 'DELETE' });
+};
+
+/** Accepts the CSV and JSON shapes documented by the backend's importer. */
+export const importPromptTemplates = async (file: File): Promise<void> => {
+ const body = new FormData();
+
+ body.append('file', file);
+ await apiFetch(`${PROMPT_TEMPLATES_BASE}/import`, { body, method: 'POST' });
+};
+
+/**
+ * Returns CSV, not JSON, so this goes through `apiFetch` rather than
+ * `apiFetchJson`. It also cannot be an anchor download: the URL alone carries no
+ * `Authorization` header, and only the transport injects one.
+ */
+export const exportPromptTemplates = async (): Promise<Blob> => {
+ const response = await apiFetch(`${PROMPT_TEMPLATES_BASE}/export`);
+
+ return await response.blob();
+};
+
+export const invalidatePromptTemplates = async (queryClient: QueryClient): Promise<void> => {
+ await queryClient.invalidateQueries({ queryKey: promptTemplateKeys.all });
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
index 452a3d3378..8396a07d96 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
@@ -1,17 +1,25 @@
import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
-import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
+import type {
+ GenerateModelConfig,
+ GenerateSettings,
+ GenerateWidgetValues,
+ LoraModelConfig,
+} from '@features/generation/core/types';
import {
getAutoFlux2ComponentSourceModel,
getDefaultGenerateSettings,
isSupportedGenerateModel,
} from '@features/generation/core/baseGenerationPolicies';
+import { syncPromptTemplateWithCatalog } from '@features/generation/core/promptTemplates';
import {
isLoraModelConfig,
normalizeGenerateSettings,
normalizeGenerateWidgetValues,
syncGenerateWidgetValuesWithModels,
} from '@features/generation/core/settings';
+import { usePromptTemplates } from '@features/generation/ui/usePromptTemplates';
import { useMountEffect } from '@platform/react/useMountEffect';
import { useCallback, useEffect, useMemo } from 'react';
@@ -33,6 +41,20 @@ const getSettingsWithAutoComponentSource = (
return { ...nextSettings, componentSourceModel };
};
+/**
+ * Returns the same object when the stored template still matches the catalog, so
+ * the identity short-circuit below keeps holding and an unchanged catalog cannot
+ * drive a commit loop.
+ */
+const getValuesWithSyncedPromptTemplate = (
+ values: GenerateWidgetValues,
+ promptTemplates: readonly PromptTemplateSnapshot[]
+): GenerateWidgetValues => {
+ const promptTemplate = syncPromptTemplateWithCatalog(values.promptTemplate, promptTemplates);
+
+ return promptTemplate === values.promptTemplate ? values : { ...values, promptTemplate };
+};
+
export const GenerateWidgetView = () => {
const ui = useGenerationUi();
const projectId = ui.project.activeProjectId;
@@ -40,6 +62,10 @@ export const GenerateWidgetView = () => {
const error = ui.models.error;
const models = ui.models.catalog;
const status = ui.models.status;
+ // The active template is stored as a snapshot, so an edit made in another tab
+ // or by another client only lands by re-reading it from the catalog here —
+ // the same treatment model snapshots get in `syncGenerateWidgetValuesWithModels`.
+ const { templates: promptTemplates } = usePromptTemplates();
useMountEffect(() => {
ui.models.ensureLoaded();
@@ -62,9 +88,12 @@ export const GenerateWidgetView = () => {
}
const storedWidgetValues = normalizeGenerateWidgetValues(storedValues);
- const syncedWidgetValues = storedWidgetValues
+ const modelSyncedValues = storedWidgetValues
? syncGenerateWidgetValuesWithModels(storedWidgetValues, models)
: null;
+ const syncedWidgetValues = modelSyncedValues
+ ? getValuesWithSyncedPromptTemplate(modelSyncedValues, promptTemplates)
+ : null;
const baseSettings = syncedWidgetValues ?? (selectedModel ? settings : getDefaultGenerateSettings(model));
const nextSettings = getSettingsWithAutoComponentSource(baseSettings, model, models);
@@ -78,7 +107,7 @@ export const GenerateWidgetView = () => {
}
ui.settings.patchGenerateSettings(getGenerateFormCommitPatch({ ...nextSettings, model }), projectId, 'system');
- }, [models, projectId, selectedModel, settings, storedValues, supportedModels, ui]);
+ }, [models, projectId, promptTemplates, selectedModel, settings, storedValues, supportedModels, ui]);
const commitSettings = useCallback(
(nextSettings: GenerateSettings) => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts
new file mode 100644
index 0000000000..d4bbdda1e6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts
@@ -0,0 +1,84 @@
+import type { PromptTemplateDraft, PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+
+import {
+ createPromptTemplate,
+ deletePromptTemplate,
+ exportPromptTemplates,
+ importPromptTemplates,
+ invalidatePromptTemplates,
+ promptTemplatesQueryOptions,
+ updatePromptTemplate,
+} from '@features/generation/data/promptTemplates';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useCallback, useMemo } from 'react';
+
+export interface PromptTemplateCatalog {
+ /** The user's own templates, name-ascending as the backend orders them. */
+ userTemplates: PromptTemplateRecord[];
+ /** Templates shipped with the backend; applicable but not editable. */
+ defaultTemplates: PromptTemplateRecord[];
+ /** Every visible template, for resolving a stored snapshot. */
+ templates: PromptTemplateRecord[];
+ isLoading: boolean;
+ /** Resolves with the saved record so a caller can refresh an applied snapshot. */
+ create: (draft: PromptTemplateDraft) => Promise<PromptTemplateRecord>;
+ update: (id: string, draft: PromptTemplateDraft) => Promise<PromptTemplateRecord>;
+ remove: (id: string) => Promise<void>;
+ importFile: (file: File) => Promise<void>;
+ exportCsv: () => Promise<Blob>;
+}
+
+/**
+ * The shared prompt template catalog. Each mutation captures the identity that
+ * started it, so a sign-out mid-flight does not invalidate the next account's
+ * cache on the way back — the same rule `useWildcards` follows.
+ */
+export const usePromptTemplates = (): PromptTemplateCatalog => {
+ const queryClient = useQueryClient();
+ const query = useQuery(promptTemplatesQueryOptions());
+ const templates = useMemo(() => query.data ?? [], [query.data]);
+ const defaultTemplates = useMemo(() => templates.filter((template) => template.isDefault), [templates]);
+ const userTemplates = useMemo(() => templates.filter((template) => !template.isDefault), [templates]);
+
+ const runAndInvalidate = useCallback(
+ async <T>(run: () => Promise<T>): Promise<T> => {
+ const owner = captureAccountScope();
+ const result = await run();
+
+ assertAccountScopeCurrent(owner);
+ await invalidatePromptTemplates(queryClient);
+ return result;
+ },
+ [queryClient]
+ );
+
+ const create = useCallback(
+ (draft: PromptTemplateDraft) => runAndInvalidate(() => createPromptTemplate(draft)),
+ [runAndInvalidate]
+ );
+
+ const update = useCallback(
+ (id: string, draft: PromptTemplateDraft) => runAndInvalidate(() => updatePromptTemplate(id, draft)),
+ [runAndInvalidate]
+ );
+
+ const remove = useCallback((id: string) => runAndInvalidate(() => deletePromptTemplate(id)), [runAndInvalidate]);
+
+ const importFile = useCallback(
+ (file: File) => runAndInvalidate(() => importPromptTemplates(file)),
+ [runAndInvalidate]
+ );
+
+ return {
+ create,
+ defaultTemplates,
+ exportCsv: exportPromptTemplates,
+ importFile,
+ isLoading: query.isPending,
+ remove,
+ templates,
+ update,
+ userTemplates,
+ };
+};