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
refactor(generation): make submission preparation explicit (#10163)
Josh Corbett53ba2fe48f7d
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex c065cca9ae..677e22acd0 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -24,6 +24,7 @@ import {import {addGalleryBoardToCaches,canAddToCachedGalleryBoard,+ getGalleryBoardDestinationIds,ensureGalleryBoardDestinations,getCachedGalleryBoard,getGalleryItemBoardIdsFromCaches,@@ -723,6 +724,7 @@ describe('patchGalleryBoardCaches', () => {expect(canAddToCachedGalleryBoard('viewed', client)).toBe(false);expect(canAddToCachedGalleryBoard('revoked', client)).toBe(false);expect(canAddToCachedGalleryBoard('never-listed', client)).toBe(false);+ expect(getGalleryBoardDestinationIds(client)).toEqual(['own']);});it('takes an archived board the caller may add to as a destination, and a board the archived listing lacks as gone', () => {@@ -760,6 +762,7 @@ describe('patchGalleryBoardCaches', () => {expect(canAddToCachedGalleryBoard('archived', client)).toBe(true);expect(canAddToCachedGalleryBoard('archived-viewed', client)).toBe(false);+ expect(getGalleryBoardDestinationIds(client)).toEqual(['own', 'archived']);expect(canAddToCachedGalleryBoard('revoked', client)).toBe(false);// Only a listing of live boards is cached: an unlisted board may be archived, so it is not a destination until// the archived listing is ensured, and gone once that listing lacks it.@@ -786,6 +789,7 @@ describe('patchGalleryBoardCaches', () => {expect(canAddToCachedGalleryBoard('own', client)).toBe(true);// Absence still counts: the failed listing is the one that would have held a board that exists.expect(canAddToCachedGalleryBoard('gone', client)).toBe(false);+ expect(getGalleryBoardDestinationIds(client)).toEqual(['archived', 'own']);});const getArchivedBoardsKey = (orderBy: 'board_name' | 'created_at' = 'created_at') =>diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 03ded4b174..2d817b1c72 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -511,6 +511,30 @@ export const canAddToCachedGalleryBoard = (boardId: string, client: QueryClientreturn false;};+/** Value snapshot of the same newest-listing policy used by uploads and destination controls. */+export const getGalleryBoardDestinationIds = (client: QueryClient = queryClient): readonly string[] => {+ const decided = new Set<string>();+ const destinations: string[] = [];+ let hasNewerLiveListing = false;+ for (const listing of getCachedGalleryBoardListings(client)) {+ for (const board of listing.state.data as GalleryBoard[]) {+ if (decided.has(board.id)) {+ continue;+ }+ decided.add(board.id);+ if ((!hasNewerLiveListing || board.archived) && canOnBoard(board, 'add_media')) {+ destinations.push(board.id);+ }+ }+ // This listing would contain every remaining readable board, so older data cannot restore one.+ if (isArchivedBoardsListing(listing)) {+ break;+ }+ hasNewerLiveListing = true;+ }+ return destinations;+};+const GALLERY_BOARD_DESTINATIONS_STALE_MS = 60_000;/**diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex e5b1660172..f71ce60fb5 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -23,7 +23,12 @@ export {imageIndexAvailabilityOptions,} from './data/queries';export { abortGalleryLocatorRequests, createGalleryLocatorRequest } from './core/selection';-export { canAddToCachedGalleryBoard, ensureGalleryBoardDestinations, getCachedGalleryBoard } from './data/queryCache';+export {+ canAddToCachedGalleryBoard,+ ensureGalleryBoardDestinations,+ getCachedGalleryBoard,+ getGalleryBoardDestinationIds,+} from './data/queryCache';export type {CanonicalGalleryItemsFilter,GalleryBoardsQuery,diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex 04aeaec296..c83df7a238 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -1,5 +1,5 @@import type { ModelConfig } from '@features/models';-import type { ProjectGraphState } from '@features/workflow/contracts';+import type { InvocationTemplatesSnapshot, ProjectGraphState } from '@features/workflow/contracts';import type { CanvasLayerContract, CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';import type {DynamicPromptsExpansionSource,@@ -359,7 +359,8 @@ export const resolveInvocationRoute = (route: InvocationRoute = project.invocation,models?: readonly ModelConfig[],/** Validate a specific project workflow (a captured submission target) instead of the active one. */- workflowDocument?: ProjectGraphState+ workflowDocument?: ProjectGraphState,+ templates?: Readonly<InvocationTemplatesSnapshot>): ResolvedInvocationRoute =>resolveInvocationRouteInput(workflowDocument@@ -367,14 +368,16 @@ export const resolveInvocationRoute = (: getInvocationRouteInput(project),mode,route,- models+ models,+ templates);export const resolveInvocationRouteInput = (input: InvocationRouteInput,mode: InvocationMode = 'global',route: InvocationRoute = input.invocation,- models?: readonly ModelConfig[]+ models?: readonly ModelConfig[],+ templates?: Readonly<InvocationTemplatesSnapshot>): ResolvedInvocationRoute => {const sourceId = route.sourceId;const destination = route.destination;@@ -382,7 +385,7 @@ export const resolveInvocationRouteInput = (// Route-rendering surfaces subscribe to templates and preferences because readiness reads them imperatively.const projectGraphReadiness =sourceId === 'workflow'- ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot(), {+ ? getProjectGraphReadiness(input.projectGraph, templates ?? getInvocationTemplatesSnapshot(), {batchCount: sanitizeBatchCount(input.workflowValues.batchCount),}): null;diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.tsindex cf6403b269..e50ea72c4f 100644--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts@@ -1,5 +1,5 @@import type { GenerationIssue } from '@features/generation/contracts';-import type { WorkflowReadinessReason } from '@features/workflow/contracts';+import type { InvocationTemplatesSnapshot, WorkflowReadinessReason } from '@features/workflow/contracts';import type { ControlLayerIssue } from '@workbench/controlLayerChecks';export type InvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'video' | 'canvas';@@ -86,3 +86,11 @@ export interface ResolvedInvocationRoute extends InvocationRoute {export interface InvocationControllerState extends InvocationRoute {lastSubmittedRunId?: string;}++/** Ephemeral values captured at dispatch, never persisted or treated as server authorization. */+export interface InvocationRuntimeInputs {+ /** GPU noise choice; the aggregate still applies the project's current CPU-noise preference. */+ readonly noiseDevice: string;+ readonly templates: Readonly<InvocationTemplatesSnapshot>;+ readonly boardDestinationIds: readonly string[];+}diff --git a/invokeai/frontend/webv2/src/workbench/invocationPreparation.ts b/invokeai/frontend/webv2/src/workbench/invocationPreparation.tsindex 6881daf531..303a5bc5a5 100644--- a/invokeai/frontend/webv2/src/workbench/invocationPreparation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationPreparation.ts@@ -1,7 +1,12 @@+import { getGalleryBoardDestinationIds } from '@features/gallery/queries';+import { getGenerationDevicesSnapshot, resolveRandDeviceMetadata } from '@features/queue/devices';+import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStoreCore } from '@platform/state/externalStoreCore';import { useExternalStoreSelector } from '@platform/state/selectors';+import type { InvocationRuntimeInputs, InvocationSourceId } from './invocationContracts';+interface InvocationPreparationSnapshot {leases: ReadonlyMap<string, number>;}@@ -55,3 +60,11 @@ registerAccountOwnedResource({clear: () => store.setSnapshot({ leases: EMPTY_LEASES }),name: 'invocation-preparation',});++/** Capture after async prerequisites; the template owner replaces snapshots, so its published value is safe to share. */+export const captureInvocationRuntimeInputs = (sourceId: InvocationSourceId): InvocationRuntimeInputs => ({+ noiseDevice: resolveRandDeviceMetadata(false, getGenerationDevicesSnapshot().options),+ templates:+ sourceId === 'workflow' ? getInvocationTemplatesSnapshot() : { error: null, status: 'idle', templates: {} },+ boardDestinationIds: getGalleryBoardDestinationIds(),+});diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsxindex 257af44cc1..8e238def4f 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx@@ -157,6 +157,7 @@ describe('board-listing reads before a submission', () => {// Nothing was awaited: the run was dispatched with the listing still unanswered.await submission;expect(dispatched).toHaveBeenCalledTimes(1);+ expect(dispatched.mock.calls[0]?.[0].runtime.boardDestinationIds).toContain('own');expect(server.listingReads()).toHaveLength(ageMs > 0 ? 1 : 0);// The stale listing's one background read lands for the next run; the fresh listing is left alone.@@ -177,6 +178,7 @@ describe('board-listing reads before a submission', () => {server.release();await submission;expect(dispatched).toHaveBeenCalledTimes(1);+ expect(dispatched.mock.calls[0]?.[0].runtime.boardDestinationIds).not.toContain('own');expect(server.listingReads()).toHaveLength(1);});});diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex e4dc4665fd..64b1b5e3e2 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -32,6 +32,7 @@ import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/preparimport type { WorkbenchCommands } from './workbenchStore';import { getDynamicPromptsExpansionSource } from './invocation';+import { captureInvocationRuntimeInputs } from './invocationPreparation';import { getActiveProjectWorkflow } from './projectWorkflows';import { getEffectiveProjectSettings, PROJECT_SETTINGS_OWNER } from './settings/projectSettings';import { readCanvasCompositingSettings } from './widgets/canvas/invoke/canvasCompositing';@@ -401,6 +402,7 @@ const dispatchResolvedInvocation = async (}commands.generation.submitResolved({+ runtime: captureInvocationRuntimeInputs(route.sourceId),backendSupportsCancellation: true,models,...expansion,diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdindex 9a9a313592..a68011c73f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/README.md+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -28,7 +28,7 @@ Canvas uploads carrying a project id await that identity’s acknowledged serverProject links are consumed after successful open, so reload restores the saved active project, not an earlier link. New-project startup selects the newly created draft before saving the session.-Workflow reads the active workflow through the App-composed port and edits, publishes, presents documents; it never replaces authored project work. Library is written only by the Workflow-owned publication controller, which captures account, project, workflow and content before start, refuses to overlap itself per workflow, reconciles a lost answer against the destination record before resending, and records resulting library id and revision on the originating workflow alone. Queue submissions carry the originating project workflow so seed advances, node progress and run previews return to it whatever is active later.+Workflow reads the active workflow through the App-composed port and edits, publishes, presents documents; it never replaces authored project work. Library is written only by the Workflow-owned publication controller, which captures account, project, workflow and content before start, refuses to overlap itself per workflow, reconciles a lost answer against the destination record before resending, and records resulting library id and revision on the originating workflow alone. Queue submissions carry the originating project workflow so seed advances, node progress and run previews return to it whatever is active later. For Generate, Workflow, Upscale and Video, submission orchestration captures ephemeral device, template and board-eligibility values immediately before dispatch, after asynchronous prerequisites; compilation consumes those values without reading live device, template or board caches. Workflow retains the template owner’s published snapshot by reference because refreshes replace snapshots rather than mutate them; non-workflow submissions do not capture template data. Canvas selects its noise device during lazy graph preparation. Canvas and one-click model-only upscale commands capture only board eligibility before enqueueing their already compiled graphs. Board eligibility follows Gallery's cached-listing policy for that dispatch, not permanent server authorization. The aggregate still uses current project settings and validates the originating workflow, prompt-expansion source and upscale input before atomically enqueueing and advancing seeds; preparation never replaces the project with its older snapshot.## Persistence runtimediff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.tsindex e8fdd0016a..b67724bf4c 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts@@ -45,7 +45,9 @@ const submitVideo = () => {state = workbenchReducer(state, {backendSupportsCancellation: true,models: [wanModel],- type: 'submitInvocationSnapshot',+ projectId: state.activeProjectId,+ route: state.projects.find((project) => project.id === state.activeProjectId)!.invocation,+ type: 'submitResolvedInvocationSnapshot',});return state;diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsxindex cb77851b5a..305644e241 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx@@ -102,7 +102,10 @@ vi.mock('@workbench/settings/store', async (importOriginal) => {};});vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation: harness.submit }));-vi.mock('@workbench/invocationPreparation', () => ({ useIsInvocationPreparing: () => false }));+vi.mock('@workbench/invocationPreparation', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useIsInvocationPreparing: () => false,+}));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project as Project),useWorkbenchCommands: () => ({}),diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex fbc14f112d..26d4db0dab 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -26,6 +26,7 @@ import { galleryKeys } from '@features/gallery/queries';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { MAX_PROMPT_HISTORY } from '@features/generation/settings';import { createDefaultUpscaleWidgetValues } from '@features/upscale';+import { getWorkflowGeneratorKey } from '@features/workflow/utility';import { queryClient } from '@platform/query/client';import { captureAccountScope } from '@platform/state/accountLifecycle';import { getDocumentLeaves } from '@workbench/canvas-engine/api';@@ -41,6 +42,7 @@ import { createEmptyCanvasDocument } from './canvasMigration';import { MAX_CANVAS_SNAPSHOTS } from './canvasProjectMutations';import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';import { getDynamicPromptsExpansionSource } from './invocation';+import { captureInvocationRuntimeInputs } from './invocationPreparation';import { getLayoutPresetLabel, layoutPresets } from './layoutPresets';import {createLayoutPresetSnapshot,@@ -494,7 +496,12 @@ const primeGenerate = () => workbenchReducer(state, { type: 'setGenerateSettings', values: createGenerateValues(overrides) });const submitGenerate = (state: WorkbenchState) =>- workbenchReducer(state, { backendSupportsCancellation: true, type: 'submitInvocationSnapshot' });+ workbenchReducer(state, {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ type: 'submitResolvedInvocationSnapshot',+ });describe('Invoke Front', () => {const getQueuedSnapshot = (state: WorkbenchState) => getActiveProject(state).queue.items[0]?.snapshot;@@ -599,6 +606,67 @@ const listGalleryBoardsInCache = (...boardIds: string[]) =>})));+describe('explicit submission runtime inputs', () => {+ it('keeps graph, device, destination and seed planning independent of later cache changes', () => {+ let state = primeGenerate(undefined, { batchCount: 3, seed: 42, seedMode: 'increment' });+ state = workbenchReducer(state, { settings: { useCpuNoise: false }, type: 'setActiveProjectSettings' });+ state = workbenchReducer(state, { settings: { autoAddBoardId: 'captured-board' }, type: 'updateGallerySettings' });+ listGalleryBoardsInCache('captured-board');+ generationDeviceMock.options = [{ device: 'xpu:0', name: 'Arc' }];+ const runtime = captureInvocationRuntimeInputs('generate');+ const action = {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ runtime,+ type: 'submitResolvedInvocationSnapshot' as const,+ };+ // Hold incidental graph identities stable; stepping seeds still come from the project.+ const time = vi.spyOn(Date, 'now').mockReturnValue(1_000);+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.25);+ let before: WorkbenchState;+ let after: WorkbenchState;+ try {+ before = workbenchReducer(state, action);+ generationDeviceMock.options = [{ device: 'cuda:0', name: 'RTX' }];+ listGalleryBoardsInCache('different-board');+ after = workbenchReducer(state, action);+ } finally {+ time.mockRestore();+ random.mockRestore();+ }++ expect(getQueuedRandDevice(after)).toBe('xpu');+ const first = getActiveProject(before).queue.items[0]!.snapshot;+ const second = getActiveProject(after).queue.items[0]!.snapshot;+ expect(second.galleryBoardId).toBe('captured-board');+ expect(second.backendSubmission).toEqual(first.backendSubmission);+ expect(second.backendSubmission).toMatchObject({ kind: 'generate', seed: 42, seedStep: 1, batchCount: 3 });+ expect(getProjectWidgetValues(getActiveProject(after), 'generate').seed).toBe(45);+ expect(getActiveProject(after).queue.items).toHaveLength(1);++ // A later submission captures the refreshed cache rather than retaining permission indefinitely.+ const refreshed = workbenchReducer(after, { ...action, runtime: captureInvocationRuntimeInputs('generate') });+ expect(getQueuedRandDevice(refreshed)).toBe('cuda');+ expect(getActiveProject(refreshed).queue.items[0]!.snapshot.galleryBoardId).toBe('none');+ expect(getProjectWidgetValues(getActiveProject(refreshed), 'generate').seed).toBe(48);+ });++ it('applies the current project CPU-noise preference to the captured GPU device', () => {+ let state = primeGenerate();+ const runtime = { ...captureInvocationRuntimeInputs('generate'), noiseDevice: 'xpu' };+ state = workbenchReducer(state, { settings: { useCpuNoise: true }, type: 'setActiveProjectSettings' });+ const next = workbenchReducer(state, {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ runtime,+ type: 'submitResolvedInvocationSnapshot',+ });+ expect(getQueuedRandDevice(next)).toBe('cpu');+ });+});+describe('project output filters', () => {it('queues the NSFW checker as the generate output when the project turns it on', () => {const initial = workbenchReducer(createInitialWorkbenchState(), {@@ -4720,6 +4788,147 @@ describe('workbenchReducer Phase 5 generation flow', () => {return node?.type === 'invocation' ? node.data.inputs.seed?.value : undefined;};+ it('validates and compiles with captured templates after the template store changes', () => {+ const state = primeWorkflow(42, 'increment');+ const runtime = captureInvocationRuntimeInputs('workflow');+ workflowTemplatesMock.snapshot = { error: 'reloading', status: 'error', templates: {} };+ const next = workbenchReducer(state, {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },+ runtime,+ type: 'submitResolvedInvocationSnapshot',+ });+ expect(readSubmission(next)).toMatchObject({+ kind: 'workflow',+ batchCount: 3,+ graph: { nodes: { 'noise-1': { seed: 42 } } },+ seeds: [{ fieldName: 'seed', nodeId: 'noise-1', seed: 42, seedStep: 1 }],+ });+ expect(readNodeSeed(next)).toBe(45);+ expect(getActiveProject(next).queue.items).toHaveLength(1);++ const rejected = workbenchReducer(state, {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ runtime: { ...runtime, templates: { error: null, status: 'loading', templates: {} } },+ type: 'submitResolvedInvocationSnapshot',+ });+ expect(getActiveProject(rejected).queue.items).toEqual([]);+ expect(readNodeSeed(rejected)).toBe(42);+ });++ it('does not enqueue or advance seeds when a workflow generator changed during preparation', () => {+ let state = primeWorkflow(42, 'increment');+ const field = (name: string, typeName: string) => ({+ ...seedTemplate.inputs.seed,+ default: undefined,+ maximum: null,+ minimum: null,+ name,+ title: name,+ type: { batch: false, cardinality: 'SINGLE' as const, name: typeName },+ });+ const template = (type: string, inputs: Record<string, unknown>) => ({ ...seedTemplate, inputs, type });+ workflowTemplatesMock.snapshot = {+ error: null,+ status: 'loaded',+ templates: {+ noise: seedTemplate,+ string: template('string', { value: field('value', 'StringField') }),+ string_batch: template('string_batch', {+ batch_group_id: { ...field('batch_group_id', 'EnumField'), default: 'None', options: ['None'] },+ strings: {+ ...field('strings', 'StringField'),+ default: [],+ type: { batch: true, cardinality: 'COLLECTION', name: 'StringField' },+ },+ }),+ string_generator: template('string_generator', { generator: field('generator', 'StringGeneratorField') }),+ },+ };+ const generator = {+ input: 'a {red|green} cat',+ maxPrompts: 4,+ type: 'string_generator_dynamic_prompts_combinatorial' as const,+ };+ for (const [id, type, inputs] of [+ ['generator-1', 'string_generator', { generator }],+ ['batch-1', 'string_batch', { batch_group_id: 'None' }],+ ['string-1', 'string', { value: 'static' }],+ ] as const) {+ state = workbenchReducer(state, {+ action: {+ node: {+ data: {+ inputs: Object.fromEntries(+ Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])+ ),+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type,+ useCache: true,+ version: '1.0.0',+ },+ id,+ position: { x: 0, y: 0 },+ type: 'invocation',+ },+ type: 'addNode',+ },+ type: 'applyWorkflowAction',+ });+ }+ for (const [source, sourceHandle, target, targetHandle] of [+ ['generator-1', 'strings', 'batch-1', 'strings'],+ ['batch-1', 'value', 'string-1', 'value'],+ ] as const) {+ state = workbenchReducer(state, {+ action: {+ edge: { id: `${source}->${target}`, source, sourceHandle, target, targetHandle, type: 'default' },+ type: 'addEdge',+ },+ type: 'applyWorkflowAction',+ });+ }+ const submission = {+ backendSupportsCancellation: true,+ projectId: state.activeProjectId,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },+ runtime: captureInvocationRuntimeInputs('workflow'),+ type: 'submitResolvedInvocationSnapshot',+ workflowGenerators: {+ 'generator-1': { items: ['a red cat', 'a green cat'], key: getWorkflowGeneratorKey(generator) },+ },+ workflowId: getActiveProject(state).workflows.activeWorkflowId,+ } satisfies WorkbenchAction;+ const valid = workbenchReducer(state, submission);+ expect(readSubmission(valid)).toMatchObject({+ batchData: [[{ fieldName: 'value', items: ['a red cat', 'a green cat'], nodeId: 'string-1' }]],+ kind: 'workflow',+ });+ expect(getActiveProject(valid).queue.items).toHaveLength(1);+ expect(readNodeSeed(valid)).toBe(48);++ state = workbenchReducer(state, {+ action: {+ fieldName: 'generator',+ nodeId: 'generator-1',+ type: 'setFieldValue',+ value: { ...generator, input: 'a {black|white} dog' },+ },+ type: 'applyWorkflowAction',+ workflowId: submission.workflowId,+ });+ const rejected = workbenchReducer(state, submission);+ expect(getActiveProject(rejected).queue.items).toEqual([]);+ expect(readNodeSeed(rejected)).toBe(42);+ });+it('compiles Auto boards to the auto-add board, leaves None unboarded, and keeps results off the selection', () => {const boardTemplate = {...seedTemplate,@@ -5442,7 +5651,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = workbenchReducer(state, {backendSupportsCancellation: true,models: [wanModel],- type: 'submitInvocationSnapshot',+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ type: 'submitResolvedInvocationSnapshot',});expect(readSubmission(state)).toMatchObject({ batchCount: 3, seed: 7, seedStep: -1 });@@ -5722,7 +5933,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = workbenchReducer(state, {backendSupportsCancellation: true,models: [wanModel],- type: 'submitInvocationSnapshot',+ projectId: state.activeProjectId,+ route: getActiveProject(state).invocation,+ type: 'submitResolvedInvocationSnapshot',});const submission = getActiveProject(state).queue.items[0]?.snapshot.recall?.videoValues;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.tsindex 3f8712743a..04396c7641 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts@@ -1,6 +1,7 @@/** Test-only reducer facade; production callers use Workbench commands and queries. */import type { WorkbenchState } from '@workbench/projectContracts';+import { captureInvocationRuntimeInputs } from './invocationPreparation';import {createInitialWorkbenchState,__workbenchReducerInternal,@@ -9,13 +10,37 @@ import {type WorkbenchReducerContext,} from './workbenchState';+type Submission = Extract<__WorkbenchReducerActionInternal, { runtime: unknown }>;+type OptionalRuntime<T> = T extends Submission ? Omit<T, 'runtime'> & { runtime?: T['runtime'] } : T;+type TestAction = OptionalRuntime<__WorkbenchReducerActionInternal>;+const DEFAULT_TEST_CONTEXT: WorkbenchReducerContext = { autoSwitchInvocationRoute: true };export const workbenchReducer = (state: WorkbenchState,- action: __WorkbenchReducerActionInternal,+ action: TestAction,context: WorkbenchReducerContext = DEFAULT_TEST_CONTEXT-): WorkbenchState => __workbenchReducerInternal(state, action, context);+): WorkbenchState =>+ __workbenchReducerInternal(+ state,+ action.type === 'submitResolvedInvocationSnapshot' ||+ action.type === 'submitCanvasInvocationSnapshot' ||+ action.type === 'submitModelOnlyUpscale'+ ? ({+ ...action,+ runtime:+ action.runtime ??+ captureInvocationRuntimeInputs(+ action.type === 'submitResolvedInvocationSnapshot'+ ? action.route.sourceId+ : action.type === 'submitCanvasInvocationSnapshot'+ ? 'canvas'+ : 'upscale'+ ),+ } as __WorkbenchReducerActionInternal)+ : (action as __WorkbenchReducerActionInternal),+ context+ );export { createInitialWorkbenchState, nextLayerName };-export type { __WorkbenchReducerActionInternal as WorkbenchAction, WorkbenchReducerContext };+export type { TestAction as WorkbenchAction, WorkbenchReducerContext };diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex eb8a1254c8..1b3c5ff3e5 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -20,6 +20,7 @@ import type {ExpandedPositivePrompts,InvocationRoute,InvocationSourceId,+ ResolvedInvocationRoute,ResultDestination,UpscaleSourceMetadata,} from '@workbench/invocationContracts';@@ -101,6 +102,7 @@ import { WIDGET_REGIONS } from '@workbench/layoutContracts';import { prependProjectEvent, PROJECT_EVENT_LIMIT } from '@workbench/projectEvents';import { createProjectId } from '@workbench/projects/ids';+import type { InvocationRuntimeInputs } from './invocationContracts';import type { WorkbenchQueueItem as QueueItem } from './queueHistoryContracts';import {@@ -144,7 +146,6 @@ import { applyWidgetDefaults, getProjectWidgetValues, getResolvedProjectWidgetVaexport { nextLayerName } from './canvasProjectMutations';import type { ProjectPromptDraftPatch } from '@features/generation/settings';-import { canAddToCachedGalleryBoard } from '@features/gallery/queries';import { compileGenerateGraph, resolveGenerateSeed } from '@features/generation/graph';import {addPromptHistoryItem,@@ -166,7 +167,6 @@ import {} from '@features/generation/settings';import { getQueueSourceResultSelection, MAX_QUEUE_BATCH_ITEMS } from '@features/queue';import { getQueueItemSnapshotLabel } from '@features/queue/contracts';-import { getGenerationDevicesSnapshot, resolveRandDeviceMetadata } from '@features/queue/devices';import {clearDeletedUpscaleInput,cloneUpscaleWidgetValues,@@ -196,7 +196,6 @@ import {type VideoWidgetValues,} from '@features/video';import { planWorkflowSubmission } from '@features/workflow/graph';-import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import {hasMultipleWorkflowReturnNodes,projectGraphReducer,@@ -428,9 +427,9 @@ type WorkbenchReducerAction =}| { type: 'undoWorkflowChange'; projectId?: string; workflowId?: string }| { type: 'redoWorkflowChange'; projectId?: string; workflowId?: string }- | { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean; models?: readonly ModelConfig[] }| ({type: 'submitResolvedInvocationSnapshot';+ runtime: InvocationRuntimeInputs;backendSupportsCancellation: boolean;/** Invoke Front: the backend runs the batch ahead of the user's other pending work. */prepend?: boolean;@@ -448,6 +447,7 @@ type WorkbenchReducerAction =| {/** The image menu's one-click upscale: queued at once, leaving the Upscale widget and the route as they are. */type: 'submitModelOnlyUpscale';+ runtime: Pick<InvocationRuntimeInputs, 'boardDestinationIds'>;projectId: string;image: ImageWithDims;upscaleModel: SpandrelModelConfig;@@ -591,6 +591,7 @@ type WorkbenchReducerAction =| { type: 'commitCanvasEdit'; projectId: string; intent: CanvasEditIntent }| ({type: 'submitCanvasInvocationSnapshot';+ runtime: Pick<InvocationRuntimeInputs, 'boardDestinationIds'>;backendSupportsCancellation: boolean;canvas: CanvasStateContractV3;destination: ResultDestination;@@ -3141,6 +3142,7 @@ const compileInvocationSnapshot = (project: Project,defaults: ScopedDefaults,route: InvocationRoute,+ runtime: InvocationRuntimeInputs,models?: readonly ModelConfig[],workflowGenerators?: WorkflowGeneratorResolutions,workflowDocument: ProjectGraphState = getActiveProjectGraph(project),@@ -3155,11 +3157,10 @@ const compileInvocationSnapshot = (} | null => {const widgetStates = getWidgetStatesSnapshot(project.widgetInstances);const projectSettings = getEffectiveProjectSettings(project.settings, defaults[PROJECT_SETTINGS_OWNER]);- const randDevice = resolveRandDeviceMetadata(projectSettings.useCpuNoise, getGenerationDevicesSnapshot().options);+ const randDevice = projectSettings.useCpuNoise ? 'cpu' : runtime.noiseDevice;if (route.sourceId === 'workflow') {- // Route validation guarantees templates are loaded before this imperative read.- const templatesSnapshot = getInvocationTemplatesSnapshot();+ const templatesSnapshot = runtime.templates;if (templatesSnapshot.status !== 'loaded') {return null;@@ -3168,12 +3169,12 @@ const compileInvocationSnapshot = (const plan = planWorkflowSubmission(workflowDocument, templatesSnapshot.templates, {autoBoardId: getGalleryAutoAddBoardId(getResolvedProjectWidgetValues(project, 'gallery', defaults),- canAddToCachedGalleryBoard+ (boardId: string) => runtime.boardDestinationIds.includes(boardId)),batchCount: sanitizeBatchCount(widgetStates.workflow?.values.batchCount),generators: workflowGenerators,// An explicit board a node names is judged like the auto-add board: one the caller may add to now.- isBoardDestination: (boardId) => canAddToCachedGalleryBoard(boardId),+ isBoardDestination: (boardId) => runtime.boardDestinationIds.includes(boardId),});// Null means a generator is still unresolved or was edited during its round trip; nothing is queued.@@ -3980,6 +3981,7 @@ const enqueueCompiledSnapshot = (project: Project,defaults: ScopedDefaults,route: InvocationRoute,+ runtime: Pick<InvocationRuntimeInputs, 'boardDestinationIds'>,compiled: Partial<ExpandedPositivePrompts> & {generate?: QueueGenerateSnapshot;graph: GraphContract;@@ -4063,7 +4065,7 @@ const enqueueCompiledSnapshot = (? null: getGalleryAutoAddBoardId(applyWidgetDefaults(widgetStates.gallery?.values ?? {}, 'gallery', defaults),- canAddToCachedGalleryBoard+ (boardId: string) => runtime.boardDestinationIds.includes(boardId));const generatePresentationSettings = normalizeGenerateSettings(widgetStates.generate?.values);const videoPresentationDimensions =@@ -4234,6 +4236,7 @@ const submitModelOnlyUpscale = (defaults: ScopedDefaults,{backendSupportsCancellation,+ runtime,image,scale,sourceMetadata,@@ -4265,6 +4268,7 @@ const submitModelOnlyUpscale = (project,defaults,route,+ runtime,{ graph: compiled.graph, widgetStates },backendSupportsCancellation,undefined,@@ -4277,7 +4281,8 @@ const submitInvocationSnapshot = (project: Project,defaults: ScopedDefaults,backendSupportsCancellation: boolean,- route = resolveInvocationRoute(project),+ runtime: InvocationRuntimeInputs,+ route: ResolvedInvocationRoute,models?: readonly ModelConfig[],expansion: Partial<ExpandedPositivePrompts> = {},workflowGenerators?: WorkflowGeneratorResolutions,@@ -4293,6 +4298,7 @@ const submitInvocationSnapshot = (project,defaults,route,+ runtime,models,workflowGenerators,workflowDocument,@@ -4307,6 +4313,7 @@ const submitInvocationSnapshot = (project,defaults,route,+ runtime,{ ...compiledSnapshot, ...expansion },backendSupportsCancellation,undefined,@@ -5503,21 +5510,6 @@ const reduceWorkbenchAction = (redoProjectWorkflow(project, action.workflowId ?? project.workflows.activeWorkflowId, now()));}- case 'submitInvocationSnapshot': {- return withEnqueueNotification(- state,- updateActiveProject(state, (project) =>- submitInvocationSnapshot(- project,- state.scopedDefaults,- action.backendSupportsCancellation,- undefined,- action.models- )- ),- state.activeProjectId- );- }case 'submitResolvedInvocationSnapshot': {const target = state.projects.find((project) => project.id === action.projectId);const workflow =@@ -5590,7 +5582,15 @@ const reduceWorkbenchAction = (project,state.scopedDefaults,action.backendSupportsCancellation,- resolveInvocationRoute(project, 'global', action.route, action.models, workflow?.document),+ action.runtime,+ resolveInvocationRoute(+ project,+ 'global',+ action.route,+ action.models,+ workflow?.document,+ action.runtime.templates+ ),action.models,{ positivePrompts: action.positivePrompts, positivePromptsSampleSeed: action.positivePromptsSampleSeed },action.workflowGenerators,@@ -6228,6 +6228,7 @@ const reduceWorkbenchAction = (project,state.scopedDefaults,{ ...project.invocation, destination: action.destination, sourceId: 'canvas' },+ action.runtime,{generate: action.generate,graph: action.graph,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex d98a1ff40f..d157899930 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -8,6 +8,7 @@ import {type GalleryImage,type GeneratedImageContract,} from '@features/gallery/contracts';+import { getGalleryBoardDestinationIds } from '@features/gallery/queries';import { recordLogEvent } from '@platform/logging/logger';import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';import { createExternalStore } from '@platform/state/externalStore';@@ -310,8 +311,18 @@ const createCommands = (setSource: command('setInvocationSource', (sourceId: ActionPayload<'setInvocationSource'>['sourceId']) => ({sourceId,})),- submitCanvas: command('submitCanvasInvocationSnapshot'),- submitModelOnlyUpscale: command('submitModelOnlyUpscale'),+ submitCanvas: (payload: Omit<ActionPayload<'submitCanvasInvocationSnapshot'>, 'runtime'>) =>+ dispatch({+ ...payload,+ runtime: { boardDestinationIds: getGalleryBoardDestinationIds() },+ type: 'submitCanvasInvocationSnapshot',+ }),+ submitModelOnlyUpscale: (payload: Omit<ActionPayload<'submitModelOnlyUpscale'>, 'runtime'>) =>+ dispatch({+ ...payload,+ runtime: { boardDestinationIds: getGalleryBoardDestinationIds() },+ type: 'submitModelOnlyUpscale',+ }),submitResolved: command('submitResolvedInvocationSnapshot'),toggleDestinationLock: command('toggleDestinationLock'),toggleRoutingLock: command('toggleRoutingLock'),diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 62b9b2c942..59cc502861 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -246,6 +246,8 @@ const WORKBENCH_RUNTIME_SHARED_MODULES = ['/features/generation/core/projectPromptDraft.ts','/features/generation/core/prompt/compel.ts','/features/queue/core/deviceLabels.ts',+ // The shared device entry otherwise becomes an imports-only boot request beside its labels and hook.+ '/features/queue/devices.ts','/features/queue/core/graphInputMedia.ts','/features/queue/data/activeProgressTargetStore.ts','/features/queue/data/progressImageStore.ts',@@ -347,6 +349,15 @@ const GALLERY_PICKER_MODULES = ['/features/gallery/ui/useGalleryUploadInput.ts',] as const;+// The backend and its URL helpers load together for recent outputs. Keep picker UI out of that lazy Launchpad read.+const GALLERY_BACKEND_MODULES = [+ '/features/gallery/core/imagePaths.ts',+ '/features/gallery/core/videoPaths.ts',+ '/features/gallery/data/backend.ts',+ '/features/gallery/data/imageUrls.ts',+ '/features/gallery/data/videoUrls.ts',+] as const;+// Gallery's shared state projection and UI port travel together.const GALLERY_STATE_MODULES = [// Board access predicates: the state view, the gallery's caches and the picker read them; alone they cost a request.@@ -535,6 +546,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, GALLERY_PICKER_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'gallery-backend',+ priority: 30,+ test: (id) => matchesAnySuffix(id, GALLERY_BACKEND_MODULES),+ },{includeDependenciesRecursively: false,name: 'gallery-state',