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): stop Invoke when a prompt cannot be expanded
joshistoast617d0d77d613
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex 3135c7e419..dd3d77f6a9 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -447,25 +447,54 @@ describe('submitResolvedInvocation', () => {expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ positivePrompts: undefined });});- it('falls back to the literal prompt when expansion fails', async () => {- parseDynamicPromptsMock.mockRejectedValueOnce(new Error('offline'));+ // Submitting the authored text on a failed expansion would put the literal+ // `{a|b}` or `__name__` in front of the model, so neither failure generates.+ describe('when a prompt cannot be expanded', () => {+ const submitDynamicPrompt = () => {+ const project = getActiveProject(createGenerateValues(animaModel, { positivePrompt: 'a {red|green} cat' }));+ const store = createWorkbenchStore();+ const submitResolved = vi.spyOn(store.commands.generation, 'submitResolved');+ const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });++ submitResolvedInvocation({+ commands: store.commands,+ models: undefined,+ owner: captureAccountScope(),+ prepareCanvasInvocation: vi.fn(),+ project,+ route,+ });++ return { store, submitResolved };+ };- const project = getActiveProject(createGenerateValues(animaModel, { positivePrompt: 'a {red|green} cat' }));- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });+ it('does not dispatch when the request fails outright', async () => {+ parseDynamicPromptsMock.mockRejectedValueOnce(new Error('offline'));- submitResolvedInvocation({- commands,- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation: vi.fn(),- project,- route,+ const { store, submitResolved } = submitDynamicPrompt();++ await vi.waitFor(() => expect(store.getSnapshot().notifications).toHaveLength(1));+ expect(submitResolved).not.toHaveBeenCalled();+ expect(store.getSnapshot().notifications[0]).toMatchObject({+ kind: 'error',+ title: 'The prompt could not be expanded',+ });});- await vi.waitFor(() => expect(submitResolved).toHaveBeenCalledTimes(1));- expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ positivePrompts: undefined });+ it('does not dispatch when the backend reports an unresolvable wildcard', async () => {+ // The route is deliberately soft: it answers 200 with the literal prompt+ // alongside the message, so only `error` distinguishes this from success.+ parseDynamicPromptsMock.mockResolvedValueOnce({+ error: 'No values found for wildcard(s): nope',+ prompts: ['a {red|green} cat'],+ });++ const { store, submitResolved } = submitDynamicPrompt();++ await vi.waitFor(() => expect(store.getSnapshot().notifications).toHaveLength(1));+ expect(submitResolved).not.toHaveBeenCalled();+ expect(store.getSnapshot().notifications[0]?.message).toBe('No values found for wildcard(s): nope');+ });});it('quietly ignores a submission owned by an expired account scope', () => {diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex cc2018b1a4..d3f9d2c315 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -14,6 +14,7 @@*/import type { GenerateSettings } from '@features/generation/contracts';+import type { ParseDynamicPromptsResponse } from '@features/generation/prompts';import type { ModelConfig } from '@features/models';import type { AccountScope } from '@platform/state/accountLifecycle';import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';@@ -31,6 +32,9 @@ import { readCanvasCompositingSettings } from './widgets/canvas/invoke/canvasComimport { readCanvasDenoisingStrength } from './widgets/canvas/invoke/canvasStrength';import { getProjectWidgetValues } from './widgetState';+/** Plain English, like the shell's other notices — this module has no i18n context. */+const EXPANSION_FAILED_TITLE = 'The prompt could not be expanded';+export interface SubmitResolvedInvocationDeps {/** The resolved route to submit — the caller has already checked it is valid. */route: ResolvedInvocationRoute;@@ -69,21 +73,22 @@ const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute)* Resolving the expansion here rather than inside Queue keeps Queue free of a* Generation import, which would close a `gallery -> queue -> generation`* dependency cycle. Reading the shared cache means invoking mid-edit still- * submits the prompts the backend actually produces. A failed expansion falls- * back to the literal prompt so an Invoke is never silently swallowed.+ * submits the prompts the backend actually produces.+ *+ * `null` means the request itself failed. A response may still carry an `error`+ * alongside a usable-looking `prompts` — the route is deliberately soft so the+ * preview can show the message, but the submit path must not act on it.*/-const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<string[] | undefined> => {+const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<ParseDynamicPromptsResponse | null> => {try {- const { prompts } = await resolveDynamicPrompts(queryClient, {+ return await resolveDynamicPrompts(queryClient, {combinatorial: settings.dynamicPromptsCombinatorial,max_prompts: settings.dynamicPromptsMaxPrompts,prompt: settings.positivePrompt,seed: settings.dynamicPromptsCombinatorial ? null : settings.dynamicPromptsSampleSeed,});-- return prompts.length > 0 ? prompts : undefined;} catch {- return undefined;+ return null;}};@@ -105,13 +110,28 @@ export const submitResolvedInvocation = ({// Only a prompt with dynamic syntax pays for a round trip; every other Invoke// stays on the synchronous path it has always taken.if (expandableSettings) {- void resolveExpandedPrompts(expandableSettings).then((positivePrompts) => {- if (isAccountScopeCurrent(owner)) {- dispatchResolvedInvocation(- { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },- positivePrompts- );+ void resolveExpandedPrompts(expandableSettings).then((expansion) => {+ if (!isAccountScopeCurrent(owner)) {+ return;}++ // Submitting the authored text would put the literal `{a|b}` or `__name__`+ // in front of the model, so a prompt that could not be expanded does not+ // generate at all. The Invoke button gates on the same state; this covers+ // the hotkey and graph-preview paths, which never see it.+ if (expansion === null || expansion.error) {+ commands.notifications.add({+ kind: 'error',+ message: expansion?.error ?? undefined,+ title: EXPANSION_FAILED_TITLE,+ });+ return;+ }++ dispatchResolvedInvocation(+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },+ expansion.prompts.length > 0 ? expansion.prompts : undefined+ );});return;}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 3cbe0401dc..1284c6bcec 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -150,15 +150,21 @@ export const InvokeControl = () => {? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues)): null);+ // A prompt that will not expand cannot be submitted — the alternative is putting+ // the literal `{a|b}` in front of the model — so this blocks rather than just+ // annotating. `submitResolvedInvocation` enforces the same rule for the hotkey.+ const expansionReason = promptExpansion.isError+ ? 'The prompt could not be expanded.'+ : (promptExpansion.error ?? null);const blockingReasons = useMemo(() => [...(isConnected ? [] : ['The backend is disconnected.']),- ...(promptExpansion.isError ? ['The prompt could not be expanded.'] : []),+ ...(expansionReason === null ? [] : [expansionReason]),...resolvedRoute.validationReasons,],- [isConnected, promptExpansion.isError, resolvedRoute.validationReasons]+ [expansionReason, isConnected, resolvedRoute.validationReasons]);- const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;+ const isValid = isInvocationRouteValid(resolvedRoute) && isConnected && expansionReason === null;const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));useMountEffect(() => {void ensureModelsLoaded();