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: respect prompt template ownership

joshistoast43cb428f8a81
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 27723ec38b..f3e0b0154a 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1022,6 +1022,7 @@
"editTemplate": "Edit template",
"search": "Search templates",
"yourTemplates": "Your templates",
+ "sharedTemplates": "Shared templates",
"defaultTemplates": "Built-in templates",
"noTemplatesYet": "No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.",
"noMatches": "No matching templates",
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index f4ec81b0a5..872e60d380 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react';
import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
import { GenerationUiProvider } from '@features/generation/react';
-import { useCapabilities } from '@features/identity';
+import { useAuthSession, useCapabilities } from '@features/identity';
import { ensureModelsLoaded, getModelBaseColorPalette, getModelBaseLabel, useModelsSelector } from '@features/models';
import { useQueryClient } from '@tanstack/react-query';
import {
@@ -43,6 +43,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
const modelsError = useModelsSelector((snapshot) => snapshot.error);
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
const { generation, notifications } = useWorkbenchCommands();
+ const session = useAuthSession();
const queryClient = useQueryClient();
const notify = useNotify();
@@ -86,6 +87,13 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
() => ({ canManagePromptTemplates }),
[canManagePromptTemplates]
);
+ const accountGroup = useMemo<GenerationUiAdapter['account']>(
+ () => ({
+ currentUserId: session.user?.user_id ?? null,
+ multiuserEnabled: session.multiuserEnabled,
+ }),
+ [session.multiuserEnabled, session.user?.user_id]
+ );
const generateSectionsOpen = useWorkbenchPreferenceSelector((preferences) => preferences.generateSectionsOpen);
const sectionPreferencesGroup = useMemo<GenerationUiAdapter['sectionPreferences']>(
() => ({
@@ -102,6 +110,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
const adapter = useMemo<GenerationUiAdapter>(
() => ({
CanvasCompositingSection: GenerateCanvasCompositingSection,
+ account: accountGroup,
capabilities: capabilitiesGroup,
gallery: galleryGroup,
models: modelsGroup,
@@ -112,6 +121,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
settings: settingsGroup,
}),
[
+ accountGroup,
capabilitiesGroup,
galleryGroup,
modelsGroup,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.test.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.test.ts
new file mode 100644
index 0000000000..5240e80f20
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyPromptTemplates,
+ PromptTemplateOwnershipError,
+ requireOwnedPromptTemplate,
+} from './promptTemplateOwnership';
+
+interface Template {
+ id: string;
+ isDefault: boolean;
+ isPublic: boolean;
+ userId: string;
+}
+
+const template = (overrides: Partial<Template> = {}): Template => ({
+ id: 'template',
+ isDefault: false,
+ isPublic: false,
+ userId: 'owner',
+ ...overrides,
+});
+
+describe('prompt template ownership policy', () => {
+ it('classifies every non-default template as personal in single-user mode', () => {
+ const records = [template({ id: 'private' }), template({ id: 'public', isPublic: true, userId: 'other' })];
+
+ expect(
+ classifyPromptTemplates(records, { currentUserId: null, multiuserEnabled: false }).personalTemplates
+ ).toEqual(records);
+ });
+
+ it('separates owned, shared, built-in, and hidden records in multi-user mode', () => {
+ const personal = template({ id: 'personal' });
+ const shared = template({ id: 'shared', isPublic: true, userId: 'other' });
+ const hidden = template({ id: 'hidden', userId: 'other' });
+ const builtIn = template({ id: 'built-in', isDefault: true, userId: 'system' });
+
+ const result = classifyPromptTemplates([personal, shared, hidden, builtIn], {
+ currentUserId: 'owner',
+ multiuserEnabled: true,
+ });
+
+ expect(result.personalTemplates).toEqual([personal]);
+ expect(result.sharedTemplates).toEqual([shared]);
+ expect(result.defaultTemplates).toEqual([builtIn]);
+ expect(result.templates).toEqual([personal, shared, builtIn]);
+ });
+
+ it('exposes only built-ins while multi-user identity is unresolved', () => {
+ const personal = template();
+ const builtIn = template({ id: 'built-in', isDefault: true });
+
+ expect(classifyPromptTemplates([personal, builtIn], { currentUserId: null, multiuserEnabled: true })).toEqual({
+ defaultTemplates: [builtIn],
+ personalTemplates: [],
+ sharedTemplates: [],
+ templates: [builtIn],
+ });
+ });
+
+ it('does not grant a foreign private record to an administrator-shaped viewer', () => {
+ const foreignPrivate = template({ userId: 'other' });
+
+ expect(
+ classifyPromptTemplates([foreignPrivate], {
+ currentUserId: 'admin',
+ multiuserEnabled: true,
+ }).templates
+ ).toEqual([]);
+ });
+
+ it('rejects mutations of shared and built-in records', () => {
+ const account = { currentUserId: 'owner', multiuserEnabled: true };
+
+ expect(() => requireOwnedPromptTemplate(template({ isPublic: true, userId: 'other' }), account)).toThrow(
+ PromptTemplateOwnershipError
+ );
+ expect(() => requireOwnedPromptTemplate(template({ isDefault: true }), account)).toThrow(
+ PromptTemplateOwnershipError
+ );
+ expect(() => requireOwnedPromptTemplate(template(), account)).not.toThrow();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.ts
new file mode 100644
index 0000000000..2db08d0e92
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplateOwnership.ts
@@ -0,0 +1,64 @@
+export interface PromptTemplateAccount {
+ currentUserId: string | null;
+ multiuserEnabled: boolean;
+}
+
+interface PromptTemplateOwnershipRecord {
+ isDefault: boolean;
+ isPublic: boolean;
+ userId: string;
+}
+
+export interface ClassifiedPromptTemplates<T> {
+ defaultTemplates: T[];
+ personalTemplates: T[];
+ sharedTemplates: T[];
+ /** The records visible to this account, excluding foreign private templates. */
+ templates: T[];
+}
+
+export const classifyPromptTemplates = <T extends PromptTemplateOwnershipRecord>(
+ records: readonly T[],
+ account: PromptTemplateAccount
+): ClassifiedPromptTemplates<T> => {
+ const defaultTemplates: T[] = [];
+ const personalTemplates: T[] = [];
+ const sharedTemplates: T[] = [];
+
+ for (const record of records) {
+ if (record.isDefault) {
+ defaultTemplates.push(record);
+ } else if (!account.multiuserEnabled || record.userId === account.currentUserId) {
+ personalTemplates.push(record);
+ } else if (account.currentUserId !== null && record.isPublic) {
+ sharedTemplates.push(record);
+ }
+ }
+
+ return {
+ defaultTemplates,
+ personalTemplates,
+ sharedTemplates,
+ templates: [...personalTemplates, ...sharedTemplates, ...defaultTemplates],
+ };
+};
+
+export class PromptTemplateOwnershipError extends Error {
+ constructor() {
+ super('Only personal prompt templates can be changed.');
+ this.name = 'PromptTemplateOwnershipError';
+ }
+}
+
+export const requireOwnedPromptTemplate = (
+ record: PromptTemplateOwnershipRecord,
+ account: PromptTemplateAccount
+): void => {
+ const isOwned =
+ !record.isDefault &&
+ (!account.multiuserEnabled || (account.currentUserId !== null && record.userId === account.currentUserId));
+
+ if (!isOwned) {
+ throw new PromptTemplateOwnershipError();
+ }
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index 3db1d77c72..c30be6b8cf 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -33,6 +33,10 @@ export interface GenerationSelectedImage {
*/
export interface GenerationUiAdapter {
CanvasCompositingSection: ComponentType;
+ account: {
+ currentUserId: string | null;
+ multiuserEnabled: boolean;
+ };
capabilities: {
/** Bulk import/export of prompt templates; the backend routes are admin-only. */
canManagePromptTemplates: boolean;
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 3a809e830c..be4aeca314 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,8 +2,11 @@ import type { PromptTemplateRecord } from '@features/generation/data/promptTempl
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import { ChakraProvider } from '@chakra-ui/react';
+import { promptTemplateKeys } from '@features/generation/data/promptTemplates';
import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
+import { PromptTemplateImage } from '@features/generation/ui/promptFields/PromptTemplateImage';
import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import i18next from 'i18next';
import { act } from 'react';
@@ -42,6 +45,7 @@ const translation = {
editTemplate: 'Edit template',
search: 'Search templates',
yourTemplates: 'Your templates',
+ sharedTemplates: 'Shared templates',
defaultTemplates: 'Built-in templates',
noTemplatesYet: 'No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.',
noMatches: 'No matching templates',
@@ -94,57 +98,79 @@ let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const templateWithImage: PromptTemplateRecord = {
+ hasImage: true,
id: 'user-1',
- imageUrl: 'http://host/image.png',
isDefault: false,
+ isPublic: false,
name: 'Cinematic',
negativePrompt: '',
positivePrompt: '{prompt}, cinematic',
+ userId: 'user-1',
};
const userTemplate: PromptTemplateRecord = {
+ hasImage: false,
id: 'user-1',
- imageUrl: null,
isDefault: false,
+ isPublic: false,
name: 'Cinematic',
negativePrompt: '',
positivePrompt: '{prompt}, cinematic still',
+ userId: 'user-1',
+};
+
+const sharedTemplate: PromptTemplateRecord = {
+ hasImage: false,
+ id: 'shared-1',
+ isDefault: false,
+ isPublic: true,
+ name: 'Community',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, shared',
+ userId: 'user-2',
};
const defaultTemplate: PromptTemplateRecord = {
+ hasImage: false,
id: 'default-1',
- imageUrl: null,
isDefault: true,
+ isPublic: false,
name: 'Photography',
negativePrompt: '',
positivePrompt: '{prompt}. photography, bokeh',
+ userId: 'system',
};
+const IMAGE_FALLBACK = <span>fallback</span>;
const createCatalog = (overrides: Partial<PromptTemplateCatalog> = {}): PromptTemplateCatalog => ({
create: vi.fn(),
defaultTemplates: [defaultTemplate],
exportCsv: vi.fn(),
- fetchImage: vi.fn().mockResolvedValue(null),
importFile: vi.fn(),
isLoaded: true,
isLoading: false,
+ personalTemplates: [userTemplate],
remove: vi.fn(),
- templates: [userTemplate, defaultTemplate],
+ sharedTemplates: [sharedTemplate],
+ templates: [userTemplate, sharedTemplate, defaultTemplate],
update: vi.fn(),
- userTemplates: [userTemplate],
...overrides,
});
-const render = async (element: React.ReactNode) => {
+const render = async (element: React.ReactNode, seed?: (queryClient: QueryClient) => void) => {
host = document.createElement('div');
host.style.width = '400px';
document.body.append(host);
root = createRoot(host);
+ const queryClient = new QueryClient();
+ seed?.(queryClient);
await act(() => {
root?.render(
<I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>{element}</ChakraProvider>
+ <QueryClientProvider client={queryClient}>
+ <ChakraProvider value={system}>{element}</ChakraProvider>
+ </QueryClientProvider>
</I18nextProvider>
);
});
@@ -180,8 +206,8 @@ describe('the prompt templates panel', () => {
await userEvent.click(buttonWithText('Cinematic'));
});
- // The four snapshot fields only. `isDefault` and the absolute `imageUrl`
- // belong to the catalog, not to persisted project state.
+ // The four snapshot fields only. Ownership and image metadata belong to the
+ // catalog, not to persisted project state.
expect(onApply).toHaveBeenCalledWith({
id: userTemplate.id,
name: userTemplate.name,
@@ -268,7 +294,7 @@ describe('the prompt templates panel', () => {
expect(labels.filter((label) => label === 'Delete')).toHaveLength(1);
});
- it('searches prompt text, not just the name', async () => {
+ it('does not search prompt prose', async () => {
await render(
<PromptTemplatesPanel
activeTemplate={null}
@@ -285,7 +311,7 @@ describe('the prompt templates panel', () => {
await userEvent.fill(host!.querySelector('input')!, 'bokeh');
});
- expect(host!.textContent).toContain('Photography');
+ expect(host!.textContent).not.toContain('Photography');
expect(host!.textContent).not.toContain('Cinematic');
});
@@ -297,7 +323,7 @@ describe('the prompt templates panel', () => {
<PromptTemplatesPanel
activeTemplate={userTemplate}
isActiveTemplateMissing
- catalog={createCatalog({ templates: [defaultTemplate], userTemplates: [] })}
+ catalog={createCatalog({ personalTemplates: [], templates: [sharedTemplate, defaultTemplate] })}
onApply={vi.fn()}
onCreate={vi.fn()}
onDetach={vi.fn()}
@@ -326,9 +352,7 @@ describe('the prompt templates panel', () => {
expect(host!.textContent).not.toContain('was deleted');
});
- // The same fuzzy name rule the wildcards panel beside it has always used —
- // these two sit in one popover and used to disagree about what typing means.
- it('matches a name fuzzily', async () => {
+ it('does not fuzzy-match a template name', async () => {
await render(
<PromptTemplatesPanel
activeTemplate={null}
@@ -345,9 +369,50 @@ describe('the prompt templates panel', () => {
await userEvent.fill(host!.querySelector('input')!, 'cnmt');
});
+ expect(host!.textContent).not.toContain('Cinematic');
+ expect(host!.textContent).not.toContain('Photography');
+ });
+
+ it('matches a case-insensitive name substring', async () => {
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ isActiveTemplateMissing={false}
+ catalog={createCatalog()}
+ onApply={vi.fn()}
+ onCreate={vi.fn()}
+ onDetach={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.fill(host!.querySelector('input')!, 'NEMA');
+ });
+
expect(host!.textContent).toContain('Cinematic');
expect(host!.textContent).not.toContain('Photography');
});
+
+ it('renders shared templates without edit or delete controls', async () => {
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ isActiveTemplateMissing={false}
+ catalog={createCatalog()}
+ onApply={vi.fn()}
+ onCreate={vi.fn()}
+ onDetach={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ expect(host!.textContent).toContain('Shared templates');
+ expect(host!.textContent).toContain('Community');
+ const labels = [...host!.querySelectorAll('button')].map((button) => button.getAttribute('aria-label'));
+ expect(labels.filter((label) => label === 'Edit')).toHaveLength(1);
+ expect(labels.filter((label) => label === 'Delete')).toHaveLength(1);
+ });
});
describe('the prompt template editor', () => {
@@ -405,21 +470,32 @@ 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 () => {
+ it('preserves an existing image when an edit is saved immediately', async () => {
const catalog = createCatalog();
- let resolveImage: (image: Blob) => void = () => {};
- catalog.fetchImage = vi.fn(
- () =>
- 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(buttonWithText('Save'));
+ });
+
+ expect(catalog.update).toHaveBeenCalledWith(
+ templateWithImage,
+ expect.objectContaining({ image: { kind: 'preserve' } })
+ );
+ });
+
+ it('marks an existing image for removal only after the user removes it', async () => {
+ const catalog = createCatalog();
+
await render(
<PromptTemplateEditor
catalog={catalog}
@@ -432,18 +508,39 @@ describe('the prompt template editor', () => {
await act(async () => {
await userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Remove image"]')!);
+ await userEvent.click(buttonWithText('Save'));
});
- await act(async () => {
- resolveImage(new Blob(['old'], { type: 'image/png' }));
- await Promise.resolve();
- });
+ expect(catalog.update).toHaveBeenCalledWith(
+ templateWithImage,
+ expect.objectContaining({ image: { kind: 'remove' } })
+ );
+ });
+ it('marks a picked image as the replacement', async () => {
+ const catalog = createCatalog();
+ const replacement = new File(['new'], 'new.png', { type: 'image/png' });
+
+ await render(
+ <PromptTemplateEditor
+ catalog={catalog}
+ showSyntaxHighlighting
+ template={templateWithImage}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ );
+
+ const input = host!.querySelector<HTMLInputElement>('input[type="file"]')!;
await act(async () => {
+ await userEvent.upload(input, replacement);
await userEvent.click(buttonWithText('Save'));
});
- expect(catalog.update).toHaveBeenCalledWith('user-1', expect.objectContaining({ image: null }));
+ expect(catalog.update).toHaveBeenCalledWith(
+ templateWithImage,
+ expect.objectContaining({ image: { blob: replacement, kind: 'replace' } })
+ );
});
it('keeps Save out of reach until the template is named', async () => {
@@ -466,3 +563,20 @@ describe('the prompt template editor', () => {
expect(buttonWithText('Save').disabled).toBe(false);
});
});
+
+it('revokes a fetched template image blob URL when it unmounts', async () => {
+ const createObjectUrl = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:template-preview');
+ const revokeObjectUrl = vi.spyOn(URL, 'revokeObjectURL');
+
+ await render(<PromptTemplateImage alt="" fallback={IMAGE_FALLBACK} template={templateWithImage} />, (queryClient) =>
+ queryClient.setQueryData(promptTemplateKeys.image(templateWithImage.id), new Blob(['image']))
+ );
+
+ expect(createObjectUrl).toHaveBeenCalledOnce();
+ await act(() => root?.unmount());
+ root = null;
+ expect(revokeObjectUrl).toHaveBeenCalledWith('blob:template-preview');
+
+ createObjectUrl.mockRestore();
+ revokeObjectUrl.mockRestore();
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx
index 0b87d4985b..7bef9f2eb4 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx
@@ -15,14 +15,14 @@ const catalog: PromptTemplateCatalog = {
create: vi.fn(),
defaultTemplates: [],
exportCsv: vi.fn(),
- fetchImage: vi.fn().mockResolvedValue(null),
importFile: vi.fn(),
isLoaded: true,
isLoading: false,
+ personalTemplates: [],
remove: vi.fn(),
+ sharedTemplates: [],
templates: [],
update: vi.fn(),
- userTemplates: [],
};
const usePromptTemplates = vi.fn((_options?: { isEnabled?: boolean }) => catalog);
@@ -143,7 +143,18 @@ describe('the prompt templates button', () => {
});
it('leaves the name alone while the template is still there', async () => {
- usePromptTemplates.mockReturnValue({ ...catalog, templates: [{ ...applied, imageUrl: null, isDefault: false }] });
+ usePromptTemplates.mockReturnValue({
+ ...catalog,
+ templates: [
+ {
+ ...applied,
+ hasImage: false,
+ isDefault: false,
+ isPublic: false,
+ userId: 'user-1',
+ },
+ ],
+ });
await render(applied);
const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
index d691bbc4df..942788831c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
@@ -3,12 +3,12 @@ import type { PromptTemplateRecord } from '@features/generation/data/promptTempl
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import type { ChangeEvent } from 'react';
-import { Box, HStack, Image, Input, Separator, Stack, Text } from '@chakra-ui/react';
-import { searchCatalog } from '@features/generation/core/catalogSearch';
+import { Box, HStack, Input, Separator, Stack, Text } from '@chakra-ui/react';
import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
import { toPromptTemplateSnapshot } from '@features/generation/data/promptTemplates';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
+import { PromptTemplateImage } from '@features/generation/ui/promptFields/PromptTemplateImage';
import { downloadBlob } from '@platform/browser/downloadBlob';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
@@ -20,6 +20,20 @@ import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
const THUMBNAIL_SIZE = '7';
+const TEMPLATE_THUMBNAIL_FALLBACK = (
+ <Box
+ alignItems="center"
+ bg="bg.emphasized"
+ boxSize={THUMBNAIL_SIZE}
+ color="fg.subtle"
+ display="flex"
+ flexShrink="0"
+ justifyContent="center"
+ rounded="sm"
+ >
+ <ImageIcon size={12} />
+ </Box>
+);
interface PromptTemplatesPanelProps {
catalog: PromptTemplateCatalog;
@@ -36,11 +50,14 @@ interface PromptTemplatesPanelProps {
onCreate: () => void;
}
-/** A template's prose is its two prompts; `searchCatalog` handles the name. */
-const getTemplateProse = (template: PromptTemplateRecord): readonly string[] => [
- template.positivePrompt,
- template.negativePrompt,
-];
+const filterTemplatesByName = (
+ templates: readonly PromptTemplateRecord[],
+ searchTerm: string
+): PromptTemplateRecord[] => {
+ const query = searchTerm.trim().toLocaleLowerCase();
+
+ return query ? templates.filter((template) => template.name.toLocaleLowerCase().includes(query)) : [...templates];
+};
export const PromptTemplatesPanel = ({
activeTemplate,
@@ -57,15 +74,19 @@ export const PromptTemplatesPanel = ({
const [searchTerm, setSearchTerm] = useState('');
const [pendingDelete, setPendingDelete] = useState<PromptTemplateRecord | null>(null);
- const userTemplates = useMemo(
- () => searchCatalog(catalog.userTemplates, searchTerm, getTemplateProse),
- [catalog.userTemplates, searchTerm]
+ const personalTemplates = useMemo(
+ () => filterTemplatesByName(catalog.personalTemplates, searchTerm),
+ [catalog.personalTemplates, searchTerm]
+ );
+ const sharedTemplates = useMemo(
+ () => filterTemplatesByName(catalog.sharedTemplates, searchTerm),
+ [catalog.sharedTemplates, searchTerm]
);
const defaultTemplates = useMemo(
- () => searchCatalog(catalog.defaultTemplates, searchTerm, getTemplateProse),
+ () => filterTemplatesByName(catalog.defaultTemplates, searchTerm),
[catalog.defaultTemplates, searchTerm]
);
- const hasResults = userTemplates.length > 0 || defaultTemplates.length > 0;
+ const hasResults = personalTemplates.length > 0 || sharedTemplates.length > 0 || defaultTemplates.length > 0;
const handleSearchChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value),
@@ -85,7 +106,7 @@ export const PromptTemplatesPanel = ({
}
try {
- await catalog.remove(pendingDelete.id);
+ await catalog.remove(pendingDelete);
// Deleting the template that is applied would otherwise leave it silently
// shaping every prompt with no way to reach it. Detached rather than
@@ -135,11 +156,17 @@ export const PromptTemplatesPanel = ({
<TemplateGroup
activeTemplateId={activeTemplate?.id ?? null}
label={t('widgets.generate.promptTemplates.yourTemplates')}
- templates={userTemplates}
+ templates={personalTemplates}
onApply={onApply}
onDelete={setPendingDelete}
onEdit={onEdit}
/>
+ <TemplateGroup
+ activeTemplateId={activeTemplate?.id ?? null}
+ label={t('widgets.generate.promptTemplates.sharedTemplates')}
+ templates={sharedTemplates}
+ onApply={onApply}
+ />
<TemplateGroup
activeTemplateId={activeTemplate?.id ?? null}
label={t('widgets.generate.promptTemplates.defaultTemplates')}
@@ -388,20 +415,14 @@ const TemplateRow = ({
);
};
-const TemplateThumbnail = ({ template }: { template: PromptTemplateRecord }) =>
- template.imageUrl ? (
- <Image alt="" boxSize={THUMBNAIL_SIZE} flexShrink="0" objectFit="cover" rounded="sm" src={template.imageUrl} />
- ) : (
- <Box
- alignItems="center"
- bg="bg.emphasized"
- boxSize={THUMBNAIL_SIZE}
- color="fg.subtle"
- display="flex"
- flexShrink="0"
- justifyContent="center"
- rounded="sm"
- >
- <ImageIcon size={12} />
- </Box>
- );
+const TemplateThumbnail = ({ template }: { template: PromptTemplateRecord }) => (
+ <PromptTemplateImage
+ alt=""
+ boxSize={THUMBNAIL_SIZE}
+ fallback={TEMPLATE_THUMBNAIL_FALLBACK}
+ flexShrink="0"
+ objectFit="cover"
+ rounded="sm"
+ template={template}
+ />
+);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts
index c66c8557eb..61edddb4cb 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts
@@ -1,11 +1,15 @@
import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
-import type { PromptTemplateDraft, PromptTemplateRecord } from '@features/generation/data/promptTemplates';
+import type {
+ PromptTemplateCreateDraft,
+ PromptTemplateRecord,
+ PromptTemplateUpdateDraft,
+} from '@features/generation/data/promptTemplates';
+import { classifyPromptTemplates, requireOwnedPromptTemplate } from '@features/generation/core/promptTemplateOwnership';
import {
createPromptTemplate,
deletePromptTemplate,
exportPromptTemplates,
- fetchPromptTemplateImage,
importPromptTemplates,
invalidatePromptTemplates,
promptTemplatesQueryOptions,
@@ -15,9 +19,13 @@ import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
+import { useGenerationUi } from './GenerationUiContext';
+
export interface PromptTemplateCatalog {
/** The user's own templates, name-ascending as the backend orders them. */
- userTemplates: PromptTemplateRecord[];
+ personalTemplates: PromptTemplateRecord[];
+ /** Public templates owned by somebody else; applicable but read-only. */
+ sharedTemplates: PromptTemplateRecord[];
/** Templates shipped with the backend; applicable but not editable. */
defaultTemplates: PromptTemplateRecord[];
/** Every visible template, for resolving a stored snapshot. */
@@ -31,20 +39,11 @@ export interface PromptTemplateCatalog {
*/
isLoaded: 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>;
+ create: (draft: PromptTemplateCreateDraft) => Promise<PromptTemplateRecord>;
+ update: (template: PromptTemplateRecord, draft: PromptTemplateUpdateDraft) => Promise<PromptTemplateRecord>;
+ remove: (template: PromptTemplateRecord) => Promise<void>;
importFile: (file: File) => Promise<void>;
exportCsv: () => Promise<Blob>;
- /**
- * The preview image behind a record's `imageUrl`, or null.
- *
- * On the port rather than imported straight from `data/` by the one component
- * that needs it: everything else here is injectable, and a single direct
- * import made the editor's tests mock a module to stand in for a dependency
- * they were otherwise handed.
- */
- fetchImage: (imageUrl: string) => Promise<Blob | null>;
}
/**
@@ -54,37 +53,49 @@ export interface PromptTemplateCatalog {
*/
export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean } = {}): PromptTemplateCatalog => {
const queryClient = useQueryClient();
+ const { account } = useGenerationUi();
// Off by default for the widget, which only wants to re-read an applied
// template and has nothing to re-read when none is applied. The picker asks
// for it in earnest, and shares this cache when it does.
const query = useQuery({ ...promptTemplatesQueryOptions(), enabled: isEnabled });
- 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 classified = useMemo(() => classifyPromptTemplates(query.data ?? [], account), [account, query.data]);
const runAndInvalidate = useCallback(
- async <T>(run: () => Promise<T>): Promise<T> => {
+ async <T>(run: () => Promise<T>, imageId?: string): Promise<T> => {
const owner = captureAccountScope();
const result = await run();
assertAccountScopeCurrent(owner);
- await invalidatePromptTemplates(queryClient);
+ await invalidatePromptTemplates(queryClient, imageId);
return result;
},
[queryClient]
);
const create = useCallback(
- (draft: PromptTemplateDraft) => runAndInvalidate(() => createPromptTemplate(draft)),
- [runAndInvalidate]
+ async (draft: PromptTemplateCreateDraft) => {
+ const saved = await runAndInvalidate(() => createPromptTemplate(draft));
+ await invalidatePromptTemplates(queryClient, saved.id);
+ return saved;
+ },
+ [queryClient, runAndInvalidate]
);
const update = useCallback(
- (id: string, draft: PromptTemplateDraft) => runAndInvalidate(() => updatePromptTemplate(id, draft)),
- [runAndInvalidate]
+ (template: PromptTemplateRecord, draft: PromptTemplateUpdateDraft) => {
+ requireOwnedPromptTemplate(template, account);
+ return runAndInvalidate(() => updatePromptTemplate(template.id, draft), template.id);
+ },
+ [account, runAndInvalidate]
);
- const remove = useCallback((id: string) => runAndInvalidate(() => deletePromptTemplate(id)), [runAndInvalidate]);
+ const remove = useCallback(
+ (template: PromptTemplateRecord) => {
+ requireOwnedPromptTemplate(template, account);
+ return runAndInvalidate(() => deletePromptTemplate(template.id), template.id);
+ },
+ [account, runAndInvalidate]
+ );
const importFile = useCallback(
(file: File) => runAndInvalidate(() => importPromptTemplates(file)),
@@ -93,16 +104,16 @@ export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean }
return {
create,
- defaultTemplates,
+ defaultTemplates: classified.defaultTemplates,
exportCsv: exportPromptTemplates,
- fetchImage: fetchPromptTemplateImage,
importFile,
isLoaded: query.isSuccess,
isLoading: query.isPending,
remove,
- templates,
+ personalTemplates: classified.personalTemplates,
+ sharedTemplates: classified.sharedTemplates,
+ templates: classified.templates,
update,
- userTemplates,
};
};