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): gate the template catalog fetch, and say when one is gone
joshistoast5f0a08850665
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 3fe5094545..27723ec38b 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1026,6 +1026,8 @@"noTemplatesYet": "No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.","noMatches": "No matching templates","applied": "Template: {{name}}",+ "appliedMissing": "Template: {{name}} (deleted)",+ "appliedMissingHelp": "\u201c{{name}}\u201d was deleted. It still shapes your prompt until you stop using it.","clearApplied": "Stop using {{name}}","clear": "Clear","name": "Name",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.tsxindex 8b796069db..3a809e830c 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@@ -46,6 +46,8 @@ const translation = {noTemplatesYet: 'No templates yet. Create one to reuse a prompt with {prompt} where your own text goes.',noMatches: 'No matching templates',applied: 'Template: {{name}}',+ appliedMissing: 'Template: {{name}} (deleted)',+ appliedMissingHelp: '“{{name}}” was deleted. It still shapes your prompt until you stop using it.',clearApplied: 'Stop using {{name}}',clear: 'Clear',name: 'Name',@@ -124,6 +126,7 @@ const createCatalog = (overrides: Partial<PromptTemplateCatalog> = {}): PromptTeexportCsv: vi.fn(),fetchImage: vi.fn().mockResolvedValue(null),importFile: vi.fn(),+ isLoaded: true,isLoading: false,remove: vi.fn(),templates: [userTemplate, defaultTemplate],@@ -164,6 +167,7 @@ describe('the prompt templates panel', () => {await render(<PromptTemplatesPanelactiveTemplate={null}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={onApply}onCreate={vi.fn()}@@ -192,6 +196,7 @@ describe('the prompt templates panel', () => {await render(<PromptTemplatesPanelactiveTemplate={userTemplate}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={onApply}onCreate={vi.fn()}@@ -218,6 +223,7 @@ describe('the prompt templates panel', () => {await render(<PromptTemplatesPanelactiveTemplate={userTemplate}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={onApply}onCreate={vi.fn()}@@ -247,6 +253,7 @@ describe('the prompt templates panel', () => {await render(<PromptTemplatesPanelactiveTemplate={null}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={vi.fn()}onCreate={vi.fn()}@@ -265,6 +272,7 @@ describe('the prompt templates panel', () => {await render(<PromptTemplatesPanelactiveTemplate={null}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={vi.fn()}onCreate={vi.fn()}@@ -281,12 +289,50 @@ describe('the prompt templates panel', () => {expect(host!.textContent).not.toContain('Cinematic');});+ // The snapshot deliberately keeps applying after the template is gone, so a+ // queue item can still explain itself. Nothing said so, which left a prompt+ // being reshaped by something the list no longer contains.+ it('says when the applied template is no longer in the catalog', async () => {+ await render(+ <PromptTemplatesPanel+ activeTemplate={userTemplate}+ isActiveTemplateMissing+ catalog={createCatalog({ templates: [defaultTemplate], userTemplates: [] })}+ onApply={vi.fn()}+ onCreate={vi.fn()}+ onDetach={vi.fn()}+ onEdit={vi.fn()}+ />+ );++ expect(host!.textContent).toContain('was deleted');+ // And the way out is still offered beside it.+ expect(buttonWithText('Stop using Cinematic')).toBeTruthy();+ });++ it('says nothing of the sort while the template is still there', async () => {+ await render(+ <PromptTemplatesPanel+ activeTemplate={userTemplate}+ isActiveTemplateMissing={false}+ catalog={createCatalog()}+ onApply={vi.fn()}+ onCreate={vi.fn()}+ onDetach={vi.fn()}+ onEdit={vi.fn()}+ />+ );++ 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 () => {await render(<PromptTemplatesPanelactiveTemplate={null}+ isActiveTemplateMissing={false}catalog={createCatalog()}onApply={vi.fn()}onCreate={vi.fn()}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.tsxnew file mode 100644index 0000000000..0b87d4985b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx@@ -0,0 +1,166 @@+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';+import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';++import { ChakraProvider } from '@chakra-ui/react';+import { PromptTemplatesButton } from '@features/generation/ui/promptFields/PromptTemplatesButton';+import { system } from '@theme/system';+import i18next from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++const catalog: PromptTemplateCatalog = {+ create: vi.fn(),+ defaultTemplates: [],+ exportCsv: vi.fn(),+ fetchImage: vi.fn().mockResolvedValue(null),+ importFile: vi.fn(),+ isLoaded: true,+ isLoading: false,+ remove: vi.fn(),+ templates: [],+ update: vi.fn(),+ userTemplates: [],+};++const usePromptTemplates = vi.fn((_options?: { isEnabled?: boolean }) => catalog);++// The real hook is a react-query observer; what matters here is the argument it+// is handed, which decides whether the request goes out at all.+vi.mock('@features/generation/ui/usePromptTemplates', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ usePromptTemplates: (options?: { isEnabled?: boolean }) => usePromptTemplates(options),+}));++vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useGenerationUi: () => ({+ capabilities: { canManagePromptTemplates: false },+ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() },+ }),+}));++const translation = {+ common: { cancel: 'Cancel', delete: 'Delete', edit: 'Edit', save: 'Save' },+ widgets: {+ generate: {+ promptTemplates: {+ applied: 'Template: {{name}}',+ appliedMissing: 'Template: {{name}} (deleted)',+ appliedMissingHelp: '“{{name}}” was deleted. It still shapes your prompt until you stop using it.',+ clearApplied: 'Stop using {{name}}',+ defaultTemplates: 'Built-in templates',+ newTemplate: 'New template',+ noTemplatesYet: 'No templates yet.',+ search: 'Search templates',+ title: 'Prompt templates',+ yourTemplates: 'Your templates',+ },+ },+ },+};++const i18n = i18next.createInstance();++await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation } } });++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 applied: PromptTemplateSnapshot = {+ id: 'user-1',+ name: 'Cinematic',+ negativePrompt: '',+ positivePrompt: '{prompt}, cinematic',+};++const render = async (activeTemplate: PromptTemplateSnapshot | null) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <PromptTemplatesButton activeTemplate={activeTemplate} showSyntaxHighlighting={false} onApply={vi.fn()} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};++/** What the hook was handed on the most recent render. */+const lastIsEnabled = (): boolean | undefined => usePromptTemplates.mock.calls.at(-1)?.[0]?.isEnabled;++beforeEach(() => usePromptTemplates.mockClear());++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('the prompt templates button', () => {+ // react-query enables a query if any one observer wants it, and this observer+ // always did — so the widget's own gating did nothing at all while this button+ // was mounted, which is always.+ it('does not ask for the catalog with nothing applied and the list closed', async () => {+ await render(null);++ expect(lastIsEnabled()).toBe(false);+ });++ it('asks for it once the list is opened', async () => {+ await render(null);++ await act(async () => {+ await userEvent.click(host!.querySelector('button')!);+ });++ expect(lastIsEnabled()).toBe(true);+ });++ // An applied template has to be re-read whether the list is open or not: to+ // refresh its text after an edit, and to notice it has been deleted.+ it('asks for it whenever a template is applied', async () => {+ await render(applied);++ expect(lastIsEnabled()).toBe(true);+ });++ it('dims the name and says so when the applied template is gone', async () => {+ await render(applied);++ const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');++ expect(name).toBeTruthy();+ expect(getComputedStyle(name!).opacity).toBe('0.5');+ });++ it('leaves the name alone while the template is still there', async () => {+ usePromptTemplates.mockReturnValue({ ...catalog, templates: [{ ...applied, imageUrl: null, isDefault: false }] });+ await render(applied);++ const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');++ expect(getComputedStyle(name!).opacity).toBe('1');+ usePromptTemplates.mockReturnValue(catalog);+ });++ // A catalog that has not been read cannot say anything is missing — an+ // unfinished or failed fetch must not read as a deletion.+ it('says nothing while the catalog is unread', async () => {+ usePromptTemplates.mockReturnValue({ ...catalog, isLoaded: false });+ await render(applied);++ const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');++ expect(getComputedStyle(name!).opacity).toBe('1');+ usePromptTemplates.mockReturnValue(catalog);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsxindex 797416acb8..46a1b5dd02 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx@@ -7,7 +7,7 @@ import { toPromptTemplateSnapshot } from '@features/generation/data/promptTemplaimport { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';import { useOnPendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';-import { usePromptTemplates } from '@features/generation/ui/usePromptTemplates';+import { isPromptTemplateMissing, usePromptTemplates } from '@features/generation/ui/usePromptTemplates';import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';import { LayoutTemplateIcon } from 'lucide-react';@@ -37,7 +37,12 @@ export const PromptTemplatesButton = ({const triggerId = useId();const [isOpen, setIsOpen] = useState(false);const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);- const catalog = usePromptTemplates();+ // The list is behind the popover, so a closed button has nothing to show —+ // but an applied template still has to be re-read, both to refresh its text+ // and to notice it has been deleted. Without this the widget's own gating did+ // nothing: react-query enables a query if any one observer wants it, and this+ // observer always did.+ const catalog = usePromptTemplates({ isEnabled: isOpen || activeTemplate !== null });const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);// A draft handed over from the gallery opens the editor straight away.useOnPendingPromptTemplateDraft(@@ -87,8 +92,13 @@ export const PromptTemplatesButton = ({[activeTemplate?.id, onApply]);+ // Deleted in another tab, or by another session of this one. It keeps+ // applying — that policy is deliberate — so the only thing wrong is that+ // nothing said so.+ const isMissing = isPromptTemplateMissing(catalog, activeTemplate);+const tooltip = activeTemplate- ? t('widgets.generate.promptTemplates.applied', { name: activeTemplate.name })+ ? t(`widgets.generate.promptTemplates.${isMissing ? 'appliedMissing' : 'applied'}`, { name: activeTemplate.name }): t('widgets.generate.promptTemplates.title');return (@@ -114,7 +124,9 @@ export const PromptTemplatesButton = ({><LayoutTemplateIcon />{activeTemplate ? (- <Text as="span" fontSize="2xs" maxW="6rem" truncate>+ // Dimmed when it is gone, the same way the icon dims when nothing+ // is applied — one vocabulary for "not fully live", no new colour.+ <Text as="span" fontSize="2xs" maxW="6rem" opacity={isMissing ? 0.5 : undefined} truncate>{activeTemplate.name}</Text>) : null}@@ -143,6 +155,7 @@ export const PromptTemplatesButton = ({) : (<PromptTemplatesPanelactiveTemplate={activeTemplate}+ isActiveTemplateMissing={isMissing}catalog={catalog}onApply={applyAndClose}onDetach={detachTemplate}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsxindex 65ed5775bb..d691bbc4df 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx@@ -24,6 +24,8 @@ const THUMBNAIL_SIZE = '7';interface PromptTemplatesPanelProps {catalog: PromptTemplateCatalog;activeTemplate: PromptTemplateSnapshot | null;+ /** The applied template is no longer in the catalog — deleted elsewhere. */+ isActiveTemplateMissing: boolean;onApply: (template: PromptTemplateSnapshot | null) => void;/*** Stop applying the active template without dismissing the panel — for when it@@ -43,6 +45,7 @@ const getTemplateProse = (template: PromptTemplateRecord): readonly string[] =>export const PromptTemplatesPanel = ({activeTemplate,catalog,+ isActiveTemplateMissing,onApply,onDetach,onCreate,@@ -158,6 +161,14 @@ export const PromptTemplatesPanel = ({</Button>) : null}</HStack>+ {/* The list above cannot explain an absence, so this says it in+ words: the template is gone but still shaping the prompt, and the+ button beside it is how to stop that. */}+ {activeTemplate && isActiveTemplateMissing ? (+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.generate.promptTemplates.appliedMissingHelp', { name: activeTemplate.name })}+ </Text>+ ) : null}</>) : null}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.tsindex 6ed8063dbb..c66c8557eb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts@@ -1,3 +1,4 @@+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';import type { PromptTemplateDraft, PromptTemplateRecord } from '@features/generation/data/promptTemplates';import {@@ -22,6 +23,13 @@ export interface PromptTemplateCatalog {/** Every visible template, for resolving a stored snapshot. */templates: PromptTemplateRecord[];isLoading: boolean;+ /**+ * The catalog has been read at least once, successfully. Distinct from+ * `!isLoading`, which is also true of a fetch that failed and of one that+ * never ran — telling a deleted template apart from an unread catalog needs+ * the difference.+ */+ 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>;@@ -89,6 +97,7 @@ export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean }exportCsv: exportPromptTemplates,fetchImage: fetchPromptTemplateImage,importFile,+ isLoaded: query.isSuccess,isLoading: query.isPending,remove,templates,@@ -96,3 +105,16 @@ export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean }userTemplates,};};++/**+ * Whether the applied template has been deleted out from under this tab.+ *+ * The snapshot keeps applying either way — a queue item has to explain itself+ * after its template is gone, and a catalog that is empty because it is still+ * loading or because the fetch failed must not silently change what generates.+ * That policy is right and stays; this is only what makes it visible.+ */+export const isPromptTemplateMissing = (+ catalog: PromptTemplateCatalog,+ active: PromptTemplateSnapshot | null+): boolean => active !== null && catalog.isLoaded && !catalog.templates.some((template) => template.id === active.id);