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(canvas): speed up invocation startup

Josh Corbetteb804b6d1061
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index ee0c6d1790..4f974cd277 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -323,6 +323,7 @@
"expandingPrompts": "Expanding prompts…",
"invoke": "Invoke",
"noNodes": "No nodes in graph",
+ "preparing": "Preparing canvas generation…",
"unavailable": "Invoke unavailable: {{reason}}",
"unrunnable": "route is not runnable",
"unableToQueue": "Unable to queue"
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 20ab0504b0..d8db6c77b9 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -88,6 +88,7 @@
"autoRoutePolicy.ts": "workbench",
"bootWidgetPreload.ts": "workbench",
"canvasDimsSync.ts": "workbench",
+ "canvasInvocationPreparation.ts": "workbench",
"canvasLayerContent.ts": "workbench",
"canvasLayerOps.ts": "workbench",
"canvasMigration.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
index 712d121cf0..dafa826db9 100644
--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
@@ -1,17 +1,18 @@
+import type { MainModelConfig } from '@features/generation/contracts';
import type { AccountScope } from '@platform/state/accountLifecycle';
+import { getDefaultGenerateSettings } from '@features/generation/settings';
import { describe, expect, it } from 'vitest';
import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';
import { submitActiveInvocation, type ActiveInvocationSubmissionRuntime } from './activeInvocationSubmission';
-import { createInitialWorkbenchState } from './workbenchState.testing';
+import { isCanvasInvocationPreparing } from './canvasInvocationPreparation';
+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
const owner = { signal: new AbortController().signal } as AccountScope;
-const createArgs = () => {
- const state = createInitialWorkbenchState();
-
+const createArgs = (state = createInitialWorkbenchState()) => {
return {
commands: {} as WorkbenchCommands,
getModels: () => undefined,
@@ -29,7 +30,62 @@ const createArgs = () => {
};
};
+const createCanvasState = () => {
+ const model: MainModelConfig = { base: 'sd-1', key: 'main', name: 'Main', type: 'main' };
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ state = workbenchReducer(state, {
+ type: 'setGenerateSettings',
+ values: { ...getDefaultGenerateSettings(model), model, modelKey: model.key },
+ });
+
+ return { ...state, backendConnection: { status: 'connected' as const } };
+};
+
describe('active invocation submission', () => {
+ it('single-flights a canvas submission before its lazy module loads and until preparation settles', async () => {
+ let resolveModule = (_value: { prepareCanvasInvocation: () => Promise<void> }): void => undefined;
+ const modulePromise = new Promise<{ prepareCanvasInvocation: () => Promise<void> }>((resolve) => {
+ resolveModule = resolve;
+ });
+ let resolvePreparation = (): void => undefined;
+ const preparationPromise = new Promise<void>((resolve) => {
+ resolvePreparation = resolve;
+ });
+ const events: string[] = [];
+ const runtime: ActiveInvocationSubmissionRuntime = {
+ assertCurrent: () => undefined,
+ capture: () => owner,
+ flushDrafts: () => events.push('flushed'),
+ isCurrent: () => true,
+ loadPrepareCanvasInvocation: () => {
+ events.push('loaded');
+ return modulePromise;
+ },
+ submit: () => {
+ events.push('submitted');
+ return preparationPromise;
+ },
+ };
+
+ const state = createCanvasState();
+ const projectId = state.activeProjectId;
+ const first = submitActiveInvocation(createArgs(state), runtime);
+ const second = submitActiveInvocation(createArgs(state), runtime);
+
+ expect(events).toEqual(['flushed', 'loaded', 'flushed']);
+ expect(isCanvasInvocationPreparing(projectId)).toBe(true);
+
+ resolveModule({ prepareCanvasInvocation: () => preparationPromise });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(events).toEqual(['flushed', 'loaded', 'flushed', 'submitted']);
+
+ resolvePreparation();
+ await Promise.all([first, second]);
+ expect(isCanvasInvocationPreparing(projectId)).toBe(false);
+ });
+
it('swallows an asynchronous failure after the initiating account becomes stale', async () => {
const events: string[] = [];
const runtime: ActiveInvocationSubmissionRuntime = {
@@ -38,10 +94,12 @@ describe('active invocation submission', () => {
flushDrafts: () => events.push('flushed'),
isCurrent: () => false,
loadPrepareCanvasInvocation: () => Promise.reject(new Error('stale failure')),
- submit: () => events.push('submitted'),
+ submit: () => {
+ events.push('submitted');
+ },
};
- await expect(submitActiveInvocation(createArgs(), runtime)).resolves.toBeUndefined();
+ await expect(submitActiveInvocation(createArgs(createCanvasState()), runtime)).resolves.toBeUndefined();
expect(events).toEqual(['flushed']);
});
@@ -55,6 +113,6 @@ describe('active invocation submission', () => {
submit: () => undefined,
};
- await expect(submitActiveInvocation(createArgs(), runtime)).rejects.toThrow('current failure');
+ await expect(submitActiveInvocation(createArgs(createCanvasState()), runtime)).rejects.toThrow('current failure');
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
index 5b20902536..a44e17e049 100644
--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
@@ -13,6 +13,8 @@ import type { SubmitResolvedInvocationDeps } from './invocationSubmit';
import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';
import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';
+import { beginCanvasInvocationPreparation, endCanvasInvocationPreparation } from './canvasInvocationPreparation';
+import { createDeferredResource } from './deferredResource';
import { isInvocationRouteValid, resolveInvocationRoute } from './invocation';
import { submitResolvedInvocation } from './invocationSubmit';
@@ -32,15 +34,29 @@ export interface ActiveInvocationSubmissionRuntime {
loadPrepareCanvasInvocation: () => Promise<{
prepareCanvasInvocation: SubmitResolvedInvocationDeps['prepareCanvasInvocation'];
}>;
- submit: (args: SubmitResolvedInvocationDeps) => void;
+ submit: (args: SubmitResolvedInvocationDeps) => Promise<void> | void;
}
+type CanvasInvocationModule = {
+ prepareCanvasInvocation: SubmitResolvedInvocationDeps['prepareCanvasInvocation'];
+};
+
+const canvasInvocationModule = createDeferredResource<CanvasInvocationModule>(
+ () => import('./widgets/canvas/invoke/prepareCanvasInvocation')
+);
+
+const loadCanvasInvocationModule = (): Promise<CanvasInvocationModule> =>
+ canvasInvocationModule.getStatus() === 'failed' ? canvasInvocationModule.retry() : canvasInvocationModule.load();
+
+/** Warms the canvas-only invocation chunk without adding it to the eager workbench bundle. */
+export const preloadCanvasInvocation = (): void => canvasInvocationModule.preload();
+
const runtime: ActiveInvocationSubmissionRuntime = {
assertCurrent: assertAccountScopeCurrent,
capture: captureAccountScope,
flushDrafts: flushGenerateDrafts,
isCurrent: isAccountScopeCurrent,
- loadPrepareCanvasInvocation: () => import('./widgets/canvas/invoke/prepareCanvasInvocation'),
+ loadPrepareCanvasInvocation: loadCanvasInvocationModule,
submit: submitResolvedInvocation,
};
@@ -50,23 +66,32 @@ export const submitActiveInvocation = async (
): Promise<void> => {
const owner = activeRuntime.capture();
activeRuntime.flushDrafts();
+ const snapshot = queries.getSnapshot();
+ const invocation = destinationOverride
+ ? { ...snapshot.activeProject.invocation, destination: destinationOverride }
+ : snapshot.activeProject.invocation;
+ const models = getModels();
+ const route = resolveInvocationRoute(snapshot.activeProject, 'global', invocation, models);
+
+ if (!isInvocationRouteValid(route) || snapshot.backendConnection.status !== 'connected') {
+ return;
+ }
+
+ const projectId = snapshot.activeProject.id;
+ const isCanvasSubmission = route.sourceId === 'canvas';
+ const preparationLease = isCanvasSubmission ? beginCanvasInvocationPreparation(projectId) : null;
+
+ if (isCanvasSubmission && !preparationLease) {
+ return;
+ }
try {
- const { prepareCanvasInvocation } = await activeRuntime.loadPrepareCanvasInvocation();
+ const prepareCanvasInvocation = isCanvasSubmission
+ ? (await activeRuntime.loadPrepareCanvasInvocation()).prepareCanvasInvocation
+ : () => Promise.resolve();
activeRuntime.assertCurrent(owner);
- const snapshot = queries.getSnapshot();
- const invocation = destinationOverride
- ? { ...snapshot.activeProject.invocation, destination: destinationOverride }
- : snapshot.activeProject.invocation;
- const models = getModels();
- const route = resolveInvocationRoute(snapshot.activeProject, 'global', invocation, models);
-
- if (!isInvocationRouteValid(route) || snapshot.backendConnection.status !== 'connected') {
- return;
- }
-
- activeRuntime.submit({
+ await activeRuntime.submit({
commands,
formatControlLayerError,
models,
@@ -81,5 +106,9 @@ export const submitActiveInvocation = async (
}
throw error;
+ } finally {
+ if (preparationLease) {
+ endCanvasInvocationPreparation(preparationLease);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.test.ts b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.test.ts
new file mode 100644
index 0000000000..c2fbf4f483
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.test.ts
@@ -0,0 +1,26 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { describe, expect, it } from 'vitest';
+
+import {
+ beginCanvasInvocationPreparation,
+ endCanvasInvocationPreparation,
+ isCanvasInvocationPreparing,
+} from './canvasInvocationPreparation';
+
+describe('canvas invocation preparation', () => {
+ it('does not let a stale account lease release a new preparation with the same project id', () => {
+ const projectId = 'shared-project';
+ const staleLease = beginCanvasInvocationPreparation(projectId);
+ expect(staleLease).not.toBeNull();
+
+ accountLifecycle.invalidate();
+ const currentLease = beginCanvasInvocationPreparation(projectId);
+ expect(currentLease).not.toBeNull();
+
+ endCanvasInvocationPreparation(staleLease!);
+ expect(isCanvasInvocationPreparing(projectId)).toBe(true);
+
+ endCanvasInvocationPreparation(currentLease!);
+ expect(isCanvasInvocationPreparing(projectId)).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts
new file mode 100644
index 0000000000..72c9ca0224
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts
@@ -0,0 +1,60 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStoreCore } from '@platform/state/externalStoreCore';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+
+interface CanvasInvocationPreparationSnapshot {
+ leases: ReadonlyMap<string, number>;
+}
+
+export interface CanvasInvocationPreparationLease {
+ projectId: string;
+ token: number;
+}
+
+const EMPTY_LEASES: ReadonlyMap<string, number> = new Map();
+const store = createExternalStoreCore<CanvasInvocationPreparationSnapshot>({ leases: EMPTY_LEASES });
+let nextLeaseToken = 1;
+
+/**
+ * Acquires the user-facing canvas preparation slot before any asynchronous
+ * module loading, prompt expansion, persistence, compositing, or upload begins.
+ * The deeper canvas orchestrator keeps its own guard for non-active entry
+ * points; this one owns the Ctrl+Enter/topbar acknowledgement window.
+ */
+export const beginCanvasInvocationPreparation = (projectId: string): CanvasInvocationPreparationLease | null => {
+ const { leases } = store.getSnapshot();
+
+ if (leases.has(projectId)) {
+ return null;
+ }
+
+ const lease = { projectId, token: nextLeaseToken };
+ nextLeaseToken += 1;
+ store.setSnapshot({ leases: new Map([...leases, [projectId, lease.token]]) });
+ return lease;
+};
+
+export const endCanvasInvocationPreparation = (lease: CanvasInvocationPreparationLease): void => {
+ const { leases } = store.getSnapshot();
+
+ // Account invalidation clears every lease synchronously. If an old async
+ // submission settles after a new account/project acquired the same id, its
+ // stale token must not release the new owner's acknowledgement.
+ if (leases.get(lease.projectId) !== lease.token) {
+ return;
+ }
+
+ const nextLeases = new Map(leases);
+ nextLeases.delete(lease.projectId);
+ store.setSnapshot({ leases: nextLeases.size > 0 ? nextLeases : EMPTY_LEASES });
+};
+
+export const isCanvasInvocationPreparing = (projectId: string): boolean => store.getSnapshot().leases.has(projectId);
+
+export const useIsCanvasInvocationPreparing = (projectId: string): boolean =>
+ useExternalStoreSelector(store.subscribe, store.getSnapshot, (snapshot) => snapshot.leases.has(projectId));
+
+registerAccountOwnedResource({
+ clear: () => store.setSnapshot({ leases: EMPTY_LEASES }),
+ name: 'canvas-invocation-preparation',
+});
diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
index 9941881fc9..ab4ac6e470 100644
--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
@@ -44,6 +44,6 @@ export const resolveAndSubmitGraphPreviewInvocation = ({
return false;
}
- submitResolvedInvocation({ commands, models, owner, prepareCanvasInvocation: prepareCanvas, project, route });
+ void submitResolvedInvocation({ commands, models, owner, prepareCanvasInvocation: prepareCanvas, project, route });
return true;
};
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index f0aa21431a..d145fc4c19 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -389,6 +389,39 @@ describe('submitResolvedInvocation', () => {
});
});
+ it('settles only after canvas preparation finishes so the active invoke guard stays held', async () => {
+ const project = getActiveProject(
+ createGenerateValues(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: animaVae })
+ );
+ const commands = createWorkbenchStore().commands;
+ let releasePreparation = (): void => undefined;
+ const preparation = new Promise<void>((resolve) => {
+ releasePreparation = resolve;
+ });
+ const prepareCanvasInvocation = vi.fn(() => preparation);
+ const route = routeFor(project, { ...project.invocation, destination: 'canvas', sourceId: 'canvas' });
+ let settled = false;
+
+ const submission = submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation,
+ project,
+ route,
+ }).then(() => {
+ settled = true;
+ });
+
+ expect(prepareCanvasInvocation).toHaveBeenCalledTimes(1);
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ releasePreparation();
+ await submission;
+ expect(settled).toBe(true);
+ });
+
it('dispatches submitResolvedInvocationSnapshot for a non-canvas source and never prepares the canvas', () => {
const project = getActiveProject(
createGenerateValues(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: animaVae })
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 0909319fa3..df540234b1 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -47,10 +47,11 @@ export interface SubmitResolvedInvocationDeps {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
/**
* The async canvas-invoke entry point, injected for testability. The real
- * implementation is fire-and-track (its returned promise is intentionally not
- * awaited); a canvas source never dispatches `submitResolvedInvocationSnapshot`.
+ * implementation resolves after preparation has either queued the graph or
+ * reported a failure; a canvas source never dispatches
+ * `submitResolvedInvocationSnapshot`.
*/
- prepareCanvasInvocation: (args: PrepareCanvasInvocationArgs) => unknown;
+ prepareCanvasInvocation: (args: PrepareCanvasInvocationArgs) => Promise<void> | void;
/** Localizes a control-layer rejection notice; defaults to the English validation sentence. */
formatControlLayerError?: PrepareCanvasInvocationArgs['formatControlLayerError'];
}
@@ -104,7 +105,7 @@ const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<Parse
}
};
-export const submitResolvedInvocation = ({
+export const submitResolvedInvocation = async ({
commands,
formatControlLayerError,
models,
@@ -112,7 +113,7 @@ export const submitResolvedInvocation = ({
prepareCanvasInvocation,
project,
route,
-}: SubmitResolvedInvocationDeps): void => {
+}: SubmitResolvedInvocationDeps): Promise<void> => {
if (!isAccountScopeCurrent(owner)) {
return;
}
@@ -122,39 +123,38 @@ 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((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
- );
- });
+ const expansion = await resolveExpandedPrompts(expandableSettings);
+ 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;
+ }
+
+ await dispatchResolvedInvocation(
+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
+ expansion.prompts.length > 0 ? expansion.prompts : undefined
+ );
return;
}
- dispatchResolvedInvocation(
+ await dispatchResolvedInvocation(
{ commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
undefined
);
};
-const dispatchResolvedInvocation = (
+const dispatchResolvedInvocation = async (
{
commands,
formatControlLayerError,
@@ -165,14 +165,15 @@ const dispatchResolvedInvocation = (
route,
}: SubmitResolvedInvocationDeps,
positivePrompts: string[] | undefined
-): void => {
+): Promise<void> => {
if (route.sourceId === 'canvas') {
// The canvas graph is composited + compiled asynchronously outside the
- // reducer; fire-and-track (the orchestrator records any failure notice and
- // guards against concurrent invokes internally). The resolved destination is
- // threaded through so a Canvas source can still land its output in the
- // Gallery (durable, non-intermediate) instead of canvas staging.
- prepareCanvasInvocation({
+ // reducer. Awaiting it lets the active submission coordinator hold its
+ // immediate acknowledgement/duplicate guard through the whole preparation.
+ // The orchestrator records any failure notice and keeps its own guard for
+ // direct/preview callers. The resolved destination is threaded through so a
+ // Canvas source can still land its output in the Gallery.
+ await prepareCanvasInvocation({
compositing: readCanvasCompositingSettings(getProjectWidgetValues(project, 'canvas')),
destination: route.destination,
commands,
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx
index 0a18391eda..a4ecefe54b 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx
@@ -7,6 +7,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
+import type { InvocationState } from './useInvocationState';
import type * as UseTopbarShortcutModule from './useTopbarShortcut';
// Isolates the regression this file exists to catch: the icon slot must swap
@@ -44,24 +45,26 @@ 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 makeInvocationState = () => ({
+const makeInvocationState = (overrides: Partial<InvocationState> = {}): InvocationState => ({
batchCount: 1,
blockingReasons: [],
invocation,
invoke: vi.fn(() => Promise.resolve()),
+ isPreparing: false,
isValid: true,
placedTypeIds: new Set<never>(),
promptExpansion: { count: 1, error: null, isDynamic: false, isError: false, isLoading: false, prompts: [] },
sourceValues: {},
sources: [],
visibleTypeIds: new Set<never>(),
+ ...overrides,
});
-const renderInvokeButton = async () => {
+const renderInvokeButton = async (overrides: Partial<InvocationState> = {}) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
- const state = makeInvocationState();
+ const state = makeInvocationState(overrides);
await act(() =>
root?.render(
@@ -71,7 +74,7 @@ const renderInvokeButton = async () => {
)
);
- return host.querySelector('button') as HTMLButtonElement;
+ return { button: host.querySelector('button') as HTMLButtonElement, state };
};
const hasProgressRing = (button: HTMLButtonElement): boolean => button.querySelector('[role="progressbar"]') !== null;
@@ -91,13 +94,13 @@ afterEach(async () => {
describe('InvokeButton icon slot', () => {
it('shows the progress ring while a batch runs and nothing is hovered or keyboard-focused', async () => {
- const button = await renderInvokeButton();
+ const { button } = await renderInvokeButton();
expect(hasProgressRing(button)).toBe(true);
});
it('does not treat a mouse-click focus as keyboard focus: the ring returns once the pointer leaves', async () => {
- const button = await renderInvokeButton();
+ const { button } = await renderInvokeButton();
await act(() => userEvent.click(button));
// A plain click focuses the button (mousedown does that natively) but must
@@ -112,7 +115,7 @@ describe('InvokeButton icon slot', () => {
});
it('suppresses the ring for real keyboard focus (:focus-visible) the same as hover', async () => {
- const button = await renderInvokeButton();
+ const { button } = await renderInvokeButton();
await act(() => userEvent.tab());
@@ -120,4 +123,18 @@ describe('InvokeButton icon slot', () => {
expect(button.matches(':focus-visible')).toBe(true);
expect(hasProgressRing(button)).toBe(false);
});
+
+ it('acknowledges canvas preparation immediately and ignores a second click', async () => {
+ harness.summary.total = 0;
+ const invoke = vi.fn(() => Promise.resolve());
+ const { button } = await renderInvokeButton({ invoke, isPreparing: true });
+
+ expect(button.getAttribute('aria-disabled')).toBe('true');
+ expect(button.getAttribute('aria-label')).toBe('topbar.invoke.preparing');
+ expect(hasProgressRing(button)).toBe(true);
+
+ await act(() => button.click());
+
+ expect(invoke).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
index d128dac905..58b2eeeff2 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
@@ -51,7 +51,7 @@ const plural = (count: number, noun: string): string => `${count} ${noun}${count
*/
export const InvokeButton = ({ state }: { state: InvocationState }) => {
const { t } = useTranslation();
- const { blockingReasons, invoke, isValid } = state;
+ const { blockingReasons, invoke, isPreparing, isValid } = state;
const shortcutBinding = useTopbarShortcutBinding('app.invoke');
const shortcutParts = shortcutBinding?.parts ?? null;
const tooltipContent = useMemo(
@@ -76,32 +76,37 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {
}, []);
const handleBlur = useCallback(() => setIsFocused(false), []);
const handleClick = useCallback(() => void invoke(), [invoke]);
+ const canInvoke = isValid && !isPreparing;
- const iconMode = getInvokeIconMode({
- hasOpenWork,
- isHovered: isHovered || isFocused,
- progress: getDeterminateProgressFraction(runningProgress?.percentage),
- });
+ const iconMode = isPreparing
+ ? ({ mode: 'progress', value: null } as const)
+ : getInvokeIconMode({
+ hasOpenWork,
+ isHovered: isHovered || isFocused,
+ progress: getDeterminateProgressFraction(runningProgress?.percentage),
+ });
return (
<Tooltip content={tooltipContent} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow>
<Button
- aria-disabled={!isValid}
+ aria-disabled={!canInvoke}
aria-keyshortcuts={shortcutBinding?.aria}
aria-label={
- isValid
+ canInvoke
? t('topbar.invoke.invoke')
- : t('topbar.invoke.unavailable', {
- reason: blockingReasons[0] ?? t('topbar.invoke.unrunnable'),
- })
+ : isPreparing
+ ? t('topbar.invoke.preparing')
+ : t('topbar.invoke.unavailable', {
+ reason: blockingReasons[0] ?? t('topbar.invoke.unrunnable'),
+ })
}
colorPalette="brand"
- cursor={isValid ? undefined : 'not-allowed'}
+ cursor={canInvoke ? undefined : 'not-allowed'}
flexShrink={0}
- opacity={isValid ? undefined : 0.55}
+ opacity={canInvoke ? undefined : 0.55}
size="xs"
onBlur={handleBlur}
- onClick={isValid ? handleClick : undefined}
+ onClick={canInvoke ? handleClick : undefined}
onFocus={handleFocus}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
@@ -132,7 +137,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {
const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[] | null; state: InvocationState }) => {
const { t } = useTranslation();
- const { batchCount, blockingReasons, invocation, isValid, promptExpansion } = state;
+ const { batchCount, blockingReasons, invocation, isPreparing, isValid, promptExpansion } = state;
const destination = getDestinationLabel(invocation.destination);
const promptCount = promptExpansion.count;
const summary =
@@ -146,7 +151,11 @@ const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[
<Stack gap="1.5" minW="14rem" p="2">
<HStack justify="space-between">
<Text fontSize="xs" fontWeight="800">
- {isValid ? t('topbar.invoke.addToQueue') : t('topbar.invoke.unableToQueue')}
+ {isPreparing
+ ? t('topbar.invoke.preparing')
+ : isValid
+ ? t('topbar.invoke.addToQueue')
+ : t('topbar.invoke.unableToQueue')}
</Text>
{shortcutParts ? (
<Kbd size="sm" variant="subtle">
@@ -158,7 +167,11 @@ const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[
{summary}
</Text>
<Separator borderColor="border.subtle" />
- {blockingReasons.length > 0 ? (
+ {isPreparing ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('topbar.invoke.preparing')}
+ </Text>
+ ) : blockingReasons.length > 0 ? (
<Stack gap="1">
{blockingReasons.map((reason) => (
<HStack key={reason} align="start" gap="1.5">
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.browser.test.tsx
index 42678b3ef1..5c3485d734 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.browser.test.tsx
@@ -45,6 +45,7 @@ const BASE_STATE = {
sourceLocked: false,
},
invoke: NOOP_INVOKE,
+ isPreparing: false,
isValid: true,
placedTypeIds: new Set(['generate']),
promptExpansion: {},
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
index fb24814f45..424dc01359 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
@@ -14,6 +14,7 @@ import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useInvocationTemplatesSelector } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';
+import { useIsCanvasInvocationPreparing } from '@workbench/canvasInvocationPreparation';
import { getPlacedWidgetTypeIds, getVisibleWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';
import {
createInvocationRouteInputSelector,
@@ -52,6 +53,7 @@ export interface InvocationState {
batchCount: number;
blockingReasons: string[];
invocation: InvocationRoute;
+ isPreparing: boolean;
isValid: boolean;
sources: GraphWidgetSource[];
visibleTypeIds: ReadonlySet<WidgetTypeId>;
@@ -73,6 +75,8 @@ export const useInvocationState = (): InvocationState => {
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
const availabilityModels = modelsStatus === 'loaded' ? models : undefined;
const { invocation } = routeInput;
+ const isCanvasPreparing = useIsCanvasInvocationPreparing(routeInput.projectId);
+ const isPreparing = invocation.sourceId === 'canvas' && isCanvasPreparing;
// Project-graph route validation reads the invocation templates imperatively;
// subscribing here keeps the resolved route live while they load.
@@ -134,6 +138,7 @@ export const useInvocationState = (): InvocationState => {
blockingReasons,
invocation,
invoke,
+ isPreparing,
isValid,
placedTypeIds,
promptExpansion,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 2fa2d4d74f..f451051ace 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -4,6 +4,8 @@ import type { MouseEvent as ReactMouseEvent } from 'react';
import { Box } from '@chakra-ui/react';
import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';
import { useQueueItemProgressImage } from '@features/queue/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { preloadCanvasInvocation } from '@workbench/activeInvocationSubmission';
import { getCanvasImportNotice } from '@workbench/canvas-operations/api';
import { getCanvasStagingSlots } from '@workbench/canvasStagingView';
import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';
@@ -78,6 +80,11 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);
const { createFromBbox, isCreating } = useCreateFromBbox(engine);
+ // Canvas invocation stays code-split from the rest of the workbench, but the
+ // canvas being mounted is a strong intent signal. Warm it while the user edits
+ // instead of making the first Ctrl+Enter pay the chunk download/evaluation.
+ useMountEffect(preloadCanvasInvocation);
+
// Right-click on the canvas surface: hit-test the layer under the cursor and
// open either the shared per-layer menu or the global empty-space menu at the
// pointer. Locked interaction skips the hit-test but keeps global save visible.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 0da1db907f..2dbbfbcbc3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -26,7 +26,8 @@
* notice — the app never gets stuck.
*
* A module-scoped in-flight guard drops an invoke while a prior prepare for the
- * same project is still running (the Invoke hotkey can be mashed).
+ * same project is still running. The active Ctrl+Enter/topbar path also holds a
+ * shallower user-facing guard from the instant the command begins.
*/
import type { GenerateModelConfig } from '@features/generation/contracts';
@@ -463,7 +464,9 @@ export interface PrepareCanvasInvocationArgs {
/**
* Resolves the active project's engine and runs the canvas-invoke orchestrator.
- * Fire-and-track: the caller does not await it (the Invoke command stays sync).
+ * The returned promise settles after the graph is dispatched or a failure is
+ * reported, allowing the active command to keep its preparing acknowledgement
+ * live for the complete pre-queue window. Other callers may still fire-and-track.
*/
export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs): Promise<void> => {
const owner = args.owner ?? captureAccountScope();