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.

refactor(webv2): route canvas edit intents and origins through the mutation port

joshistoast9584777978c6
diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
index 790180a7d1..66101be91a 100644
--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
@@ -33,7 +33,7 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })
const adapter = useMemo<UpscaleUiAdapter>(
() => ({
...project,
- patchPromptDraft: (values) => commands.generation.patchPromptDraft(values, project.projectId),
+ patchPromptDraft: (values) => commands.generation.patchPromptDraft(values, 'upscale', project.projectId),
patchValues: (values, origin) => commands.widgets.patchValues('upscale', values, project.projectId, origin),
reportError: (message) =>
commands.notifications.reportError({ area: 'upscale', message, namespace: 'generation' }),
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 62690aa2e9..d788d1ecba 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -80,6 +80,7 @@
"WorkbenchRuntime.tsx": "workbench",
"WorkbenchSessionController.tsx": "workbench",
"WorkbenchWidgetRegistryContext.tsx": "workbench",
+ "autoRoutePolicy.ts": "workbench",
"canvasDimsSync.ts": "workbench",
"canvasLayerOps.ts": "workbench",
"canvasMigration.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index ef6867ba45..f98223beb2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -643,18 +643,3 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettings
export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues =>
isGenerateSettings(values) && isGenerateModelConfig((values as unknown as Record<string, unknown>).model);
-
-/**
- * Widget-value keys that carry no generation intent — layout state and the
- * shared topbar batch count. Any other changed key is a high-confidence edit
- * for auto-switching the Invoke route, so new settings count by default.
- */
-const GENERATE_UI_NOISE_KEYS: ReadonlySet<string> = new Set([
- 'aspectRatioIsLocked',
- 'batchCount',
- 'negativePromptHeightPx',
- 'positivePromptHeightPx',
-]);
-
-export const isHighConfidenceGenerateEdit = (changedKeys: readonly string[]): boolean =>
- changedKeys.some((key) => !GENERATE_UI_NOISE_KEYS.has(key));
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 7f05b01529..8c3c9c229c 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -13,7 +13,6 @@ export {
getDefaultLoraWeight,
getModelDefaultVae,
hasModelDefaultVae,
- isHighConfidenceGenerateEdit,
isLoraCompatibleWithModel,
isLoraModelConfig,
isMainModelConfig,
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
index 11fc358285..a080f4fa45 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
@@ -45,6 +45,7 @@ describe('Upscale snapshot submission', () => {
});
state = workbenchReducer(state, {
projectId,
+ sourceId: 'upscale',
type: 'patchProjectPromptDraft',
values: { negativePrompt: 'blur', positivePrompt: 'fine detail' },
});
@@ -57,6 +58,7 @@ describe('Upscale snapshot submission', () => {
});
state = workbenchReducer(state, {
projectId,
+ sourceId: 'upscale',
type: 'patchProjectPromptDraft',
values: { negativePrompt: 'changed later', positivePrompt: 'changed later' },
});
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
index a91fca73fa..7a129d7f63 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
@@ -350,17 +350,3 @@ export const resolveUpscaleSeed = (values: UpscaleWidgetValues): number =>
values.shouldRandomizeSeed ? Math.floor(Math.random() * SEED_MAX) : values.seed;
export const cloneUpscaleWidgetValues = (values: UpscaleWidgetValues): UpscaleWidgetValues => structuredClone(values);
-
-/**
- * Widget-value keys that carry no upscale intent — layout state and the shared
- * topbar batch count. Any other changed key is a high-confidence edit for
- * auto-switching the Invoke route, so new settings count by default.
- */
-const UPSCALE_UI_NOISE_KEYS: ReadonlySet<string> = new Set([
- 'batchCount',
- 'negativePromptHeightPx',
- 'positivePromptHeightPx',
-]);
-
-export const isHighConfidenceUpscaleEdit = (changedKeys: readonly string[]): boolean =>
- changedKeys.some((key) => !UPSCALE_UI_NOISE_KEYS.has(key));
diff --git a/invokeai/frontend/webv2/src/features/upscale/index.ts b/invokeai/frontend/webv2/src/features/upscale/index.ts
index 6049902d54..d0c5a4a648 100644
--- a/invokeai/frontend/webv2/src/features/upscale/index.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/index.ts
@@ -5,7 +5,6 @@ export {
createDefaultUpscaleWidgetValues,
getUpscaleOutputDimensions,
getUpscaleValidationReasons,
- isHighConfidenceUpscaleEdit,
normalizeUpscaleWidgetValues,
resolveUpscaleSeed,
syncUpscaleWidgetValuesWithModels,
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
index ff2b3b2112..001af37897 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
@@ -334,16 +334,6 @@ const undoLabels: Partial<Record<ProjectGraphAction['type'], string>> = {
/** Returns the project-undo label for an action, or null when the edit should not create an undo entry. */
export const getProjectGraphUndoLabel = (action: ProjectGraphAction): string | null => undoLabels[action.type] ?? null;
-/** Edits meaningful enough to auto-select the project graph as the invocation source. */
-export const isHighConfidenceGraphEdit = (action: ProjectGraphAction): boolean =>
- action.type === 'addNode' ||
- action.type === 'addNodeAndEdge' ||
- action.type === 'addGraphElements' ||
- action.type === 'removeNodes' ||
- action.type === 'addEdge' ||
- action.type === 'removeEdges' ||
- action.type === 'setFieldValue';
-
const updateNode = (
document: ProjectGraphState,
nodeId: string,
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts
new file mode 100644
index 0000000000..1fb32fe863
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts
@@ -0,0 +1,166 @@
+import type { InvocationRoute } from '@workbench/invocationContracts';
+
+import { describe, expect, it } from 'vitest';
+
+import type { CanvasProjectMutation } from './canvasProjectMutations';
+
+import {
+ autoSwitchDestinations,
+ getChangedValueKeys,
+ getRouteAfterHighConfidenceEdit,
+ isHighConfidenceCanvasEdit,
+ isHighConfidenceCanvasEditIntent,
+ isHighConfidenceGenerateEdit,
+ isHighConfidenceGraphEdit,
+ isHighConfidenceUpscaleEdit,
+} from './autoRoutePolicy';
+
+const mutation = (value: Record<string, unknown>): CanvasProjectMutation => value as never;
+
+const route = (overrides: Partial<InvocationRoute> = {}): InvocationRoute => ({
+ destination: 'canvas',
+ destinationLocked: false,
+ sourceId: 'generate',
+ sourceLocked: false,
+ ...overrides,
+});
+
+describe('getRouteAfterHighConfidenceEdit', () => {
+ it('maps each new source to its default destination', () => {
+ expect(getRouteAfterHighConfidenceEdit(route({ sourceId: 'canvas' }), 'generate')).toEqual(
+ route({ destination: 'gallery', sourceId: 'generate' })
+ );
+ expect(getRouteAfterHighConfidenceEdit(route(), 'workflow')).toEqual(
+ route({ destination: 'gallery', sourceId: 'workflow' })
+ );
+ expect(getRouteAfterHighConfidenceEdit(route(), 'upscale')).toEqual(
+ route({ destination: 'gallery', sourceId: 'upscale' })
+ );
+ expect(getRouteAfterHighConfidenceEdit(route({ destination: 'gallery' }), 'canvas')).toEqual(
+ route({ destination: 'canvas', sourceId: 'canvas' })
+ );
+ expect(Object.keys(autoSwitchDestinations).sort()).toEqual(['canvas', 'generate', 'upscale', 'workflow']);
+ });
+
+ it('preserves route identity for same-source and source-locked edits', () => {
+ const sameSource = route({ destination: 'gallery' });
+ const locked = route({ sourceLocked: true });
+
+ expect(getRouteAfterHighConfidenceEdit(sameSource, 'generate')).toBe(sameSource);
+ expect(getRouteAfterHighConfidenceEdit(locked, 'canvas')).toBe(locked);
+ });
+
+ it('preserves a locked destination while changing source', () => {
+ expect(getRouteAfterHighConfidenceEdit(route({ destinationLocked: true }), 'workflow')).toEqual(
+ route({ destinationLocked: true, sourceId: 'workflow' })
+ );
+ });
+});
+
+describe('widget edit classification', () => {
+ it('detects changed keys with Object.is semantics', () => {
+ expect(
+ getChangedValueKeys({ height: 512, model: null, seed: Number.NaN }, { height: 512, seed: Number.NaN })
+ ).toEqual([]);
+ expect(getChangedValueKeys({ height: 512 }, { height: 768, unknown: true })).toEqual(['height', 'unknown']);
+ });
+
+ it('ignores only documented Generate and Upscale UI noise', () => {
+ expect(
+ isHighConfidenceGenerateEdit([
+ 'aspectRatioIsLocked',
+ 'batchCount',
+ 'negativePromptHeightPx',
+ 'positivePromptHeightPx',
+ ])
+ ).toBe(false);
+ expect(isHighConfidenceUpscaleEdit(['batchCount', 'negativePromptHeightPx', 'positivePromptHeightPx'])).toBe(false);
+ expect(isHighConfidenceGenerateEdit(['steps'])).toBe(true);
+ expect(isHighConfidenceUpscaleEdit(['creativity'])).toBe(true);
+ expect(isHighConfidenceGenerateEdit(['futureSetting'])).toBe(true);
+ expect(isHighConfidenceUpscaleEdit(['futureSetting'])).toBe(true);
+ });
+});
+
+describe('Canvas edit classification', () => {
+ it('counts structural layer-stack and visibility changes but not selection-only changes', () => {
+ expect(
+ isHighConfidenceCanvasEdit(
+ mutation({
+ add: { index: 0, layers: [{}] },
+ enabledUpdates: [],
+ selectedLayerId: 'new-layer',
+ type: 'applyCanvasLayerStackMutation',
+ })
+ )
+ ).toBe(true);
+ expect(
+ isHighConfidenceCanvasEdit(
+ mutation({
+ enabledUpdates: [],
+ removeIds: ['old-layer'],
+ selectedLayerId: null,
+ type: 'applyCanvasLayerStackMutation',
+ })
+ )
+ ).toBe(true);
+ expect(
+ isHighConfidenceCanvasEdit(
+ mutation({
+ enabledUpdates: [{ id: 'layer', isEnabled: false }],
+ selectedLayerId: 'layer',
+ type: 'applyCanvasLayerStackMutation',
+ })
+ )
+ ).toBe(true);
+ expect(
+ isHighConfidenceCanvasEdit(
+ mutation({ enabledUpdates: [], selectedLayerId: 'layer', type: 'applyCanvasLayerStackMutation' })
+ )
+ ).toBe(false);
+ expect(isHighConfidenceCanvasEdit(mutation({ type: 'setCanvasLayersEnabled', updates: [] }))).toBe(false);
+ expect(
+ isHighConfidenceCanvasEdit(
+ mutation({ type: 'setCanvasLayersEnabled', updates: [{ id: 'layer', isEnabled: false }] })
+ )
+ ).toBe(true);
+ });
+
+ it('counts composite layer patches but ignores metadata-only patches', () => {
+ for (const patch of [{ blendMode: 'multiply' }, { isEnabled: false }, { opacity: 0.5 }, { transform: { x: 1 } }]) {
+ expect(isHighConfidenceCanvasEdit(mutation({ patch, type: 'updateCanvasLayer' }))).toBe(true);
+ }
+ expect(
+ isHighConfidenceCanvasEdit(mutation({ patch: { isLocked: true, name: 'Layer 1' }, type: 'updateCanvasLayer' }))
+ ).toBe(false);
+ });
+
+ it('treats committed paint as intent and delegates mutation intents', () => {
+ expect(isHighConfidenceCanvasEditIntent({ kind: 'paint' })).toBe(true);
+ expect(
+ isHighConfidenceCanvasEditIntent({
+ kind: 'mutation',
+ mutation: mutation({ id: 'layer', type: 'setCanvasSelectedLayer' }),
+ })
+ ).toBe(false);
+ });
+});
+
+describe('Workflow edit classification', () => {
+ it('counts graph topology and field values while ignoring presentation changes', () => {
+ for (const type of [
+ 'addEdge',
+ 'addGraphElements',
+ 'addNode',
+ 'addNodeAndEdge',
+ 'removeEdges',
+ 'removeNodes',
+ 'setFieldValue',
+ ] as const) {
+ expect(isHighConfidenceGraphEdit({ type } as never)).toBe(true);
+ }
+ for (const type of ['setMetadata', 'setNodeLabel', 'setNodePosition'] as const) {
+ expect(isHighConfidenceGraphEdit({ type } as never)).toBe(false);
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
new file mode 100644
index 0000000000..94e4330604
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
@@ -0,0 +1,159 @@
+import type { ProjectGraphAction } from '@features/workflow/utility';
+import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';
+
+import type { CanvasProjectMutation } from './canvasProjectMutations';
+
+import { isInvocationSourceAvailable } from './invocation';
+
+/** Programmatic dispatches never auto-switch the Invoke route; absent means user. */
+export type WorkbenchActionOrigin = 'user' | 'system';
+
+/** Destination each surface maps to when the source auto-switches. */
+export const autoSwitchDestinations: Record<InvocationSourceId, ResultDestination> = {
+ canvas: 'canvas',
+ generate: 'gallery',
+ upscale: 'gallery',
+ workflow: 'gallery',
+};
+
+/**
+ * Route after a high-confidence edit on `sourceId`; identity-preserving when
+ * nothing changes. The destination remaps only on an actual source transition,
+ * so repeated edits on the same surface never re-force a manually chosen
+ * destination, and locks always win.
+ */
+export const getRouteAfterHighConfidenceEdit = (
+ invocation: InvocationRoute,
+ sourceId: InvocationSourceId
+): InvocationRoute => {
+ if (invocation.sourceLocked || invocation.sourceId === sourceId || !isInvocationSourceAvailable(sourceId)) {
+ return invocation;
+ }
+
+ const destination = invocation.destinationLocked ? invocation.destination : autoSwitchDestinations[sourceId];
+
+ return { ...invocation, destination, sourceId };
+};
+
+export const getChangedValueKeys = (previous: Record<string, unknown>, patch: Record<string, unknown>): string[] =>
+ Object.keys(patch).filter((key) => !Object.is(previous[key], patch[key]));
+
+const GENERATE_UI_NOISE_KEYS: ReadonlySet<string> = new Set([
+ 'aspectRatioIsLocked',
+ 'batchCount',
+ 'negativePromptHeightPx',
+ 'positivePromptHeightPx',
+]);
+
+const UPSCALE_UI_NOISE_KEYS: ReadonlySet<string> = new Set([
+ 'batchCount',
+ 'negativePromptHeightPx',
+ 'positivePromptHeightPx',
+]);
+
+const hasIntentBearingKey = (changedKeys: readonly string[], noiseKeys: ReadonlySet<string>): boolean =>
+ changedKeys.some((key) => !noiseKeys.has(key));
+
+export const isHighConfidenceGenerateEdit = (changedKeys: readonly string[]): boolean =>
+ hasIntentBearingKey(changedKeys, GENERATE_UI_NOISE_KEYS);
+
+export const isHighConfidenceUpscaleEdit = (changedKeys: readonly string[]): boolean =>
+ hasIntentBearingKey(changedKeys, UPSCALE_UI_NOISE_KEYS);
+
+const GRAPH_EDIT_CONFIDENCE = {
+ addEdge: true,
+ addFormElement: false,
+ addGraphElements: true,
+ addNode: true,
+ addNodeAndEdge: true,
+ exposeField: false,
+ moveFormElement: false,
+ moveFormElementTo: false,
+ removeEdges: true,
+ removeFormElement: false,
+ removeNodes: true,
+ setContainerLayout: false,
+ setFieldDescription: false,
+ setFieldLabel: false,
+ setFieldValue: true,
+ setFormElementContent: false,
+ setMetadata: false,
+ setNodeFieldShowDescription: false,
+ setNodeIsIntermediate: false,
+ setNodeIsOpen: false,
+ setNodeLabel: false,
+ setNodeNotes: false,
+ setNodePosition: false,
+ setNodeUseCache: false,
+ unexposeField: false,
+} satisfies Record<ProjectGraphAction['type'], boolean>;
+
+export const isHighConfidenceGraphEdit = (action: ProjectGraphAction): boolean => GRAPH_EDIT_CONFIDENCE[action.type];
+
+type CanvasEditConfidence = 'conditional' | 'high' | 'none';
+
+const CANVAS_EDIT_CONFIDENCE = {
+ addCanvasLayer: 'high',
+ applyCanvasLayerStackMutation: 'conditional',
+ clearCanvasStaging: 'none',
+ commitStagedImage: 'none',
+ convertCanvasLayer: 'high',
+ cycleStagedImage: 'none',
+ deleteCanvasSnapshot: 'none',
+ discardAllStagedImages: 'none',
+ discardSelectedStagedImage: 'none',
+ duplicateCanvasLayer: 'high',
+ mergeCanvasLayersDown: 'high',
+ removeCanvasLayers: 'high',
+ reorderCanvasLayers: 'high',
+ replaceCanvasDocument: 'none',
+ replaceCanvasLayer: 'high',
+ resizeCanvasDocument: 'high',
+ restoreCanvasSnapshot: 'none',
+ rollbackStagedImageCommit: 'none',
+ saveCanvasSnapshot: 'none',
+ setCanvasBbox: 'high',
+ setCanvasLayersEnabled: 'conditional',
+ setCanvasSelectedLayer: 'none',
+ setCanvasStagingAutoSwitch: 'none',
+ setStagedImageIndex: 'none',
+ toggleCanvasStagingThumbnailsVisibility: 'none',
+ toggleCanvasStagingVisibility: 'none',
+ updateCanvasLayer: 'conditional',
+ updateCanvasLayerConfig: 'high',
+ updateCanvasLayerSource: 'high',
+} satisfies Record<CanvasProjectMutation['type'], CanvasEditConfidence>;
+
+const CONTENT_BEARING_LAYER_PATCH_KEYS = ['blendMode', 'isEnabled', 'opacity', 'transform'] as const;
+
+export const isHighConfidenceCanvasEdit = (mutation: CanvasProjectMutation): boolean => {
+ const confidence = CANVAS_EDIT_CONFIDENCE[mutation.type];
+
+ if (confidence === 'high') {
+ return true;
+ }
+ if (confidence === 'none') {
+ return false;
+ }
+
+ if (mutation.type === 'applyCanvasLayerStackMutation') {
+ return (
+ (mutation.add?.layers.length ?? 0) > 0 ||
+ (mutation.removeIds?.length ?? 0) > 0 ||
+ mutation.enabledUpdates.length > 0
+ );
+ }
+ if (mutation.type === 'setCanvasLayersEnabled') {
+ return mutation.updates.length > 0;
+ }
+ if (mutation.type === 'updateCanvasLayer') {
+ return CONTENT_BEARING_LAYER_PATCH_KEYS.some((key) => key in mutation.patch);
+ }
+
+ return false;
+};
+
+export type CanvasEditIntent = { kind: 'paint' } | { kind: 'mutation'; mutation: CanvasProjectMutation };
+
+export const isHighConfidenceCanvasEditIntent = (intent: CanvasEditIntent): boolean =>
+ intent.kind === 'paint' || isHighConfidenceCanvasEdit(intent.mutation);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index e31fbbba4c..49be6a288f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -11,14 +11,17 @@ Canvas mutations are explicitly project-addressed. `CanvasProjectMutation` is th
type: 'applyCanvasProjectMutation';
projectId: string;
mutation: CanvasProjectMutation;
+ origin?: 'user' | 'system';
}
```
The workbench reducer handles this envelope only through `updateProjectById`. There are no canvas actions whose target is inferred from the active project.
-Each engine receives a `CanvasProjectMutationPort` bound to its immutable `projectId`. The port exposes only `getCanvasState()`, `subscribe()`, and `dispatch(mutation)`. It neither exposes the global workbench dispatcher nor follows active-project changes. Widgets use `useCanvasProjectMutationDispatch`, which captures the current project ID and emits the same envelope. Consequently, project switches and colliding layer IDs cannot redirect a delayed engine mutation to another project.
+Each engine receives a `CanvasProjectMutationPort` bound to its immutable `projectId`. The port exposes `getCanvasState()`, `subscribe()`, `dispatch(mutation, origin?)`, and `commitEdit(intent)`. It neither exposes the global workbench dispatcher nor follows active-project changes. Widgets use `useCanvasProjectMutationDispatch`, which captures the current project ID and emits the same envelope. Consequently, project switches and colliding layer IDs cannot redirect a delayed engine mutation to another project.
-The port's `dispatch()` returns whether the named project's canvas identity changed. Paint persistence clears a dirty result only after the intended layer accepts the bitmap reference. A rejected update retains dirty pixels for retry; deletion of the layer or project is terminal and discards obsolete persistence work. This applies equally to raster/control paint sources and paint-backed masks.
+The port's `dispatch()` returns whether the named project's canvas identity changed. User-origin mutations may auto-route the invocation controller; history replay, synchronization, rollback, and bitmap persistence dispatch as `system`. Prepared transactions dispatch their document mutation as `system`, verify reducer and mirror postconditions, then call `commitEdit()` exactly once for a successful user edit. Paint calls `commitEdit({ kind: 'paint' })` synchronously at stroke commit, so a delayed persistence upload can never steal a later manual route.
+
+Paint persistence clears a dirty result only after the intended layer accepts the bitmap reference. A rejected update retains dirty pixels for retry; deletion of the layer or project is terminal and discards obsolete persistence work. This applies equally to raster/control paint sources and paint-backed masks.
## Package and capability boundaries
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
index 31c245f266..a1eb702162 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
@@ -41,6 +41,7 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {
const lock = createLockStore();
const editOwner = Symbol('test-edit-owner');
const deps: CanvasMutationContextDeps = {
+ commitEdit: vi.fn(),
createLayerId: () => 'layer-new',
dispatch: vi.fn(() => true),
editOwner,
@@ -107,8 +108,48 @@ describe('createCanvasMutationContext', () => {
});
describe('dispatchPrepared', () => {
+ it('defers a user edit route until reducer and mirror postconditions succeed', () => {
+ const { context, deps } = createHarness();
+
+ context.dispatchPrepared(
+ action,
+ () => true,
+ () => true
+ );
+
+ expect(deps.dispatch).toHaveBeenCalledWith(action, 'system');
+ expect(deps.commitEdit).toHaveBeenCalledWith({ kind: 'mutation', mutation: action });
+ });
+
+ it('does not commit system-originated or history-replayed edit intent', () => {
+ const history = createHistory();
+ const { context, deps } = createHarness({ history });
+
+ context.dispatchPrepared(
+ action,
+ () => true,
+ () => true,
+ 'system'
+ );
+ history.push({
+ bytes: 1,
+ label: 'Replay',
+ redo: () => undefined,
+ undo: () =>
+ context.dispatchPrepared(
+ action,
+ () => true,
+ () => true
+ ),
+ });
+ history.undo();
+
+ expect(deps.commitEdit).not.toHaveBeenCalled();
+ });
+
it('throws when dispatch rejects the mutation and the reducer shows no postcondition', () => {
- const { context } = createHarness({ dispatch: () => false });
+ const commitEdit = vi.fn();
+ const { context } = createHarness({ commitEdit, dispatch: () => false });
expect(() =>
context.dispatchPrepared(
action,
@@ -116,6 +157,7 @@ describe('createCanvasMutationContext', () => {
() => false
)
).toThrow('Canvas document mutation was rejected');
+ expect(commitEdit).not.toHaveBeenCalled();
});
it('rethrows a dispatch error when the reducer did not apply the mutation', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
index 136c4afb9f..d828a48fe1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
@@ -1,3 +1,4 @@
+import type { CanvasEditIntent, WorkbenchActionOrigin } from '@workbench/autoRoutePolicy';
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
import type { History } from '@workbench/canvas-engine/history/history';
@@ -32,8 +33,13 @@ export interface CanvasMutationContext {
capturePermit(owner?: symbol): DocumentEditPermit | null;
isPermitCurrent(permit: DocumentEditPermit): boolean;
isGuardCurrent(guard: LayerExportGuard): boolean;
- dispatch(action: CanvasProjectMutation): boolean;
- dispatchPrepared(action: CanvasProjectMutation, reducerAccepted: () => boolean, mirrorAccepted: () => boolean): void;
+ dispatch(action: CanvasProjectMutation, origin?: WorkbenchActionOrigin): boolean;
+ dispatchPrepared(
+ action: CanvasProjectMutation,
+ reducerAccepted: () => boolean,
+ mirrorAccepted: () => boolean,
+ origin?: WorkbenchActionOrigin
+ ): void;
preparePixels(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;
installPrepared(prepared: PreparedLayerCacheReplacement, persist?: boolean): void;
endBurst(): void;
@@ -46,7 +52,8 @@ export interface CanvasMutationContextDeps {
readonly history: History;
readonly getDocument: () => CanvasDocumentContractV2 | null;
readonly getReducerDocument: () => CanvasDocumentContractV2 | null;
- readonly dispatch: (action: CanvasProjectMutation) => boolean;
+ readonly dispatch: (action: CanvasProjectMutation, origin?: WorkbenchActionOrigin) => boolean;
+ readonly commitEdit: (intent: CanvasEditIntent) => void;
readonly refreshMirror: () => void;
readonly editingLocked: { get(): boolean; subscribe(listener: () => void): () => void };
readonly editOwner: symbol;
@@ -86,10 +93,13 @@ export const createCanvasMutationContext = (
const dispatchPrepared = (
action: CanvasProjectMutation,
isApplied: () => boolean,
- isMirrored: () => boolean
+ isMirrored: () => boolean,
+ origin: WorkbenchActionOrigin = deps.history.isApplying() ? 'system' : 'user'
): void => {
try {
- if (!deps.dispatch(action)) {
+ // Prepared mutations are not route-worthy until both reducer and mirror
+ // postconditions succeed. Commit their edit intent separately below.
+ if (!deps.dispatch(action, 'system')) {
throw new Error('Canvas document mutation was rejected');
}
} catch (error) {
@@ -114,7 +124,6 @@ export const createCanvasMutationContext = (
if (!isMirrored()) {
throw error;
}
- return;
}
// A reducer may reject a guarded transaction by returning the unchanged
@@ -136,13 +145,17 @@ export const createCanvasMutationContext = (
throw new Error('Canvas document mutation was not mirrored');
}
}
+
+ if (origin === 'user') {
+ deps.commitEdit({ kind: 'mutation', mutation: action });
+ }
};
return {
canEdit,
capturePermit,
createLayerId: () => deps.createLayerId(),
- dispatch: (action) => deps.dispatch(action),
+ dispatch: (action, origin) => deps.dispatch(action, origin),
dispatchPrepared,
dispose: () => unsubscribeDocumentEditingLock(),
endBurst: () => deps.endBurst(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts
index 57bd8418ff..889a059a57 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts
@@ -29,7 +29,8 @@ const createMirrorRejectingPort = (
let readsAfterCommit = 0;
let armedType: CanvasProjectMutation['type'] | null = null;
const port: CanvasProjectMutationPort = {
- dispatch: (mutation) => {
+ commitEdit: real.commitEdit,
+ dispatch: (mutation, origin) => {
if (mutation.type === armedType) {
faultActive = true;
readsAfterCommit = 0;
@@ -37,7 +38,7 @@ const createMirrorRejectingPort = (
} else {
faultActive = false;
}
- return real.dispatch(mutation);
+ return real.dispatch(mutation, origin);
},
getCanvasState: () => {
if (faultActive) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
index e6e0c56ae3..98c12f9cfc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
@@ -18,7 +18,8 @@ export interface StagedResultControllerOptions<Permit, Owner = symbol> {
readonly dispatchPrepared: (
mutation: CanvasProjectMutation,
reducerAccepted: () => boolean,
- mirrorAccepted: () => boolean
+ mirrorAccepted: () => boolean,
+ origin?: 'system' | 'user'
) => void;
readonly endBurst: () => void;
readonly getCanvasState: () => CanvasStateContractV2 | null;
@@ -144,7 +145,8 @@ export class StagedResultController<Permit, Owner = symbol> {
() =>
hasPreviousLayerStack(o.getCanvasState()?.document ?? null) &&
o.getCanvasState()?.stagingArea === previousStagingArea,
- () => hasPreviousLayerStack(o.getDocument())
+ () => hasPreviousLayerStack(o.getDocument()),
+ 'system'
);
}
return { status: 'stale' };
@@ -162,7 +164,7 @@ export class StagedResultController<Permit, Owner = symbol> {
o.dispatchPrepared(mutation, reducerAccepted, mirrorAccepted);
} catch (error) {
if (reducerAccepted()) {
- o.dispatchPrepared(rollback, reducerRolledBack, mirrorRolledBack);
+ o.dispatchPrepared(rollback, reducerRolledBack, mirrorRolledBack, 'system');
}
throw error;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts
index 09e281ea48..4ad52e838c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts
@@ -38,6 +38,7 @@ interface EngineStore {
}
const createMutationPort = (store: EngineStore, projectId: string): CanvasProjectMutationPort => ({
+ commitEdit: () => undefined,
dispatch: (mutation) => {
const before = store.getState().projects.find((project) => project.id === projectId)?.canvas ?? null;
if (!before) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 452b5bf766..9631b02ced 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -72,6 +72,7 @@ const createTestMutationPort = (store: EngineStore, projectId: string): CanvasPr
}
});
return {
+ commitEdit: () => undefined,
dispatch: (mutation) => {
const before = canvas;
if (!before) {
@@ -3423,11 +3424,15 @@ describe('engine-owned history: stroke → undo → redo', () => {
},
};
const bitmapStore = createSpyBitmapStore();
+ const mutationPort = createTestMutationPort(store, 'p1');
+ const commitEdit = vi.fn(mutationPort.commitEdit);
+ mutationPort.commitEdit = commitEdit;
const engine = createCanvasEngine({
backend,
bitmapStore,
imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort,
projectId: 'p1',
store,
});
@@ -3444,11 +3449,11 @@ describe('engine-owned history: stroke → undo → redo', () => {
overlay.fire('pointermove', pointerAt(40, 40));
overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));
- return { bitmapStore, engine, strokes, surfaces };
+ return { bitmapStore, commitEdit, engine, strokes, surfaces };
};
it('records a stroke and restores before/after pixels on undo/redo', () => {
- const { bitmapStore, engine, strokes, surfaces } = drawStroke();
+ const { bitmapStore, commitEdit, engine, strokes, surfaces } = drawStroke();
// One stroke committed and one history entry recorded.
expect(strokes).toHaveLength(1);
@@ -3456,6 +3461,8 @@ describe('engine-owned history: stroke → undo → redo', () => {
expect(event.layerId).toBe('paint1');
expect(engine.stores.canUndo.get()).toBe(true);
expect(engine.stores.canRedo.get()).toBe(false);
+ expect(commitEdit).toHaveBeenCalledOnce();
+ expect(commitEdit).toHaveBeenCalledWith({ kind: 'paint' });
// The commit marked the layer dirty for persistence.
const dirtyAfterStroke = bitmapStore.markLayerDirty.mock.calls.length;
expect(dirtyAfterStroke).toBeGreaterThanOrEqual(1);
@@ -3479,6 +3486,7 @@ describe('engine-owned history: stroke → undo → redo', () => {
expect(redoPut).toBeDefined();
expect(engine.stores.canUndo.get()).toBe(true);
expect(engine.stores.canRedo.get()).toBe(false);
+ expect(commitEdit).toHaveBeenCalledOnce();
engine.lifecycle.dispose();
});
@@ -5742,6 +5750,7 @@ describe('staged result acceptance', () => {
pendingImages: [stagedCandidate()],
};
const mutationPort: CanvasProjectMutationPort = {
+ commitEdit: () => undefined,
dispatch: () => false,
getCanvasState: () => canvas,
subscribe: () => () => undefined,
@@ -5774,6 +5783,7 @@ describe('staged result acceptance', () => {
let committed = false;
let postCommitReads = 0;
const mutationPort: CanvasProjectMutationPort = {
+ commitEdit: () => undefined,
dispatch: (mutation) => {
if (mutation.type !== 'commitStagedImage') {
return false;
@@ -5834,6 +5844,7 @@ describe('staged result acceptance', () => {
backend: createTestStubRasterBackend(),
imageResolver: () => Promise.resolve(new Blob()),
mutationPort: {
+ commitEdit: () => undefined,
dispatch: () => false,
getCanvasState: () => null,
subscribe: () => () => undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 24f76cb91b..73757a6b76 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -616,17 +616,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return false;
}
if (layer.type === 'raster' || layer.type === 'control') {
- return mutationPort.dispatch({
- id: layerId,
- source: { bitmap, offset, type: 'paint' },
- type: 'updateCanvasLayerSource',
- });
+ return mutationPort.dispatch(
+ {
+ id: layerId,
+ source: { bitmap, offset, type: 'paint' },
+ type: 'updateCanvasLayerSource',
+ },
+ 'system'
+ );
} else if (layer.type === 'inpaint_mask' || layer.type === 'regional_guidance') {
- return mutationPort.dispatch({
- config: { layerType: layer.type, mask: { bitmap, offset } },
- id: layerId,
- type: 'updateCanvasLayerConfig',
- });
+ return mutationPort.dispatch(
+ {
+ config: { layerType: layer.type, mask: { bitmap, offset } },
+ id: layerId,
+ type: 'updateCanvasLayerConfig',
+ },
+ 'system'
+ );
}
return false;
};
@@ -637,7 +643,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const bitmapStore: BitmapStore =
opts.bitmapStore ??
createBitmapStore({
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => mutationPort.dispatch(action, 'system'),
dispatchBitmap: (layerId, bitmap, offset) => dispatchLayerBitmap(layerId, bitmap, offset),
encodeSurface: (surface) => backend.encodeSurface(surface),
getAuthoritativeLayerSource: getAuthoritativeLayerSourceById,
@@ -666,6 +672,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
isGestureActive: () => pipeline.isGestureActive(),
});
const history = historyController.history;
+ const dispatchCanvasMutation = (
+ action: CanvasProjectMutation,
+ origin: 'system' | 'user' = history.isApplying() ? 'system' : 'user'
+ ): boolean => mutationPort.dispatch(action, origin);
// Direct pixel writes do not replace the reducer canvas object. Snapshot
// freshness therefore also binds to this engine-local content epoch.
let rasterContentEpoch = 0;
@@ -676,7 +686,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const structuralController = new StructuralLayerController({
canEdit: () => canEditDocument(),
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => dispatchCanvasMutation(action),
getDocument: () => mirror.getDocument(),
history,
isGestureActive: () => pipeline.isGestureActive(),
@@ -792,7 +802,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
bytes,
label,
redo: () => {
- mutationPort.dispatch({ index: created.index, layer: created.layer, type: 'addCanvasLayer' });
+ dispatchCanvasMutation({ index: created.index, layer: created.layer, type: 'addCanvasLayer' });
// Re-create an EMPTY cache marked fresh so the async rasterize pass can't
// clobber the restored stroke; `applyImagePatch` grows it to the stroke's
// content bounds and writes the `after` pixels.
@@ -801,7 +811,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
applyImagePatch(layerId, rect, afterImageData);
},
undo: () => {
- mutationPort.dispatch({ ids: [layerId], type: 'removeCanvasLayers' });
+ dispatchCanvasMutation({ ids: [layerId], type: 'removeCanvasLayers' });
},
};
};
@@ -817,6 +827,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// an undo/redo replay routes pixels through `applyImagePatch`, not a fresh
// stroke, so this never fires during apply — the guard is belt-and-braces.
if (!history.isApplying()) {
+ mutationPort.commitEdit({ kind: 'paint' });
const label = event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke';
history.push(
event.createdLayer
@@ -915,7 +926,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
transform: {
backend,
canEdit: () => canEditDocument(),
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => dispatchCanvasMutation(action),
endBurst: () => endNudgeBurst(),
getCache: (layerId) => layerCache.get(layerId) ?? null,
getDocument: () => mirror.getDocument(),
@@ -975,7 +986,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),
createLayerId,
createPath2D: createPath2DImpl,
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => dispatchCanvasMutation(action),
emitStrokeCommitted: (event) => commitOrdinaryStroke(event),
getDocument: () => mirror.getDocument(),
getSelectionMask: () => selection.mask(),
@@ -1280,8 +1291,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// Later-defined engine values (mirror, pipeline, prepared-cache helpers) are
// passed as thunks: the context never invokes them during construction.
const mutationContext = createCanvasMutationContext({
+ commitEdit: (intent) => mutationPort.commitEdit(intent),
createLayerId,
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action, origin) => dispatchCanvasMutation(action, origin),
editOwner: documentEditOwner,
editingLocked: stores.documentEditingLocked,
endBurst: () => endNudgeBurst(),
@@ -2928,7 +2940,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
canEdit: () => canEditDocument(),
deleteDerived: deleteDerivedSurfaces,
discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => dispatchCanvasMutation(action),
endBurst: () => endNudgeBurst(),
getDocument: () => mirror.getDocument(),
history,
@@ -2953,7 +2965,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
rasterize: {
backend,
canEdit: () => canEditDocument(),
- dispatch: (action) => mutationPort.dispatch(action),
+ dispatch: (action) => dispatchCanvasMutation(action),
endBurst: () => endNudgeBurst(),
getDocument: () => mirror.getDocument(),
history,
@@ -3327,7 +3339,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
replaceTemporaryRestoreTool: () => pipeline.replaceTemporaryRestoreTool('sam', 'view'),
selectLayer: (layerId) => {
if (mirror.getDocument()?.selectedLayerId !== layerId) {
- mutationPort.dispatch({ id: layerId, type: 'setCanvasSelectedLayer' });
+ dispatchCanvasMutation({ id: layerId, type: 'setCanvasSelectedLayer' });
}
},
setSamInputHandler: (handler) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
index ef67c63952..c748771166 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
@@ -45,6 +45,7 @@ const createFakeDeps = (): EngineDeps => {
backend: createTestStubRasterBackend(),
imageResolver: () => Promise.resolve(new Blob()),
mutationPort: {
+ commitEdit: () => undefined,
dispatch: (mutation) => {
const before = project.canvas;
project = applyCanvasProjectMutation(project, mutation);
@@ -311,6 +312,7 @@ describe('createEngineRegistry', () => {
});
const listeners = new Set<() => void>();
const mutationPort = {
+ commitEdit: () => undefined,
dispatch: (mutation: Parameters<typeof applyCanvasProjectMutation>[1]) => {
const before = project.canvas;
project = applyCanvasProjectMutation(project, mutation);
diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
index f6bc3ad167..1946c3400e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
@@ -131,7 +131,10 @@ export const reconcileCanvasDims = ({
/** The minimal workbench store surface the sync depends on. */
export interface CanvasDimsSyncStore {
- commands: Pick<WorkbenchCommands, 'canvas' | 'generation'>;
+ commands: {
+ canvas: Pick<WorkbenchCommands['canvas'], 'apply'>;
+ generation: Pick<WorkbenchCommands['generation'], 'patchSettings'>;
+ };
getState(): WorkbenchState;
subscribe(listener: () => void): () => void;
}
@@ -242,7 +245,7 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync
};
isSyncing = true;
try {
- store.commands.canvas.apply(project.id, { bbox: result.bbox, type: 'setCanvasBbox' });
+ store.commands.canvas.apply(project.id, { bbox: result.bbox, type: 'setCanvasBbox' }, 'system');
} finally {
isSyncing = false;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
index dc0f292545..ba60b05fd1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
@@ -243,3 +243,35 @@ describe('project-bound bitmap persistence', () => {
upload.bitmapStore.dispose();
});
});
+
+describe('Canvas edit intent', () => {
+ it('keeps system mutations from routing and routes a confirmed user edit', () => {
+ const store = createWorkbenchStore();
+ const projectId = store.getState().activeProjectId;
+ const port = createCanvasProjectMutationPort(store, projectId);
+
+ store.commands.generation.setSource('workflow');
+ port.dispatch({ bbox: { height: 768, width: 768, x: 0, y: 0 }, type: 'setCanvasBbox' }, 'system');
+
+ expect(store.queries.getProject(projectId)?.invocation.sourceId).toBe('workflow');
+
+ port.commitEdit({ kind: 'paint' });
+
+ expect(store.queries.getProject(projectId)?.invocation).toMatchObject({
+ destination: 'canvas',
+ sourceId: 'canvas',
+ });
+ });
+
+ it('keeps confirmed edits bound to the originating project', () => {
+ const store = createWorkbenchStore();
+ const originProjectId = store.getState().activeProjectId;
+ const port = createCanvasProjectMutationPort(store, originProjectId);
+ const otherProjectId = store.commands.projects.create().id;
+
+ port.commitEdit({ kind: 'paint' });
+
+ expect(store.queries.getProject(originProjectId)?.invocation.sourceId).toBe('canvas');
+ expect(store.queries.getProject(otherProjectId)?.invocation.sourceId).toBe('generate');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
index 76575afc3a..9664f35936 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
@@ -1,13 +1,15 @@
import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';
import type { WorkbenchState } from '@workbench/projectContracts';
+import type { CanvasEditIntent, WorkbenchActionOrigin } from './autoRoutePolicy';
import type { CanvasProjectMutation } from './canvasProjectMutations';
import type { WorkbenchCanvasCommands } from './workbenchStore';
export interface CanvasProjectMutationPort {
getCanvasState(): CanvasStateContractV2 | null;
subscribe(listener: () => void): () => void;
- dispatch(mutation: CanvasProjectMutation): boolean;
+ dispatch(mutation: CanvasProjectMutation, origin?: WorkbenchActionOrigin): boolean;
+ commitEdit(intent: CanvasEditIntent): void;
}
export const createCanvasProjectMutationPort = (
@@ -22,7 +24,8 @@ export const createCanvasProjectMutationPort = (
store.getState().projects.find((project) => project.id === projectId)?.canvas ?? null;
return {
- dispatch: (mutation) => store.commands.canvas.apply(projectId, mutation),
+ commitEdit: (intent) => store.commands.canvas.commitEdit(projectId, intent),
+ dispatch: (mutation, origin) => store.commands.canvas.apply(projectId, mutation, origin),
getCanvasState,
subscribe: store.subscribe,
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts
deleted file mode 100644
index 02c1452830..0000000000
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { CanvasProjectMutation } from './canvasProjectMutations';
-
-import { isHighConfidenceCanvasEdit } from './canvasProjectMutations';
-
-const mutation = (value: Record<string, unknown>): CanvasProjectMutation => value as never;
-
-describe('isHighConfidenceCanvasEdit', () => {
- it('counts content edits: layer add/source updates, bbox, and document resize', () => {
- expect(isHighConfidenceCanvasEdit(mutation({ type: 'addCanvasLayer' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ type: 'updateCanvasLayerSource' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ type: 'updateCanvasLayerConfig' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ type: 'setCanvasBbox' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ type: 'resizeCanvasDocument' }))).toBe(true);
- });
-
- it('counts layer patches only when they carry content intent', () => {
- expect(isHighConfidenceCanvasEdit(mutation({ patch: { transform: {} }, type: 'updateCanvasLayer' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ patch: { opacity: 0.5 }, type: 'updateCanvasLayer' }))).toBe(true);
- expect(isHighConfidenceCanvasEdit(mutation({ patch: { blendMode: 'multiply' }, type: 'updateCanvasLayer' }))).toBe(
- true
- );
- expect(
- isHighConfidenceCanvasEdit(mutation({ patch: { isLocked: true, name: 'Layer 1' }, type: 'updateCanvasLayer' }))
- ).toBe(false);
- });
-
- it('ignores selection, visibility, staging review, snapshots, and hydration', () => {
- const excluded: string[] = [
- 'applyCanvasLayerStackMutation',
- 'commitStagedImage',
- 'setCanvasSelectedLayer',
- 'setCanvasLayersEnabled',
- 'setStagedImageIndex',
- 'cycleStagedImage',
- 'discardSelectedStagedImage',
- 'discardAllStagedImages',
- 'clearCanvasStaging',
- 'toggleCanvasStagingVisibility',
- 'toggleCanvasStagingThumbnailsVisibility',
- 'setCanvasStagingAutoSwitch',
- 'rollbackStagedImageCommit',
- 'saveCanvasSnapshot',
- 'restoreCanvasSnapshot',
- 'deleteCanvasSnapshot',
- 'replaceCanvasDocument',
- ];
-
- for (const type of excluded) {
- expect(isHighConfidenceCanvasEdit(mutation({ type }))).toBe(false);
- }
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index ebdcc4cb1b..d111849a9d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -136,45 +136,6 @@ const CANVAS_PROJECT_MUTATION_TYPES: ReadonlySet<string> = new Set<CanvasProject
export const isCanvasProjectMutation = (value: { type: string }): value is CanvasProjectMutation =>
CANVAS_PROJECT_MUTATION_TYPES.has(value.type);
-/**
- * Mutations that count as deliberate canvas content edits for auto-switching
- * the Invoke route. Selection, visibility, staging review/navigation
- * (including accepting a staged image — the terminal review act, whose failed
- * mirror acceptance must roll the project back exactly), snapshot management,
- * and document hydration are excluded — they express review or bookkeeping,
- * not editing intent. `applyCanvasLayerStackMutation` is excluded because the
- * engine dispatches the same type for both forward ops (merge/copy/extract)
- * and their exact-compensation rollbacks; a route flip there would break
- * transactional restore invariants, and those flows are accompanied by other
- * high-confidence gestures in practice.
- */
-const HIGH_CONFIDENCE_CANVAS_MUTATION_TYPES: ReadonlySet<CanvasProjectMutation['type']> = new Set<
- CanvasProjectMutation['type']
->([
- 'addCanvasLayer',
- 'convertCanvasLayer',
- 'duplicateCanvasLayer',
- 'mergeCanvasLayersDown',
- 'removeCanvasLayers',
- 'reorderCanvasLayers',
- 'replaceCanvasLayer',
- 'resizeCanvasDocument',
- 'setCanvasBbox',
- 'updateCanvasLayerConfig',
- 'updateCanvasLayerSource',
-]);
-
-/** Layer patch keys that carry content intent (move/transform/composite), unlike rename or lock toggles. */
-const CONTENT_BEARING_LAYER_PATCH_KEYS = ['transform', 'opacity', 'blendMode'] as const;
-
-export const isHighConfidenceCanvasEdit = (mutation: CanvasProjectMutation): boolean => {
- if (mutation.type === 'updateCanvasLayer') {
- return CONTENT_BEARING_LAYER_PATCH_KEYS.some((key) => key in mutation.patch);
- }
-
- return HIGH_CONFIDENCE_CANVAS_MUTATION_TYPES.has(mutation.type);
-};
-
type CanvasLayers = CanvasDocumentContractV2['layers'];
const layerExists = (layers: CanvasLayers, id: string): boolean => layers.some((layer) => layer.id === id);
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index fa8eff301b..effd312322 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -14,9 +14,8 @@ import { createDefaultUpscaleWidgetValues } from '@features/upscale';
import { describe, expect, it, vi } from 'vitest';
import {
- autoSwitchDestinations,
+ areInvocationRouteInputsEqual,
getInvocationRouteInput,
- getRouteAfterHighConfidenceEdit,
resolveInvocationRoute,
resolveInvocationRouteInput,
} from './invocation';
@@ -322,47 +321,3 @@ describe('submitResolvedInvocation', () => {
});
});
});
-
-describe('getRouteAfterHighConfidenceEdit', () => {
- const route = (overrides: Partial<InvocationRoute> = {}): InvocationRoute => ({
- destination: 'canvas',
- destinationLocked: false,
- sourceId: 'generate',
- sourceLocked: false,
- ...overrides,
- });
-
- it('switches the source and remaps the destination per the auto-switch mapping', () => {
- expect(getRouteAfterHighConfidenceEdit(route(), 'workflow')).toEqual(
- route({ destination: 'gallery', sourceId: 'workflow' })
- );
- expect(getRouteAfterHighConfidenceEdit(route(), 'upscale')).toEqual(
- route({ destination: 'gallery', sourceId: 'upscale' })
- );
- expect(getRouteAfterHighConfidenceEdit(route({ destination: 'gallery' }), 'canvas')).toEqual(
- route({ destination: 'canvas', sourceId: 'canvas' })
- );
- });
-
- it('covers every source in the destination mapping', () => {
- expect(Object.keys(autoSwitchDestinations).sort()).toEqual(['canvas', 'generate', 'upscale', 'workflow']);
- });
-
- it('is an identity no-op when the source is unchanged, preserving a manual destination', () => {
- const gallerySameSource = route({ destination: 'gallery' });
-
- expect(getRouteAfterHighConfidenceEdit(gallerySameSource, 'generate')).toBe(gallerySameSource);
- });
-
- it('does nothing when the source is locked', () => {
- const locked = route({ sourceLocked: true });
-
- expect(getRouteAfterHighConfidenceEdit(locked, 'canvas')).toBe(locked);
- });
-
- it('switches only the source when the destination is locked', () => {
- expect(getRouteAfterHighConfidenceEdit(route({ destinationLocked: true }), 'workflow')).toEqual(
- route({ destinationLocked: true, sourceId: 'workflow' })
- );
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index ed8ecc9c9b..77914603f3 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -75,33 +75,6 @@ export const defaultInvocationRoute: InvocationRoute = {
destinationLocked: false,
};
-/** Destination each surface maps to when the source auto-switches. */
-export const autoSwitchDestinations: Record<InvocationSourceId, ResultDestination> = {
- canvas: 'canvas',
- generate: 'gallery',
- upscale: 'gallery',
- workflow: 'gallery',
-};
-
-/**
- * Route after a high-confidence edit on `sourceId`; identity-preserving when
- * nothing changes. The destination remaps only on an actual source transition,
- * so repeated edits on the same surface never re-force a manually chosen
- * destination, and locks always win.
- */
-export const getRouteAfterHighConfidenceEdit = (
- invocation: InvocationRoute,
- sourceId: InvocationSourceId
-): InvocationRoute => {
- if (invocation.sourceLocked || invocation.sourceId === sourceId || !isInvocationSourceAvailable(sourceId)) {
- return invocation;
- }
-
- const destination = invocation.destinationLocked ? invocation.destination : autoSwitchDestinations[sourceId];
-
- return { ...invocation, destination, sourceId };
-};
-
const validDestinationIds = new Set(resultDestinations.map((destination) => destination.id));
const sourceWidgetIds: Partial<Record<InvocationSourceId, WidgetId>> = {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
index 1e5cc11b54..57831d514c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
@@ -76,6 +76,7 @@ const createTrackedRoot = (host: HTMLDivElement) => {
const createEngineDeps = (state: CanvasStateContractV2): EngineDeps => {
const listeners = new Set<() => void>();
const mutationPort: CanvasProjectMutationPort = {
+ commitEdit: () => undefined,
dispatch: () => false,
getCanvasState: () => state,
subscribe: (listener) => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 91ae6df7d6..ef4368af6c 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -1477,6 +1477,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, { type: 'undoProjectChange' });
expect(getActiveProject(state).projectGraph.nodes).toHaveLength(0);
+ expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
});
it('replaceProjectGraph snapshots the previous document into graph history', () => {
@@ -1492,6 +1493,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const project = getActiveProject(state);
expect(project.projectGraph.id).toBe('replacement-graph');
+ expect(project.invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
expect(project.graphHistory[0]?.document?.id).toBe(originalGraphId);
expect(project.graphHistory[0]?.retainedBytes).toBeGreaterThan(0);
expect(project.graphHistory[0]?.document).toBe(project.undoRedo.past.at(-1)?.project.projectGraph);
@@ -1502,6 +1504,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);
+ expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
});
it('keeps the newest graph-history entries within the count limit and recomputes retained bytes', () => {
@@ -1659,6 +1662,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const state = createInitialWorkbenchState();
const beforeUpscale = getProjectWidgetValues(getActiveProject(state), 'upscale');
const nextState = workbenchReducer(state, {
+ sourceId: 'upscale',
type: 'patchProjectPromptDraft',
values: { negativePrompt: 'blur', negativePromptEnabled: false, positivePrompt: 'fine detail' },
});
@@ -3445,6 +3449,7 @@ describe('auto invocation route switching', () => {
let promptState = createInitialWorkbenchState();
promptState = workbenchReducer(promptState, {
+ sourceId: 'upscale',
type: 'patchProjectPromptDraft',
values: { positivePrompt: 'crisp detail' },
});
@@ -3485,6 +3490,73 @@ describe('auto invocation route switching', () => {
expect(getRoute(edited)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });
});
+ it('switches to Canvas for structural and visibility edits', () => {
+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);
+
+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
+ state = workbenchReducer(state, {
+ add: { index: 1, layers: [createRasterLayer('b')] },
+ enabledUpdates: [],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ });
+
+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });
+
+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
+ state = workbenchReducer(state, {
+ type: 'setCanvasLayersEnabled',
+ updates: [{ id: 'a', isEnabled: false }],
+ });
+
+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });
+ });
+
+ it('routes confirmed paint intents but ignores system Canvas mutations', () => {
+ let state = createInitialWorkbenchState();
+
+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
+ state = reduceWorkbench(state, {
+ intent: { kind: 'paint' },
+ projectId: state.activeProjectId,
+ type: 'commitCanvasEdit',
+ });
+
+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });
+
+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
+ state = reduceWorkbench(state, {
+ mutation: { bbox: { height: 768, width: 768, x: 0, y: 0 }, type: 'setCanvasBbox' },
+ origin: 'system',
+ projectId: state.activeProjectId,
+ type: 'applyCanvasProjectMutation',
+ });
+
+ expect(getRoute(state).sourceId).toBe('workflow');
+ });
+
+ it('uses the explicit source on shared prompt edits', () => {
+ let state = createInitialWorkbenchState();
+
+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
+ state = workbenchReducer(state, {
+ sourceId: 'generate',
+ type: 'patchProjectPromptDraft',
+ values: { positivePrompt: 'generate prompt' },
+ });
+
+ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'generate' });
+
+ state = workbenchReducer(state, { sourceId: 'canvas', type: 'setInvocationSource' });
+ state = workbenchReducer(state, {
+ sourceId: 'generate',
+ type: 'patchProjectPromptDraft',
+ values: { positivePrompt: 'canvas parameter prompt' },
+ });
+
+ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'canvas' });
+ });
+
it('never lets generate edits steal the route from an active canvas source', () => {
let state = createInitialWorkbenchState();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts
index 47a066c33b..2622a9ccb8 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts
@@ -5,9 +5,23 @@
* separate makes reducer coupling visible and lets those tests be retired as
* command-level coverage replaces them.
*/
-export {
- __workbenchReducerInternal as workbenchReducer,
+import type { WorkbenchState } from '@workbench/projectContracts';
+
+import {
createInitialWorkbenchState,
+ __workbenchReducerInternal,
nextLayerName,
+ type __WorkbenchReducerActionInternal,
+ type WorkbenchReducerContext,
} from './workbenchState';
-export type { __WorkbenchReducerActionInternal as WorkbenchAction } from './workbenchState';
+
+const DEFAULT_TEST_CONTEXT: WorkbenchReducerContext = { autoSwitchInvocationRoute: true };
+
+export const workbenchReducer = (
+ state: WorkbenchState,
+ action: __WorkbenchReducerActionInternal,
+ context: WorkbenchReducerContext = DEFAULT_TEST_CONTEXT
+): WorkbenchState => __workbenchReducerInternal(state, action, context);
+
+export { createInitialWorkbenchState, nextLayerName };
+export type { __WorkbenchReducerActionInternal as WorkbenchAction, WorkbenchReducerContext };
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index ab2ff47ba8..50e6487238 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -49,12 +49,19 @@ import {
import type { WorkbenchQueueItem as QueueItem } from './queueHistoryContracts';
-import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';
import {
- applyCanvasProjectMutation,
- type CanvasProjectMutation,
+ getChangedValueKeys,
+ getRouteAfterHighConfidenceEdit,
isHighConfidenceCanvasEdit,
-} from './canvasProjectMutations';
+ isHighConfidenceCanvasEditIntent,
+ isHighConfidenceGenerateEdit,
+ isHighConfidenceGraphEdit,
+ isHighConfidenceUpscaleEdit,
+ type CanvasEditIntent,
+ type WorkbenchActionOrigin,
+} from './autoRoutePolicy';
+import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';
+import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';
import { getProjectWidgetValues } from './widgetState';
export { nextLayerName } from './canvasProjectMutations';
import { compileGenerateGraph, resolveGenerateSeed } from '@features/generation/graph';
@@ -65,7 +72,6 @@ import {
getGenerationModelAvailabilityReasons,
getPromptDraftFromValues,
getPromptHistoryItemFromGenerateSettings,
- isHighConfidenceGenerateEdit,
migrateProjectPromptDraft,
normalizeGenerateSettings,
normalizeGenerateWidgetValues,
@@ -80,7 +86,6 @@ import {
compileUpscaleGraph,
getUpscaleOutputDimensions,
getUpscaleValidationReasons,
- isHighConfidenceUpscaleEdit,
normalizeUpscaleWidgetValues,
resolveUpscaleSeed,
syncUpscaleWidgetValuesWithModels,
@@ -92,7 +97,6 @@ import {
cloneProjectGraph,
createProjectGraph,
getProjectGraphUndoLabel,
- isHighConfidenceGraphEdit,
normalizeProjectGraph,
projectGraphReducer,
type ProjectGraphAction,
@@ -105,7 +109,6 @@ import {
} from './canvasStagingView';
import {
defaultInvocationRoute,
- getRouteAfterHighConfidenceEdit,
isInvocationRouteValid,
isInvocationSourceAvailable,
resolveInvocationRoute,
@@ -113,12 +116,13 @@ import {
import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';
import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';
import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';
-import { getWorkbenchPreferences, normalizeProjectSettings } from './settings/store';
+import { normalizeProjectSettings } from './settings/store';
type QueueGenerateSnapshot = NonNullable<QueueItem['snapshot']['generate']>;
-/** Programmatic dispatches (`'system'`) never auto-switch the Invoke route; absent means `'user'`. */
-export type WorkbenchActionOrigin = 'user' | 'system';
+export interface WorkbenchReducerContext {
+ autoSwitchInvocationRoute: boolean;
+}
type WorkbenchReducerAction =
| { type: 'createProject' }
@@ -169,7 +173,13 @@ type WorkbenchReducerAction =
projectId?: string;
origin?: WorkbenchActionOrigin;
}
- | { type: 'patchProjectPromptDraft'; values: ProjectPromptDraftPatch; projectId?: string }
+ | {
+ type: 'patchProjectPromptDraft';
+ values: ProjectPromptDraftPatch;
+ sourceId: 'generate' | 'upscale';
+ projectId?: string;
+ origin?: WorkbenchActionOrigin;
+ }
| { type: 'setGenerateBatchCount'; batchCount: number; projectId?: string }
| { type: 'addPromptToHistory'; prompt: PromptHistoryItem; projectId?: string }
| { type: 'removePromptFromHistory'; prompt: PromptHistoryItem; projectId?: string }
@@ -244,7 +254,13 @@ type WorkbenchReducerAction =
| { type: 'touchGalleryImagesRefresh'; projectId?: string }
| { type: 'removeGalleryImages'; imageNames: string[]; projectId?: string }
| { type: 'setGalleryProjectBoardId'; boardId: string; projectId?: string }
- | { type: 'applyCanvasProjectMutation'; projectId: string; mutation: CanvasProjectMutation }
+ | {
+ type: 'applyCanvasProjectMutation';
+ projectId: string;
+ mutation: CanvasProjectMutation;
+ origin?: WorkbenchActionOrigin;
+ }
+ | { type: 'commitCanvasEdit'; projectId: string; intent: CanvasEditIntent }
| {
type: 'submitCanvasInvocationSnapshot';
backendSupportsCancellation: boolean;
@@ -1515,8 +1531,12 @@ const updateActiveInvocation = (
* edit. Deliberately no undo entry or event: the route change rides the
* edit's own project update, matching the workflow auto-source precedent.
*/
-const applyAutoRouteForEdit = (project: Project, sourceId: InvocationSourceId): Project => {
- if (!getWorkbenchPreferences().autoSwitchInvocationRoute) {
+const applyAutoRouteForEdit = (
+ project: Project,
+ sourceId: InvocationSourceId,
+ context: WorkbenchReducerContext
+): Project => {
+ if (!context.autoSwitchInvocationRoute) {
return project;
}
@@ -1531,11 +1551,8 @@ const applyAutoRouteForEdit = (project: Project, sourceId: InvocationSourceId):
* mirrors generate dims onto the bbox — so generate edits never steal the
* route from an active canvas source.
*/
-const applyAutoRouteForGenerateEdit = (project: Project): Project =>
- project.invocation.sourceId === 'canvas' ? project : applyAutoRouteForEdit(project, 'generate');
-
-const getChangedValueKeys = (previous: Record<string, unknown>, patch: Record<string, unknown>): string[] =>
- Object.keys(patch).filter((key) => !Object.is(previous[key], patch[key]));
+const applyAutoRouteForGenerateEdit = (project: Project, context: WorkbenchReducerContext): Project =>
+ project.invocation.sourceId === 'canvas' ? project : applyAutoRouteForEdit(project, 'generate', context);
const compileInvocationSnapshot = (
project: Project,
@@ -2007,7 +2024,11 @@ export const createInitialWorkbenchState = (): WorkbenchState => {
};
};
-export const __workbenchReducerInternal = (state: WorkbenchState, action: WorkbenchReducerAction): WorkbenchState => {
+export const __workbenchReducerInternal = (
+ state: WorkbenchState,
+ action: WorkbenchReducerAction,
+ context: WorkbenchReducerContext
+): WorkbenchState => {
switch (action.type) {
case 'createProject': {
const project = createDraftProject(state.projects);
@@ -2312,7 +2333,9 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
const updated = updateProjectWidgetValues(project, 'generate', () => cloneGenerateWidgetValues(action.values));
// Whole-values commits come from model selection/recall — always intent-bearing.
- return updated === project || action.origin === 'system' ? updated : applyAutoRouteForGenerateEdit(updated);
+ return updated === project || action.origin === 'system'
+ ? updated
+ : applyAutoRouteForGenerateEdit(updated, context);
});
}
case 'patchGenerateSettings': {
@@ -2325,7 +2348,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
const changedKeys = getChangedValueKeys(getProjectWidgetValues(project, 'generate'), action.values);
- return isHighConfidenceGenerateEdit(changedKeys) ? applyAutoRouteForGenerateEdit(updated) : updated;
+ return isHighConfidenceGenerateEdit(changedKeys) ? applyAutoRouteForGenerateEdit(updated, context) : updated;
});
}
case 'patchProjectPromptDraft': {
@@ -2334,9 +2357,13 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
applyProjectPromptDraft(values, action.values)
);
- // Only the upscale widget's prompt fields dispatch this action today;
- // needs a source discriminator if Generate ever adopts the shared draft.
- return updated === project ? updated : applyAutoRouteForEdit(updated, 'upscale');
+ if (updated === project || action.origin === 'system') {
+ return updated;
+ }
+
+ return action.sourceId === 'generate'
+ ? applyAutoRouteForGenerateEdit(updated, context)
+ : applyAutoRouteForEdit(updated, 'upscale', context);
});
}
case 'setGenerateBatchCount': {
@@ -2380,10 +2407,10 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
const changedKeys = getChangedValueKeys(getProjectWidgetValues(project, action.widgetId), action.values);
if (action.widgetId === 'generate' && isHighConfidenceGenerateEdit(changedKeys)) {
- return applyAutoRouteForGenerateEdit(updated);
+ return applyAutoRouteForGenerateEdit(updated, context);
}
if (action.widgetId === 'upscale' && isHighConfidenceUpscaleEdit(changedKeys)) {
- return applyAutoRouteForEdit(updated, 'upscale');
+ return applyAutoRouteForEdit(updated, 'upscale', context);
}
return updated;
@@ -2413,13 +2440,14 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
return project;
}
+ const routedProject = isHighConfidenceGraphEdit(action.action)
+ ? applyAutoRouteForEdit(project, 'workflow', context)
+ : project;
const undoLabel = getProjectGraphUndoLabel(action.action);
- const nextProject = undoLabel ? pushUndo(project, undoLabel) : project;
- // Meaningful workflow edits are high-confidence source events that
- // steer the global Invoke route to the project graph.
+ const nextProject = undoLabel ? pushUndo(routedProject, undoLabel) : routedProject;
const updated = { ...nextProject, projectGraph };
- return isHighConfidenceGraphEdit(action.action) ? applyAutoRouteForEdit(updated, 'workflow') : updated;
+ return updated;
});
}
case 'replaceProjectGraph': {
@@ -2427,8 +2455,9 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
const nextState = updateActiveProject(state, (project) => {
// One immutable clone is shared by undo and graph history; neither
// snapshot path mutates the document.
+ const routedProject = applyAutoRouteForEdit(project, 'workflow', context);
const outgoingGraph = cloneProjectGraph(project.projectGraph);
- const nextProject = pushUndo(project, 'Replace project graph', outgoingGraph);
+ const nextProject = pushUndo(routedProject, 'Replace project graph', outgoingGraph);
const historySnapshot = createDocumentHistorySnapshot(`Before: ${action.label}`, outgoingGraph, false);
didRetainOutgoingGraph = (historySnapshot.retainedBytes ?? 0) <= GRAPH_HISTORY_BYTE_BUDGET;
@@ -2490,7 +2519,8 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
return project;
}
- const nextProject = pushUndo(project, 'Restore graph history snapshot');
+ const routedProject = applyAutoRouteForEdit(project, 'workflow', context);
+ const nextProject = pushUndo(routedProject, 'Restore graph history snapshot');
return {
...nextProject,
@@ -2854,11 +2884,18 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
return updateProjectById(state, action.projectId, (project) => {
const updated = applyCanvasProjectMutation(project, action.mutation);
- return updated !== project && isHighConfidenceCanvasEdit(action.mutation)
- ? applyAutoRouteForEdit(updated, 'canvas')
+ return updated !== project && action.origin !== 'system' && isHighConfidenceCanvasEdit(action.mutation)
+ ? applyAutoRouteForEdit(updated, 'canvas', context)
: updated;
});
}
+ case 'commitCanvasEdit': {
+ if (!isHighConfidenceCanvasEditIntent(action.intent)) {
+ return state;
+ }
+
+ return updateProjectById(state, action.projectId, (project) => applyAutoRouteForEdit(project, 'canvas', context));
+ }
case 'submitCanvasInvocationSnapshot': {
return updateProjectById(state, action.projectId, (project) =>
enqueueCompiledSnapshot(
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
index 5856f0e2f6..c435ae891b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
@@ -1,57 +1,99 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import type * as settingsStore from './settings/store';
+import { describe, expect, it } from 'vitest';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
-/**
- * With the autoSwitchInvocationRoute preference off, no surface edit — not
- * even the pre-existing workflow rule — may steer the Invoke route. The
- * default-on behavior is covered in workbenchState.test.ts, whose un-hydrated
- * store resolves to DEFAULT_PREFERENCES.
- */
-
-vi.mock('./settings/store', async (importOriginal) => {
- const original = await importOriginal<typeof settingsStore>();
-
- return {
- ...original,
- getWorkbenchPreferences: () => ({ ...original.DEFAULT_PREFERENCES, autoSwitchInvocationRoute: false }),
- };
-});
+const preferenceOff = { autoSwitchInvocationRoute: false };
describe('auto invocation route switching with the preference off', () => {
- it('leaves the route alone for workflow, generate, and canvas edits', () => {
+ it('leaves the route alone for workflow, generate, upscale, and Canvas edits', () => {
let state = createInitialWorkbenchState();
- state = workbenchReducer(state, {
- action: {
- node: {
- data: {
- inputs: {},
- isIntermediate: true,
- isOpen: true,
- label: '',
- nodePack: 'invokeai',
- notes: '',
- type: 'add',
- useCache: true,
- version: '1.0.0',
+ state = workbenchReducer(
+ state,
+ {
+ action: {
+ node: {
+ data: {
+ inputs: {},
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type: 'add',
+ useCache: true,
+ version: '1.0.0',
+ },
+ id: 'node-1',
+ position: { x: 0, y: 0 },
+ type: 'invocation',
},
- id: 'node-1',
- position: { x: 0, y: 0 },
- type: 'invocation',
+ type: 'addNode',
+ },
+ type: 'applyProjectGraphAction',
+ },
+ preferenceOff
+ );
+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } }, preferenceOff);
+ state = workbenchReducer(
+ state,
+ {
+ type: 'patchWidgetValues',
+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },
+ widgetId: 'upscale',
+ },
+ preferenceOff
+ );
+ state = workbenchReducer(
+ state,
+ {
+ sourceId: 'upscale',
+ type: 'patchProjectPromptDraft',
+ values: { positivePrompt: 'shared prompt' },
+ },
+ preferenceOff
+ );
+ state = workbenchReducer(
+ state,
+ {
+ mutation: {
+ bbox: { height: 768, width: 768, x: 0, y: 0 },
+ type: 'setCanvasBbox',
},
- type: 'addNode',
+ projectId: state.activeProjectId,
+ type: 'applyCanvasProjectMutation',
+ },
+ preferenceOff
+ );
+ state = workbenchReducer(state, { type: 'saveProjectGraphSnapshot' }, preferenceOff);
+ const snapshotId = state.projects.find((project) => project.id === state.activeProjectId)?.graphHistory[0]?.id;
+ const projectGraph = state.projects.find((project) => project.id === state.activeProjectId)?.projectGraph;
+
+ expect(projectGraph).toBeDefined();
+
+ state = workbenchReducer(
+ state,
+ {
+ document: { ...projectGraph!, id: 'replacement-graph' },
+ label: 'Preference-off replacement',
+ type: 'replaceProjectGraph',
+ },
+ preferenceOff
+ );
+ state = workbenchReducer(
+ state,
+ { snapshotId: snapshotId ?? '', type: 'restoreProjectGraphSnapshot' },
+ preferenceOff
+ );
+ state = workbenchReducer(
+ state,
+ {
+ intent: { kind: 'paint' },
+ projectId: state.activeProjectId,
+ type: 'commitCanvasEdit',
},
- type: 'applyProjectGraphAction',
- });
- state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });
- state = workbenchReducer(state, {
- type: 'patchWidgetValues',
- values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },
- widgetId: 'upscale',
- });
+ preferenceOff
+ );
const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index 8b1ad70552..d85ef774d8 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -3,9 +3,11 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { createExternalStore } from '@platform/state/externalStore';
+import type { CanvasEditIntent } from './autoRoutePolicy';
import type { CanvasProjectMutation } from './canvasProjectMutations';
import { recordDiagnosticEntry } from './diagnostics/logger';
+import { getWorkbenchPreferences } from './settings/store';
import {
createInitialWorkbenchState,
__workbenchReducerInternal,
@@ -59,15 +61,21 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt
),
},
canvas: {
- apply: (projectId: string, mutation: CanvasProjectMutation): boolean => {
+ apply: (
+ projectId: string,
+ mutation: CanvasProjectMutation,
+ origin?: ActionPayload<'applyCanvasProjectMutation'>['origin']
+ ): boolean => {
const before = getState().projects.find((project) => project.id === projectId)?.canvas;
if (!before) {
return false;
}
- dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' });
+ dispatch({ mutation, origin, projectId, type: 'applyCanvasProjectMutation' });
return getState().projects.find((project) => project.id === projectId)?.canvas !== before;
},
+ commitEdit: (projectId: string, intent: CanvasEditIntent): void =>
+ dispatch({ intent, projectId, type: 'commitCanvasEdit' }),
appendStagingCandidate: command('appendCanvasStagingCandidate'),
},
gallery: {
@@ -133,7 +141,12 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt
clearPromptHistory: command('clearPromptHistory', (projectId?: string) => ({ projectId })),
patchPromptDraft: command(
'patchProjectPromptDraft',
- (values: ActionPayload<'patchProjectPromptDraft'>['values'], projectId?: string) => ({ projectId, values })
+ (
+ values: ActionPayload<'patchProjectPromptDraft'>['values'],
+ sourceId: ActionPayload<'patchProjectPromptDraft'>['sourceId'],
+ projectId?: string,
+ origin?: ActionPayload<'patchProjectPromptDraft'>['origin']
+ ) => ({ origin, projectId, sourceId, values })
),
patchSettings: command(
'patchGenerateSettings',
@@ -494,7 +507,9 @@ export const createWorkbenchStore = (initialState = createInitialWorkbenchState(
const dispatch = (action: WorkbenchAction): void => {
const previousState = state;
- const nextState = __workbenchReducerInternal(state, action);
+ const nextState = __workbenchReducerInternal(state, action, {
+ autoSwitchInvocationRoute: getWorkbenchPreferences().autoSwitchInvocationRoute,
+ });
setSnapshotState(nextState);
recordDiagnosticForAction(action, previousState, nextState);