Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): auto-switch invoke route on high-confidence edits
joshistoast09559f6b7cbb
diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 4878a7e853..eff7c34ea0 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -341,6 +341,9 @@ describe('createCanvasDimsSync (wiring)', () => {it('stays inert when the project is not invoking into the canvas', () => {const store = createWorkbenchStore();store.commands.generation.setSource('generate');+ // Lock the source: a bbox drag is itself a canvas intent signal and would+ // otherwise auto-route the project into canvas mode.+ store.commands.generation.toggleSourceLock();store.commands.generation.patchSettings({ height: 1024, model, modelKey: model.key, width: 1024 });let syncDispatches = 0;diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.tsindex 4be0291689..02c1452830 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.test.ts@@ -1,7 +1,7 @@-import type { CanvasProjectMutation } from './canvasProjectMutations';-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;@@ -11,7 +11,6 @@ describe('isHighConfidenceCanvasEdit', () => {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: 'commitStagedImage' }))).toBe(true);expect(isHighConfidenceCanvasEdit(mutation({ type: 'setCanvasBbox' }))).toBe(true);expect(isHighConfidenceCanvasEdit(mutation({ type: 'resizeCanvasDocument' }))).toBe(true);});@@ -29,6 +28,8 @@ describe('isHighConfidenceCanvasEdit', () => {it('ignores selection, visibility, staging review, snapshots, and hydration', () => {const excluded: string[] = [+ 'applyCanvasLayerStackMutation',+ 'commitStagedImage','setCanvasSelectedLayer','setCanvasLayersEnabled','setStagedImageIndex',diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex a8e8d2e123..ebdcc4cb1b 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -138,18 +138,20 @@ export const isCanvasProjectMutation = (value: { type: string }): value is Canva/*** Mutations that count as deliberate canvas content edits for auto-switching- * the Invoke route. Selection, visibility, staging review/navigation, snapshot- * management, and document hydration are excluded — they express review or- * bookkeeping, not editing intent. `applyCanvasLayerStackMutation` also fires- * on rare error-rollback paths (staged-result commit failures); that false- * positive is accepted rather than threading an origin through the engine.+ * 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',- 'applyCanvasLayerStackMutation',- 'commitStagedImage','convertCanvasLayer','duplicateCanvasLayer','mergeCanvasLayersDown',diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex deb021f2ec..91ae6df7d6 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1468,10 +1468,11 @@ describe('workbenchReducer Phase 5 generation flow', () => {const project = getActiveProject(state);// A meaningful graph edit lands in the document, creates an undo entry,- // and steers the unlocked invocation source to the project graph.+ // and steers the unlocked invocation route to the project graph.expect(project.projectGraph.nodes).toHaveLength(1);expect(project.undoRedo.past.at(-1)?.label).toBe('Add workflow node');expect(project.invocation.sourceId).toBe('workflow');+ expect(project.invocation.destination).toBe('gallery');state = workbenchReducer(state, { type: 'undoProjectChange' });@@ -3396,3 +3397,142 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =expect(state).toBe(initial);});});++describe('auto invocation route switching', () => {+ const getRoute = (state: WorkbenchState) => getActiveProject(state).invocation;++ it('switches to generate with a gallery destination on a high-confidence settings patch', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'generate' });+ });++ it('ignores noise-only generate patches and system-originated patches', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ const noiseOnly = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePromptHeightPx: 120 },+ });++ expect(getRoute(noiseOnly).sourceId).toBe('workflow');++ const systemOriginated = workbenchReducer(state, {+ origin: 'system',+ type: 'patchGenerateSettings',+ values: { steps: 25 },+ });++ expect(getRoute(systemOriginated).sourceId).toBe('workflow');+ });++ it('switches to upscale on widget-value edits and shared prompt draft edits', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'upscale' });++ let promptState = createInitialWorkbenchState();++ promptState = workbenchReducer(promptState, {+ type: 'patchProjectPromptDraft',+ values: { positivePrompt: 'crisp detail' },+ });++ expect(getRoute(promptState)).toMatchObject({ destination: 'gallery', sourceId: 'upscale' });+ });++ it('ignores system-originated and non-graph-bearing widget-value patches', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ origin: 'system',+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { selectedImageName: 'result.png' },+ widgetId: 'gallery',+ });++ expect(getRoute(state).sourceId).toBe('generate');+ });++ it('switches to canvas with a canvas destination on content mutations but not selection', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ const selected = workbenchReducer(state, { id: 'a', type: 'setCanvasSelectedLayer' });++ expect(getRoute(selected)).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });++ const edited = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });++ expect(getRoute(edited)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });+ });++ it('never lets generate edits steal the route from an active canvas source', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'canvas', type: 'setInvocationSource' });+ // Canvas compiles from generate values, so the generate panel is also the+ // canvas parameter panel — editing it expresses canvas intent here.+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });+ state = workbenchReducer(state, { type: 'setGenerateSettings', values: createGenerateValues() });++ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });+ });++ it('respects the source and destination locks', () => {+ let sourceLockedState = createInitialWorkbenchState();++ sourceLockedState = workbenchReducer(sourceLockedState, { type: 'toggleSourceLock' });+ sourceLockedState = workbenchReducer(sourceLockedState, {+ layer: createRasterLayer('a'),+ type: 'addCanvasLayer',+ });++ expect(getRoute(sourceLockedState)).toMatchObject({ destination: 'canvas', sourceId: 'generate' });++ let destinationLockedState = createInitialWorkbenchState();++ destinationLockedState = workbenchReducer(destinationLockedState, { type: 'toggleDestinationLock' });+ destinationLockedState = workbenchReducer(destinationLockedState, {+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });++ expect(getRoute(destinationLockedState)).toMatchObject({ destination: 'canvas', sourceId: 'upscale' });+ });++ it('never remaps the destination on a manual source change or a same-source edit', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ // The dropdown is the strongest intent signal: destination stays put.+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'workflow' });++ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });+ state = workbenchReducer(state, { destination: 'canvas', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 30 } });++ // Editing the surface already routed as the source keeps the manual destination.+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'generate' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 8ba7c90eea..ab2ff47ba8 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -50,7 +50,11 @@ import {import type { WorkbenchQueueItem as QueueItem } from './queueHistoryContracts';import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';-import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';+import {+ applyCanvasProjectMutation,+ type CanvasProjectMutation,+ isHighConfidenceCanvasEdit,+} from './canvasProjectMutations';import { getProjectWidgetValues } from './widgetState';export { nextLayerName } from './canvasProjectMutations';import { compileGenerateGraph, resolveGenerateSeed } from '@features/generation/graph';@@ -61,6 +65,7 @@ import {getGenerationModelAvailabilityReasons,getPromptDraftFromValues,getPromptHistoryItemFromGenerateSettings,+ isHighConfidenceGenerateEdit,migrateProjectPromptDraft,normalizeGenerateSettings,normalizeGenerateWidgetValues,@@ -75,6 +80,7 @@ import {compileUpscaleGraph,getUpscaleOutputDimensions,getUpscaleValidationReasons,+ isHighConfidenceUpscaleEdit,normalizeUpscaleWidgetValues,resolveUpscaleSeed,syncUpscaleWidgetValuesWithModels,@@ -99,6 +105,7 @@ import {} from './canvasStagingView';import {defaultInvocationRoute,+ getRouteAfterHighConfidenceEdit,isInvocationRouteValid,isInvocationSourceAvailable,resolveInvocationRoute,@@ -106,7 +113,7 @@ import {import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';-import { normalizeProjectSettings } from './settings/store';+import { getWorkbenchPreferences, normalizeProjectSettings } from './settings/store';type QueueGenerateSnapshot = NonNullable<QueueItem['snapshot']['generate']>;@@ -1503,6 +1510,33 @@ const updateActiveInvocation = (};});+/**+ * Applies the auto-switch route rule to a project after a high-confidence+ * 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) {+ return project;+ }++ const invocation = getRouteAfterHighConfidenceEdit(project.invocation, sourceId);++ return invocation === project.invocation ? project : { ...project, invocation };+};++/**+ * The generate widget doubles as Canvas's parameter panel — canvas invocations+ * compile from generate values (prepareCanvasInvocation) and canvasDimsSync+ * 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 compileInvocationSnapshot = (project: Project,route: InvocationRoute,@@ -2274,19 +2308,36 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe);}case 'setGenerateSettings': {- return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>- updateProjectWidgetValues(project, 'generate', () => cloneGenerateWidgetValues(action.values))- );+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {+ 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);+ });}case 'patchGenerateSettings': {- return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>- updateProjectWidgetValues(project, 'generate', (values) => patchRecord(values, action.values))- );+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {+ const updated = updateProjectWidgetValues(project, 'generate', (values) => patchRecord(values, action.values));++ if (updated === project || action.origin === 'system') {+ return updated;+ }++ const changedKeys = getChangedValueKeys(getProjectWidgetValues(project, 'generate'), action.values);++ return isHighConfidenceGenerateEdit(changedKeys) ? applyAutoRouteForGenerateEdit(updated) : updated;+ });}case 'patchProjectPromptDraft': {- return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>- updateProjectWidgetValues(project, 'generate', (values) => applyProjectPromptDraft(values, action.values))- );+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {+ const updated = updateProjectWidgetValues(project, 'generate', (values) =>+ 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');+ });}case 'setGenerateBatchCount': {const batchCount = sanitizeBatchCount(action.batchCount);@@ -2317,9 +2368,26 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe}case 'patchWidgetValues': {// Generic widget-owned UI state (panel modes, tabs, sizes). Not undoable.- return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>- updateProjectWidgetValues(project, action.widgetId, (values) => patchRecord(values, action.values))- );+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {+ const updated = updateProjectWidgetValues(project, action.widgetId, (values) =>+ patchRecord(values, action.values)+ );++ if (updated === project || action.origin === 'system') {+ return updated;+ }++ const changedKeys = getChangedValueKeys(getProjectWidgetValues(project, action.widgetId), action.values);++ if (action.widgetId === 'generate' && isHighConfidenceGenerateEdit(changedKeys)) {+ return applyAutoRouteForGenerateEdit(updated);+ }+ if (action.widgetId === 'upscale' && isHighConfidenceUpscaleEdit(changedKeys)) {+ return applyAutoRouteForEdit(updated, 'upscale');+ }++ return updated;+ });}case 'patchWidgetInstanceValues': {return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>@@ -2347,21 +2415,11 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbeconst undoLabel = getProjectGraphUndoLabel(action.action);const nextProject = undoLabel ? pushUndo(project, undoLabel) : project;- // Meaningful workflow edits are high-confidence source events: they- // steer the global Invoke route to the project graph unless locked.- const shouldAutoSetSource =- !project.invocation.sourceLocked &&- project.invocation.sourceId !== 'workflow' &&- isHighConfidenceGraphEdit(action.action) &&- isInvocationSourceAvailable('workflow');+ // Meaningful workflow edits are high-confidence source events that+ // steer the global Invoke route to the project graph.+ const updated = { ...nextProject, projectGraph };- return {- ...nextProject,- invocation: shouldAutoSetSource- ? { ...nextProject.invocation, sourceId: 'workflow' }- : nextProject.invocation,- projectGraph,- };+ return isHighConfidenceGraphEdit(action.action) ? applyAutoRouteForEdit(updated, 'workflow') : updated;});}case 'replaceProjectGraph': {@@ -2793,9 +2851,13 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbereturn updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);}case 'applyCanvasProjectMutation': {- return updateProjectById(state, action.projectId, (project) =>- applyCanvasProjectMutation(project, action.mutation)- );+ return updateProjectById(state, action.projectId, (project) => {+ const updated = applyCanvasProjectMutation(project, action.mutation);++ return updated !== project && isHighConfidenceCanvasEdit(action.mutation)+ ? applyAutoRouteForEdit(updated, 'canvas')+ : updated;+ });}case 'submitCanvasInvocationSnapshot': {return updateProjectById(state, action.projectId, (project) =>diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.tsnew file mode 100644index 0000000000..5856f0e2f6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from 'vitest';++import type * as settingsStore from './settings/store';++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 }),+ };+});++describe('auto invocation route switching with the preference off', () => {+ it('leaves the route alone for workflow, generate, 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',+ },+ id: 'node-1',+ position: { x: 0, y: 0 },+ type: 'invocation',+ },+ type: 'addNode',+ },+ 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',+ });++ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);++ expect(project?.projectGraph.nodes).toHaveLength(1);+ expect(project?.invocation).toMatchObject({ destination: 'canvas', sourceId: 'generate' });+ });+});