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(canvas): run workflows from layers
joshistoast74ce5fe36571
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 8fb02c0fa4..3aa6766662 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1176,6 +1176,7 @@"rasterize": "Rasterize layer","rename": "Rename layer","reorder": "Reorder layer",+ "runWorkflow": "Run workflow","saveLayerToAssets": "Save layer to assets","selectObject": "Select object","show": "Show layer",@@ -1288,6 +1289,37 @@"title": "Select object","unsupported": "This layer content cannot be used for object selection."},+ "runWorkflow": {+ "aborted": "Workflow run was canceled.",+ "busy": "Finish the current canvas interaction, then try again.",+ "cancel": "Cancel",+ "copyRaster": "Copy as raster layer",+ "copySuccess": "Added the workflow result as a raster layer.",+ "destination": "Destination",+ "disabled": "Enable the layer before running the workflow.",+ "durabilityFailure": "The workflow output could not be preserved: {{message}}",+ "empty": "This layer has no content to run through the workflow.",+ "failed": "Workflow run failed: {{message}}",+ "gallery": "Gallery",+ "gallerySuccess": "Saved the workflow result to Gallery.",+ "graphFailure": "The active workflow failed: {{message}}",+ "hydrationFailure": "The workflow output could not be loaded: {{message}}",+ "input": "Workflow image input",+ "locked": "Unlock the layer before running the workflow.",+ "missing": "The source layer no longer exists.",+ "noBindings": "The active workflow has no compatible image input and output.",+ "notReady": "The active workflow is not ready with this layer input.",+ "output": "Workflow image output",+ "replace": "Replace layer",+ "replaceSuccess": "Replaced the layer with the workflow result.",+ "run": "Run",+ "running": "Running workflow…",+ "staging": "Canvas staging",+ "stagingSuccess": "Added the workflow result to canvas staging.",+ "stale": "The layer or project changed while the workflow was running. Run it again.",+ "title": "Run workflow from layer",+ "unsupported": "This layer cannot be used as a workflow image input."+ },"addLayer": "Add layer","adjustments": {"brightness": "Brightness",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.tsindex 26b22bd98d..ba1687009d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts@@ -83,6 +83,14 @@ const statusEvent = (const okEnqueue: UtilityEnqueue = () => Promise.resolve({ enqueued: 1, itemIds: [1] });+const createDeferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+};+afterEach(() => {vi.useRealTimers();});@@ -174,12 +182,14 @@ describe('runUtilityGraph — await + settle', () => {});describe('runUtilityGraph — timeout + cancellation', () => {- it('rejects with timeout after timeoutMs with no terminal event', async () => {+ it('rejects with timeout and cancels every accepted backend item', async () => {vi.useFakeTimers();const fake = createFakeHub();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());const promise = runUtilityGraph({+ cancel,createId: () => UTIL_ID,- enqueue: okEnqueue,+ enqueue: () => Promise.resolve({ enqueued: 3, itemIds: [11, 12, 13] }),graph: { edges: [], id: 'g', nodes: {} },hub: fake.hub,timeoutMs: 1000,@@ -187,39 +197,145 @@ describe('runUtilityGraph — timeout + cancellation', () => {const assertion = expect(promise).rejects.toMatchObject({ reason: 'timeout' });await vi.advanceTimersByTimeAsync(1000);await assertion;+ expect(cancel).toHaveBeenCalledExactlyOnceWith([11, 12, 13]);// Listeners cleaned up after timeout.expect(fake.handlerCount('queue_item_status_changed')).toBe(0);});- it('rejects immediately when the signal is already aborted', async () => {+ it('rejects immediately without enqueueing or canceling when the signal is already aborted', async () => {const fake = createFakeHub();const controller = new AbortController();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());+ const enqueue = vi.fn(okEnqueue);controller.abort();const promise = runUtilityGraph({+ cancel,createId: () => UTIL_ID,- enqueue: okEnqueue,+ enqueue,graph: { edges: [], id: 'g', nodes: {} },hub: fake.hub,signal: controller.signal,});await expect(promise).rejects.toMatchObject({ reason: 'aborted' });+ expect(enqueue).not.toHaveBeenCalled();+ expect(cancel).not.toHaveBeenCalled();});- it('rejects aborted when the signal fires mid-flight and detaches listeners', async () => {+ it('rejects aborted, cancels accepted backend items, and detaches listeners', async () => {const fake = createFakeHub();const controller = new AbortController();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());const promise = runUtilityGraph({+ cancel,createId: () => UTIL_ID,- enqueue: okEnqueue,+ enqueue: () => Promise.resolve({ enqueued: 2, itemIds: [21, 22] }),graph: { edges: [], id: 'g', nodes: {} },hub: fake.hub,signal: controller.signal,});+ await Promise.resolve();controller.abort();await expect(promise).rejects.toMatchObject({ reason: 'aborted' });+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledExactlyOnceWith([21, 22]));expect(fake.handlerCount('invocation_complete')).toBe(0);});+ it('rejects promptly, then cancels accepted items when a pending enqueue resolves', async () => {+ const fake = createFakeHub();+ const controller = new AbortController();+ const enqueue = createDeferred<{ enqueued: number; itemIds: number[] }>();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());+ const promise = runUtilityGraph({+ cancel,+ createId: () => UTIL_ID,+ enqueue: () => enqueue.promise,+ graph: { edges: [], id: 'g', nodes: {} },+ hub: fake.hub,+ signal: controller.signal,+ });+ const assertion = expect(promise).rejects.toMatchObject({ reason: 'aborted' });++ controller.abort();+ await assertion;+ expect(cancel).not.toHaveBeenCalled();++ enqueue.resolve({ enqueued: 2, itemIds: [31, 32] });+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledExactlyOnceWith([31, 32]));+ });++ it('cancels at most once across abort, timeout, terminal, and cancellation-failure races', async () => {+ vi.useFakeTimers();+ const fake = createFakeHub();+ const controller = new AbortController();+ const enqueue = createDeferred<{ enqueued: number; itemIds: number[] }>();+ const cancel = vi.fn((_itemIds: number[]) => Promise.reject(new Error('cancel failed')));+ const promise = runUtilityGraph({+ cancel,+ createId: () => UTIL_ID,+ enqueue: () => enqueue.promise,+ graph: { edges: [], id: 'g', nodes: {} },+ hub: fake.hub,+ signal: controller.signal,+ timeoutMs: 1000,+ });+ const assertion = expect(promise).rejects.toMatchObject({ reason: 'aborted' });++ controller.abort();+ await vi.advanceTimersByTimeAsync(1000);+ fake.emit('queue_item_status_changed', statusEvent('failed'));+ enqueue.resolve({ enqueued: 2, itemIds: [41, 42] });++ await assertion;+ await vi.runAllTimersAsync();+ expect(cancel).toHaveBeenCalledExactlyOnceWith([41, 42]);+ });++ it('does not cancel when a terminal success wins before a later abort', async () => {+ const fake = createFakeHub();+ const controller = new AbortController();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());+ const promise = runUtilityGraph({+ cancel,+ createId: () => UTIL_ID,+ enqueue: () => Promise.resolve({ enqueued: 2, itemIds: [51, 52] }),+ graph: { edges: [], id: 'g', nodes: {} },+ hub: fake.hub,+ signal: controller.signal,+ });+ await Promise.resolve();++ fake.emit('invocation_complete', completeEvent());+ fake.emit('queue_item_status_changed', statusEvent('completed'));+ await expect(promise).resolves.toMatchObject({ imageName: 'filtered.png' });+ controller.abort();+ await Promise.resolve();++ expect(cancel).not.toHaveBeenCalled();+ });++ it('does not cancel when an aborted pending enqueue later accepts zero items', async () => {+ const fake = createFakeHub();+ const controller = new AbortController();+ const enqueue = createDeferred<{ enqueued: number; itemIds: number[] }>();+ const cancel = vi.fn((_itemIds: number[]) => Promise.resolve());+ const promise = runUtilityGraph({+ cancel,+ createId: () => UTIL_ID,+ enqueue: () => enqueue.promise,+ graph: { edges: [], id: 'g', nodes: {} },+ hub: fake.hub,+ signal: controller.signal,+ });+ const assertion = expect(promise).rejects.toMatchObject({ reason: 'aborted' });++ controller.abort();+ enqueue.resolve({ enqueued: 0, itemIds: [] });++ await assertion;+ await Promise.resolve();+ expect(cancel).not.toHaveBeenCalled();+ });+it('does not use a timeout when timeoutMs is 0', async () => {vi.useFakeTimers();const fake = createFakeHub();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.tsindex 920f555d97..c70d4d8a02 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts@@ -17,7 +17,9 @@* events by our unique origin.* 3. Enqueues the graph (listeners are attached first, closing the fast-finish* race), then resolves with the output `imageName` on completion, or rejects- * on failure/cancellation/timeout/abort.+ * on failure/cancellation/timeout/abort. Abort and timeout also best-effort+ * cancel every backend item accepted for this run, including when enqueue+ * resolves after the local await has already rejected.** Zero React, zero DOM: `hub` and `enqueue` are injected, so this runs in node* tests against fakes. Every side-effecting dependency is a parameter.@@ -28,7 +30,7 @@ import type { SocketHub } from '@workbench/backend/socketHub';import type { BackendGraphContract } from '@workbench/types';import { buildUtilityQueueItemOrigin } from '@workbench/backend/events';-import { enqueueUtilityGraph } from '@workbench/generation/api';+import { cancelQueueItems, enqueueUtilityGraph } from '@workbench/generation/api';/** The default time a utility graph may run before it is abandoned. */export const DEFAULT_UTILITY_QUEUE_TIMEOUT_MS = 120_000;@@ -50,6 +52,9 @@ export type UtilityEnqueue = (request: {origin: string;}) => Promise<{ itemIds: number[]; enqueued: number }>;+/** The cancellation seam: best-effort cancels accepted backend item ids. */+export type UtilityCancel = (itemIds: number[]) => Promise<void>;+/** Dependencies for {@link runUtilityGraph} (all injectable for tests). */export interface RunUtilityGraphOptions {/** The graph to enqueue and await. */@@ -63,9 +68,11 @@ export interface RunUtilityGraphOptions {hub: Pick<SocketHub, 'on'>;/** Enqueue seam (defaults to the real utility enqueue API). */enqueue?: UtilityEnqueue;+ /** Cancellation seam (defaults to the real queue cancellation API). */+ cancel?: UtilityCancel;/** Abandon after this many ms (default {@link DEFAULT_UTILITY_QUEUE_TIMEOUT_MS}). `0` disables. */timeoutMs?: number;- /** Cancels the await (does not itself cancel the backend item). */+ /** Cancels the await and best-effort cancels accepted backend items. */signal?: AbortSignal;/** Injectable id source (defaults to `crypto.randomUUID`). */createId?: () => string;@@ -92,6 +99,7 @@ const extractImageName = (result: InvocationCompleteEvent['result'] | undefined)export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<UtilityGraphResult> => {const { graph, hub, outputNodeId, signal } = options;const enqueue = options.enqueue ?? enqueueUtilityGraph;+ const cancel = options.cancel ?? cancelQueueItems;const timeoutMs = options.timeoutMs ?? DEFAULT_UTILITY_QUEUE_TIMEOUT_MS;const utilityId = (options.createId ?? (() => crypto.randomUUID()))();const origin = buildUtilityQueueItemOrigin(utilityId);@@ -99,9 +107,37 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilitreturn new Promise<UtilityGraphResult>((resolve, reject) => {let settled = false;let capturedImageName: string | null = null;+ let cancellationRequested = false;+ let cancellationStarted = false;+ let enqueueResult: { itemIds: number[]; enqueued: number } | null = null;const detachers: Array<() => void> = [];let timer: ReturnType<typeof setTimeout> | null = null;+ const cancelAcceptedItems = (): void => {+ if (+ !cancellationRequested ||+ cancellationStarted ||+ enqueueResult === null ||+ enqueueResult.enqueued === 0 ||+ enqueueResult.itemIds.length === 0+ ) {+ return;+ }++ cancellationStarted = true;+ const itemIds = [...enqueueResult.itemIds];+ void Promise.resolve()+ .then(() => cancel(itemIds))+ .catch(() => {+ // Cancellation is best-effort and must never mask the original settle reason.+ });+ };++ const requestBackendCancellation = (): void => {+ cancellationRequested = true;+ cancelAcceptedItems();+ };+const cleanup = (): void => {if (timer !== null) {clearTimeout(timer);@@ -135,6 +171,10 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit};function onAbort(): void {+ if (settled) {+ return;+ }+ requestBackendCancellation();settleReject(new UtilityQueueError('aborted', 'The utility graph was aborted.'));}@@ -184,6 +224,10 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilitif (timeoutMs > 0) {timer = setTimeout(() => {+ if (settled) {+ return;+ }+ requestBackendCancellation();settleReject(new UtilityQueueError('timeout', `The utility graph timed out after ${timeoutMs}ms.`));}, timeoutMs);}@@ -192,6 +236,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit// the time this resolves; `settled` guards against a late enqueue result.enqueue({ graph, origin }).then((result) => {+ enqueueResult = result;+ cancelAcceptedItems();if (!settled && result.enqueued === 0) {settleReject(new UtilityQueueError('enqueue', 'The backend queue did not accept the utility graph.'));}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 50803f6511..e548366e7f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -4134,6 +4134,48 @@ describe('setStagedPreview', () => {engine.dispose();});++ it('stores an image candidate placement and renders it independently of the current bbox', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);++ const base = createTestStubRasterBackend();+ const backend: StubRasterBackend = {+ ...base,+ createImageBitmap: () => Promise.resolve({ close: vi.fn(), height: 17, width: 23 } as unknown as ImageBitmap),+ };+ const { setDocument, store } = createReactiveStore(emptyDoc({ height: 100, width: 100, x: 50, y: 60 }));+ const engine = createCanvasEngine({+ backend,+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const screen = createFakeCanvas();+ engine.attach(screen.element, createFakeCanvas().element);++ engine.setStagedPreview({+ imageName: 'placed-candidate',+ placement: { height: 34, opacity: 0.4, width: 46, x: -8, y: 13 },+ });+ await flushMicrotasks();+ raf.flush();++ expect(stagedDraws(screen.surface).at(-1)!.slice(1)).toEqual([-8, 13, 46, 34]);+ const alphaSets = screen.surface.callLog+ .filter((entry) => entry.op === 'set' && entry.args[0] === 'globalAlpha')+ .map((entry) => entry.args[1]);+ expect(alphaSets).toContain(0.4);++ // A placed candidate no longer follows the bbox, so moving the bbox only+ // invalidates overlay chrome and must not recomposite every canvas layer.+ screen.surface.callLog.length = 0;+ setDocument(emptyDoc({ height: 50, width: 50, x: 2, y: 3 }));+ raf.flush();+ expect(stagedDraws(screen.surface)).toHaveLength(0);+ engine.dispose();+ });});describe('commitRasterFilterResult', () => {@@ -5497,6 +5539,886 @@ describe('commitRasterFilterResult', () => {});});+describe('commitGeneratedImageResult', () => {+ const generatedImage = { height: 18, imageName: 'workflow-result.png', width: 24 };+ const generatedOrigin = { x: -9, y: 14 };++ const workflowRaster = (id = 'source'): CanvasRasterLayerContractV2 => ({+ adjustments: { brightness: 0.2, contrast: -0.1, saturation: 0.3 },+ blendMode: 'multiply',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 0.65,+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ transform: { rotation: 0.4, scaleX: 2, scaleY: 3, x: 5, y: 6 },+ type: 'raster',+ });++ const workflowControl = (id = 'source'): CanvasLayerContract => ({+ adapter: {+ beginEndStepPct: [0.15, 0.85],+ controlMode: 'more_control',+ kind: 'controlnet',+ model: 'control-model',+ weight: 0.7,+ },+ blendMode: 'screen',+ filter: { settings: { low: 12, high: 90 }, type: 'canny' },+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 0.55,+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ transform: { rotation: -0.3, scaleX: 1.5, scaleY: 0.75, x: 11, y: -4 },+ type: 'control',+ withTransparencyEffect: true,+ });++ const workflowDocument = (layers: CanvasLayerContract[] = [workflowRaster()]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ layers,+ selectedLayerId: layers.at(-1)?.id ?? null,+ version: 2,+ width: 100,+ });++ const createGeneratedFaultBackend = () => {+ const base = createTestStubRasterBackend();+ let allocationCountdown: number | null = null;+ let drawCountdown: number | null = null;+ let createHook: { countdown: number; run: () => void } | null = null;+ const backend: StubRasterBackend = {+ ...base,+ createSurface: (width, height) => {+ if (allocationCountdown !== null) {+ if (allocationCountdown === 0) {+ allocationCountdown = null;+ throw new Error('generated cache allocation failed');+ }+ allocationCountdown -= 1;+ }+ if (createHook) {+ if (createHook.countdown === 0) {+ const hook = createHook;+ createHook = null;+ hook.run();+ } else {+ createHook.countdown -= 1;+ }+ }+ const surface = base.createSurface(width, height);+ const ctx = new Proxy(surface.ctx, {+ get: (target, property, receiver) => {+ const value = Reflect.get(target, property, receiver);+ if (property !== 'drawImage' || typeof value !== 'function') {+ return value;+ }+ return (...args: unknown[]) => {+ if (drawCountdown !== null) {+ if (drawCountdown === 0) {+ drawCountdown = null;+ throw new Error('generated cache draw failed');+ }+ drawCountdown -= 1;+ }+ return Reflect.apply(value, target, args);+ };+ },+ });+ Object.defineProperty(surface, 'ctx', { value: ctx });+ return surface;+ },+ };+ return {+ armAllocation: (successfulCreates: number) => {+ allocationCountdown = successfulCreates;+ },+ armCreateHook: (successfulCreates: number, run: () => void) => {+ createHook = { countdown: successfulCreates, run };+ },+ armDraw: (successfulDraws: number) => {+ drawCountdown = successfulDraws;+ },+ backend,+ };+ };++ it('replaces a raster at the generated origin and native size, clears baked adjustments, and replays exactly', async () => {+ const source = workflowRaster();+ const before = structuredClone(source);+ const backend = createRecordingRasterBackend();+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('workflow-result')));+ const bitmapStore = createSpyBitmapStore();+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend,+ bitmapStore,+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }++ const result = await engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ });++ expect(result).toEqual({ layerId: source.id, status: 'committed' });+ const after = engine.getDocument()!.layers[0]!;+ expect(after).toEqual({+ blendMode: source.blendMode,+ id: source.id,+ isEnabled: source.isEnabled,+ isLocked: source.isLocked,+ name: source.name,+ opacity: source.opacity,+ source: { bitmap: generatedImage, offset: generatedOrigin, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect('adjustments' in after).toBe(false);+ const committedPixels = await engine.exportLayerPixels(source.id);+ expect(committedPixels.status).toBe('ok');+ if (committedPixels.status === 'ok') {+ expect(committedPixels.rect).toEqual({ ...generatedOrigin, height: 18, width: 24 });+ expect(drawGraphContains(committedPixels.surface as StubRasterSurface, backend, 'bitmap-workflow-result')).toBe(+ true+ );+ }+ expect(engine.stores.canUndo.get()).toBe(true);++ engine.undo();+ expect(engine.getDocument()!.layers[0]).toEqual(before);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);++ engine.redo();+ expect(engine.getDocument()!.layers[0]).toEqual(after);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);+ expect(bitmapStore.discardLayer).toHaveBeenCalledTimes(2);+ engine.dispose();+ });++ it('replaces a control while preserving adapter, filter, transparency effect, and layer presentation', async () => {+ const source = workflowControl();+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ })+ ).resolves.toEqual({ layerId: source.id, status: 'committed' });++ expect(engine.getDocument()!.layers[0]).toEqual({+ ...source,+ source: { bitmap: generatedImage, offset: generatedOrigin, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ engine.undo();+ expect(engine.getDocument()!.layers[0]).toEqual(source);+ engine.redo();+ expect(engine.getDocument()!.layers[0]).toMatchObject({+ adapter: source.type === 'control' ? source.adapter : undefined,+ filter: source.type === 'control' ? source.filter : undefined,+ withTransparencyEffect: true,+ });+ engine.dispose();+ });++ it('copies a generated result to an unlocked raster immediately above its source and restores selection on undo', async () => {+ const above = workflowRaster('above');+ const source = workflowControl('source');+ const selected = workflowRaster('selected');+ const document = { ...workflowDocument([above, source, selected]), selectedLayerId: selected.id };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }++ const result = await engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'copy-raster',+ });+ if (result.status !== 'committed') {+ throw new Error(`expected a committed copy, received ${JSON.stringify(result)}`);+ }++ expect(engine.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ above.id,+ result.layerId,+ source.id,+ selected.id,+ ]);+ expect(engine.getDocument()!.layers[2]).toEqual(source);+ expect(engine.getDocument()!.layers[1]).toMatchObject({+ id: result.layerId,+ isEnabled: true,+ isLocked: false,+ opacity: 1,+ source: { bitmap: generatedImage, offset: generatedOrigin, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect(engine.getDocument()!.selectedLayerId).toBe(result.layerId);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.redo();+ expect(engine.getDocument()!.layers[1]?.id).toBe(result.layerId);+ expect(engine.getDocument()!.selectedLayerId).toBe(result.layerId);+ expect(engine.stores.canRedo.get()).toBe(false);+ engine.dispose();+ });++ const createPendingGuardHarness = async () => {+ const source = workflowRaster();+ const document = workflowDocument([source]);+ const decoded = createDeferred<Blob>();+ const reactive = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: (imageName) =>+ imageName === generatedImage.imageName ? decoded.promise : Promise.resolve(new Blob()),+ projectId: 'p1',+ store: reactive.store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ (reactive.store.dispatch as Mock).mockClear();+ const pending = engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ });+ return { ...reactive, decoded, document, engine, exported, pending, source };+ };++ it('returns failed without mutation when the durable generated image cannot be resolved', async () => {+ const source = workflowRaster();+ const document = workflowDocument([source]);+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: (imageName) =>+ imageName === generatedImage.imageName+ ? Promise.reject(new Error('generated decode failed'))+ : Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ (store.dispatch as Mock).mockClear();++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ })+ ).resolves.toEqual({ message: 'generated decode failed', status: 'failed' });+ expect(engine.getDocument()).toEqual(document);+ expect(store.dispatch).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.dispose();+ });++ it('returns missing after decode when the source was deleted', async () => {+ const harness = await createPendingGuardHarness();+ harness.setDocument({ ...harness.document, layers: [] });+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'missing' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns locked after decode when the source became locked', async () => {+ const harness = await createPendingGuardHarness();+ harness.setDocument({ ...harness.document, layers: [{ ...harness.source, isLocked: true }] });+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'locked' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns unsupported after decode when the source became a mask', async () => {+ const harness = await createPendingGuardHarness();+ harness.setDocument({ ...harness.document, layers: [maskLayer(harness.source.id)] });+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'unsupported' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns stale after decode when the immutable source contract changed', async () => {+ const harness = await createPendingGuardHarness();+ harness.setDocument({ ...harness.document, layers: [{ ...harness.source, opacity: 0.1 }] });+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'stale' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns stale after decode when the document was replaced with the same source object', async () => {+ const harness = await createPendingGuardHarness();+ harness.setDocument({ ...harness.document, width: 200 }, 1);+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'stale' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns stale after decode when another project became active', async () => {+ const harness = await createPendingGuardHarness();+ harness.setActiveProjectId('p2');+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'stale' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns busy after decode while a pointer gesture is open', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const harness = await createPendingGuardHarness();+ const overlay = createInputCanvas();+ harness.engine.attach(createInputCanvas().element, overlay.element);+ overlay.fire('pointerdown', pointerAt(5, 5));+ harness.decoded.resolve(new Blob());+ await expect(harness.pending).resolves.toEqual({ status: 'busy' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns aborted without resolving the generated image when already cancelled', async () => {+ const source = workflowRaster();+ const resolver = vi.fn(() => Promise.resolve(new Blob()));+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: resolver,+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ resolver.mockClear();+ const controller = new AbortController();+ controller.abort();++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ signal: controller.signal,+ target: 'replace',+ })+ ).resolves.toEqual({ status: 'aborted' });+ expect(resolver).not.toHaveBeenCalled();+ expect(engine.getDocument()).toEqual(workflowDocument([source]));+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.dispose();+ });++ it('returns aborted during bitmap decode, releases the late bitmap, and never mutates', async () => {+ const source = workflowRaster();+ const bitmapDeferred = createDeferred<ImageBitmap>();+ const bitmap = recordingBitmap('late-generated');+ const base = createTestStubRasterBackend();+ const createImageBitmap = vi.fn(() => bitmapDeferred.promise);+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend: { ...base, createImageBitmap },+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ const controller = new AbortController();+ const pending = engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ signal: controller.signal,+ target: 'replace',+ });+ await vi.waitFor(() => expect(createImageBitmap).toHaveBeenCalledOnce());++ controller.abort();+ bitmapDeferred.resolve(bitmap);++ await expect(pending).resolves.toEqual({ status: 'aborted' });+ expect(bitmap.close).toHaveBeenCalledOnce();+ expect(engine.getDocument()).toEqual(workflowDocument([source]));+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.dispose();+ });++ it('returns stale when unpersisted paint pixels change while the generated image resolves', async () => {+ vi.stubGlobal('Path2D', class FakePath2D {});+ const source: CanvasRasterLayerContractV2 = {+ ...workflowRaster(),+ source: {+ bitmap: { height: 10, imageName: 'workflow-paint-source.png', width: 10 },+ type: 'paint',+ },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ };+ const generatedBlob = createDeferred<Blob>();+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: (imageName) =>+ imageName === generatedImage.imageName ? generatedBlob.promise : Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ const pending = engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ });++ engine.selectAll();+ engine.fillSelection();+ const afterPaintEdit = structuredClone(engine.getDocument()!);+ generatedBlob.resolve(new Blob());++ await expect(pending).resolves.toEqual({ status: 'stale' });+ expect(engine.getDocument()).toEqual(afterPaintEdit);+ expect(engine.getDocument()!.layers[0]).not.toMatchObject({ source: { bitmap: generatedImage } });+ expect(engine.stores.canUndo.get()).toBe(true);+ engine.dispose();+ });++ it.each([+ { successfulCreates: 0, target: 'replace' as const },+ { successfulCreates: 2, target: 'replace' as const },+ { successfulCreates: 1, target: 'copy-raster' as const },+ ])(+ 'leaves document, cache, selection, and history exact when $target allocation fails after $successfulCreates successful creates',+ async ({ successfulCreates, target }) => {+ const source = workflowRaster();+ const selected = workflowRaster('selected');+ const document = { ...workflowDocument([source, selected]), selectedLayerId: selected.id };+ const faults = createGeneratedFaultBackend();+ const bitmap = recordingBitmap('allocation-failure');+ faults.backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ const cache = exported.surface;+ const cacheCalls = structuredClone((cache as StubRasterSurface).callLog);+ (store.dispatch as Mock).mockClear();+ faults.armAllocation(successfulCreates);++ const result = await engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target,+ });++ expect(result).toEqual({ message: 'generated cache allocation failed', status: 'failed' });+ expect(bitmap.close).toHaveBeenCalledOnce();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.getDocument()!.selectedLayerId).toBe(selected.id);+ expect(store.dispatch).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(false);+ const after = await engine.exportLayerPixels(source.id);+ expect(after.status).toBe('ok');+ if (after.status === 'ok') {+ expect(after.surface).toBe(cache);+ expect(after.guard.cacheVersion).toBe(exported.guard.cacheVersion);+ expect((after.surface as StubRasterSurface).callLog).toEqual(cacheCalls);+ }+ engine.dispose();+ }+ );++ it.each([+ { successfulDraws: 0, target: 'replace' as const },+ { successfulDraws: 2, target: 'replace' as const },+ { successfulDraws: 1, target: 'copy-raster' as const },+ ])(+ 'leaves document, cache, selection, and history exact when $target draw fails after $successfulDraws successful draws',+ async ({ successfulDraws, target }) => {+ const source = workflowRaster();+ const selected = workflowRaster('selected');+ const document = { ...workflowDocument([source, selected]), selectedLayerId: selected.id };+ const faults = createGeneratedFaultBackend();+ const bitmap = recordingBitmap('draw-failure');+ faults.backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ const cache = exported.surface;+ const cacheCalls = structuredClone((cache as StubRasterSurface).callLog);+ (store.dispatch as Mock).mockClear();+ faults.armDraw(successfulDraws);++ const result = await engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target,+ });++ expect(result).toEqual({ message: 'generated cache draw failed', status: 'failed' });+ expect(bitmap.close).toHaveBeenCalledOnce();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.getDocument()!.selectedLayerId).toBe(selected.id);+ expect(store.dispatch).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(false);+ const after = await engine.exportLayerPixels(source.id);+ expect(after.status).toBe('ok');+ if (after.status === 'ok') {+ expect(after.surface).toBe(cache);+ expect(after.guard.cacheVersion).toBe(exported.guard.cacheVersion);+ expect((after.surface as StubRasterSurface).callLog).toEqual(cacheCalls);+ }+ engine.dispose();+ }+ );++ it.each([+ { successfulCreates: 2, target: 'replace' as const },+ { successfulCreates: 1, target: 'copy-raster' as const },+ ])(+ 'returns aborted without mutation when $target is cancelled during cache preparation',+ async ({ successfulCreates, target }) => {+ const source = workflowRaster();+ const document = workflowDocument([source]);+ const faults = createGeneratedFaultBackend();+ const controller = new AbortController();+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ (store.dispatch as Mock).mockClear();+ faults.armCreateHook(successfulCreates, () => controller.abort());++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ signal: controller.signal,+ target,+ })+ ).resolves.toEqual({ status: 'aborted' });+ expect(engine.getDocument()).toEqual(document);+ expect(store.dispatch).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.dispose();+ }+ );++ it.each([+ { successfulCreates: 2, target: 'replace' as const },+ { successfulCreates: 1, target: 'copy-raster' as const },+ ])('revalidates the exact guard immediately before $target publication', async ({ successfulCreates, target }) => {+ const source = workflowRaster();+ const document = workflowDocument([source]);+ const reactive = createReactiveStore(document);+ const faults = createGeneratedFaultBackend();+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store: reactive.store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ (reactive.store.dispatch as Mock).mockClear();+ faults.armCreateHook(successfulCreates, () => {+ reactive.setDocument({ ...document, layers: [{ ...source, opacity: 0.2 }] });+ });++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target,+ })+ ).resolves.toEqual({ status: 'stale' });+ expect(reactive.store.dispatch).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.dispose();+ });++ it('keeps replace undo and redo retryable when detached cache preparation fails', async () => {+ const source = workflowRaster();+ const document = workflowDocument([source]);+ const faults = createGeneratedFaultBackend();+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ })+ ).resolves.toEqual({ layerId: source.id, status: 'committed' });+ const committed = structuredClone(engine.getDocument()!);++ faults.armAllocation(0);+ expect(() => engine.undo()).toThrow('generated cache allocation failed');+ expect(engine.getDocument()).toEqual(committed);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);++ faults.armDraw(0);+ expect(() => engine.redo()).toThrow('generated cache draw failed');+ expect(engine.getDocument()).toEqual(document);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);++ engine.redo();+ expect(engine.getDocument()).toEqual(committed);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);+ engine.dispose();+ });++ it('keeps copy redo retryable, absent, and selection-exact when detached cache preparation fails', async () => {+ const source = workflowRaster();+ const selected = workflowRaster('selected');+ const document = { ...workflowDocument([source, selected]), selectedLayerId: selected.id };+ const faults = createGeneratedFaultBackend();+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: faults.backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ const result = await engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'copy-raster',+ });+ if (result.status !== 'committed') {+ throw new Error('expected a committed workflow copy');+ }+ const committed = structuredClone(engine.getDocument()!);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ faults.armAllocation(0);+ expect(() => engine.redo()).toThrow('generated cache allocation failed');+ expect(engine.getDocument()).toEqual(document);+ expect(engine.getDocument()!.selectedLayerId).toBe(selected.id);+ expect(engine.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(false);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);++ engine.redo();+ expect(engine.getDocument()).toEqual(committed);+ expect(engine.getDocument()!.selectedLayerId).toBe(result.layerId);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);+ engine.dispose();+ });++ it('reloads a replaced generated image from its durable bitmap contract', async () => {+ const source = workflowRaster();+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ })+ ).resolves.toEqual({ layerId: source.id, status: 'committed' });+ const reloadedDocument = structuredClone(engine.getDocument()!);+ engine.dispose();++ const reloadedStore = createReducerBackedStore(reloadedDocument);+ const resolver = vi.fn(() => Promise.resolve(new Blob()));+ const reloadedEngine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: resolver,+ projectId: reloadedStore.projectId,+ store: reloadedStore.store,+ });+ expect((await reloadedEngine.exportLayerPixels(source.id)).status).toBe('ok');+ expect(resolver).toHaveBeenCalledWith(generatedImage.imageName);+ reloadedEngine.dispose();+ });++ it('clears an unguarded control-filter preview when replacing the control with a workflow result', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const source = workflowControl();+ const backend = createRecordingRasterBackend();+ let bitmapCall = 0;+ backend.createImageBitmap = vi.fn(() =>+ Promise.resolve(recordingBitmap(bitmapCall++ === 0 ? 'control-preview' : 'workflow-result'))+ );+ const { projectId, store } = createReducerBackedStore(workflowDocument([source]));+ const engine = createCanvasEngine({+ backend,+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const screen = createFakeCanvas();+ engine.attach(screen.element, createFakeCanvas().element);+ raf.flush();+ const exported = await engine.exportLayerPixels(source.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an exportable workflow source');+ }+ engine.setFilterPreview(source.id, { imageName: 'control-preview.png' });+ await flushMicrotasks();+ raf.flush();+ expect(drawGraphContains(screen.surface, backend, 'bitmap-control-preview')).toBe(true);+ screen.surface.callLog.length = 0;++ await expect(+ engine.commitGeneratedImageResult({+ guard: exported.guard,+ image: generatedImage,+ origin: generatedOrigin,+ target: 'replace',+ })+ ).resolves.toEqual({ layerId: source.id, status: 'committed' });+ raf.flush();++ expect(drawGraphContains(screen.surface, backend, 'bitmap-control-preview')).toBe(false);+ expect(drawGraphContains(screen.surface, backend, 'bitmap-workflow-result')).toBe(true);+ engine.dispose();+ });+});+describe('replaceSelectionFromImage', () => {const resultImage = { height: 10, imageName: 'sam-result.png', width: 10 };const resultRect = { height: 10, width: 10, x: -7, y: 13 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 719b2a4f80..db25e23b0e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -126,10 +126,17 @@ import { createViewTool } from './tools/viewTool';/*** The input to {@link CanvasEngine.setStagedPreview}: either a persisted image* (decoded via the engine's `imageResolver`, sized to the decoded pixels — the- * final staged candidate) or an inline data-URL with explicit document-space- * dimensions (a live denoise-progress frame, scaled to fill those dims).+ * final staged candidate, optionally with candidate-specific placement) or an+ * inline data-URL with explicit document-space dimensions (a live+ * denoise-progress frame, scaled to fill those dims at the current bbox).*/-export type StagedPreviewInput = { imageName: string } | { dataUrl: string; width: number; height: number };+export interface StagedPreviewPlacement extends Rect {+ opacity: number;+}++export type StagedPreviewInput =+ | { imageName: string; placement?: StagedPreviewPlacement }+ | { dataUrl: string; width: number; height: number };/*** Result of {@link CanvasEngine.mergeVisibleRasterLayers}: `'merged'` when the@@ -164,6 +171,21 @@ export interface CommitRasterFilterOptions {signal?: AbortSignal;}+export type GeneratedImageTarget = 'replace' | 'copy-raster';++export type CommitGeneratedImageResult =+ | { status: 'committed'; layerId: string }+ | { status: 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' | 'aborted' }+ | { status: 'failed'; message: string };++export interface CommitGeneratedImageOptions {+ guard: LayerExportGuard;+ image: CanvasImageRef;+ origin: Vec2;+ target: GeneratedImageTarget;+ signal?: AbortSignal;+}+export type ReplaceSelectionFromImageResult =| { status: 'selected' }| { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' }@@ -436,6 +458,8 @@ export interface CanvasEngine {cropLayerToBbox(layerId: string): Promise<CropLayerResult>;/** Commits a durable raster-filter result only while its export guard remains current. */commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;+ /** Replaces or copies a layer with a durable generated image while its export guard remains current. */+ commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;/** Adds a durable SAM image as a new mask layer while its source export guard remains current. */commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;/** Creates a new raster paint layer above `layerId` from that layer's baked pixels. */@@ -564,17 +588,17 @@ export interface CanvasEngine {*/nudgeSelectedLayer(dx: number, dy: number): void;/**- * Shows a staged generation preview drawn over the CURRENT bbox on the- * composited canvas (above committed layers), or clears it with `null`.+ * Shows a staged generation preview above committed layers, or clears it with+ * `null`. A final `imageName` candidate may provide its own placement; legacy+ * candidates and live `dataUrl` progress frames follow the CURRENT bbox.** The input is decoded to a surface off the main path — an `imageName` through- * the engine's `imageResolver` (the final candidate, drawn at the decoded- * pixel size), or a `dataUrl` with explicit dims (a live progress frame,- * scaled to those dims). Decoding is async and latest-call-wins: a stale- * decode resolving after a newer `setStagedPreview`/clear is discarded- * (version-guarded like the rasterize path), so rapid candidate cycling never- * flashes an older result. The preview's top-left tracks the bbox at render- * time, matching where `acceptStagedImage` places the accepted layer.+ * the engine's `imageResolver`, or a `dataUrl` with explicit dimensions.+ * Decoding is async and latest-call-wins: a stale decode resolving after a+ * newer `setStagedPreview`/clear is discarded (version-guarded like the+ * rasterize path), so rapid candidate cycling never flashes an older result.+ * Explicit placement matches candidate acceptance; otherwise the preview's+ * top-left tracks the bbox at render time.*/setStagedPreview(input: StagedPreviewInput | null): void;/**@@ -776,7 +800,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// `stagedPreviewToken` version-guards the async decode: every set/clear bumps// it, and a decode whose token no longer matches is dropped so a slow decode// can't clobber a newer selection (mirrors the rasterize race guard).- let stagedPreview: { surface: RasterSurface; width: number; height: number } | null = null;+ let stagedPreview: {+ surface: RasterSurface;+ width: number;+ height: number;+ placement?: StagedPreviewPlacement;+ } | null = null;let stagedPreviewToken = 0;// Completed-stroke subscribers (persistence P2.2, history P2.3).const strokeListeners = new Set<(event: StrokeCommittedEvent) => void>();@@ -1716,25 +1745,36 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {/** Decodes a staged-preview input to a surface (imageName via resolver, dataUrl via the backend seam). */const decodeStagedPreview = async (input: StagedPreviewInput- ): Promise<{ surface: RasterSurface; width: number; height: number }> => {+ ): Promise<{ surface: RasterSurface; width: number; height: number; placement?: StagedPreviewPlacement }> => {if ('imageName' in input) {const blob = await imageResolver(input.imageName);const bitmap = await backend.createImageBitmap(blob);const width = bitmap.width;const height = bitmap.height;+ try {+ const surface = backend.createSurface(width, height);+ surface.ctx.clearRect(0, 0, width, height);+ surface.ctx.drawImage(bitmap, 0, 0);+ return {+ height,+ placement: input.placement ? { ...input.placement } : undefined,+ surface,+ width,+ };+ } finally {+ bitmap.close();+ }+ }+ const { dataUrl, height, width } = input;+ const bitmap = await backend.createImageBitmap(dataUrlToBlob(dataUrl));+ try {const surface = backend.createSurface(width, height);surface.ctx.clearRect(0, 0, width, height);- surface.ctx.drawImage(bitmap, 0, 0);- bitmap.close();+ surface.ctx.drawImage(bitmap, 0, 0, width, height);return { height, surface, width };+ } finally {+ bitmap.close();}- const { dataUrl, height, width } = input;- const bitmap = await backend.createImageBitmap(dataUrlToBlob(dataUrl));- const surface = backend.createSurface(width, height);- surface.ctx.clearRect(0, 0, width, height);- surface.ctx.drawImage(bitmap, 0, 0, width, height);- bitmap.close();- return { height, surface, width };};const setStagedPreview = (input: StagedPreviewInput | null): void => {@@ -1942,6 +1982,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const needsComposite = flags.all || flags.view || flags.layers.size > 0;if (needsComposite) {ensureLayerCaches(doc);+ const stagedPlacement = stagedPreview?.placement;compositeDocument(screen, doc, layerCache, view, {// Memoized adjusted surfaces for raster layers with brightness/contrast/// saturation/curves (not recomputed per frame — see adjustedSurfaceCache).@@ -1962,11 +2003,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// Crisp + cheap when zoomed in (nearest-neighbor up-scale), smooth when// shrinking (bilinear down-scale). See `shouldSmoothAtZoom`.imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),- // The preview's origin follows the CURRENT bbox so it lands exactly where- // `acceptStagedImage` would place the accepted layer (bbox x/y, unscaled).+ // Candidate-specific placement wins for final images. Progress frames+ // and legacy image inputs continue to follow the CURRENT bbox origin.stagedPreview: stagedPreview? {- rect: { height: stagedPreview.height, width: stagedPreview.width, x: doc.bbox.x, y: doc.bbox.y },+ opacity: stagedPlacement?.opacity ?? 1,+ rect: stagedPlacement+ ? {+ height: stagedPlacement.height,+ width: stagedPlacement.width,+ x: stagedPlacement.x,+ y: stagedPlacement.y,+ }+ : { height: stagedPreview.height, width: stagedPreview.width, x: doc.bbox.x, y: doc.bbox.y },surface: stagedPreview.surface,}: null,@@ -2029,10 +2078,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const mirror: DocumentMirror = createDocumentMirror(store, projectId, {// The bbox rectangle/handles are overlay chrome, so a bbox move is normally- // overlay-only (no recomposite). The one exception: a staged-generation- // preview is drawn in the COMPOSITE at the current bbox origin, so while one- // is active the document must recomposite to reposition it with the bbox.- onBboxChanged: () => scheduler.invalidate(stagedPreview ? { all: true } : { overlay: true }),+ // overlay-only (no recomposite). The one exception: a legacy/progress staged+ // preview is drawn in the COMPOSITE at the current bbox origin, so it must+ // recomposite to follow the bbox. Explicitly placed candidates do not.+ onBboxChanged: () =>+ scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true }),onDocumentReplaced: () => {rasterDocumentGeneration += 1;layerRasterizationJobs.clear();@@ -3012,6 +3062,225 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}};+ const commitGeneratedImageResult = async (+ options: CommitGeneratedImageOptions+ ): Promise<CommitGeneratedImageResult> => {+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }++ const validateGuard = ():+ | {+ document: CanvasDocumentContractV2;+ liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;+ }+ | { result: CommitGeneratedImageResult } => {+ const document = mirror.getDocument();+ const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);+ if (!document || !liveLayer) {+ return { result: { status: 'missing' } };+ }+ if (liveLayer.isLocked) {+ return { result: { status: 'locked' } };+ }+ if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {+ return { result: { status: 'unsupported' } };+ }+ if (pipeline.isGestureActive()) {+ return { result: { status: 'busy' } };+ }+ if (!isLayerExportGuardCurrent(options.guard)) {+ return { result: { status: 'stale' } };+ }+ return { document, liveLayer };+ };++ try {+ const blob = await imageResolver(options.image.imageName, options.signal);+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }++ const bitmap = await backend.createImageBitmap(blob);+ if (options.signal?.aborted) {+ bitmap.close();+ return { status: 'aborted' };+ }++ let generatedPixels: RasterSurface;+ try {+ generatedPixels = backend.createSurface(options.image.width, options.image.height);+ generatedPixels.ctx.setTransform(1, 0, 0, 1, 0, 0);+ generatedPixels.ctx.clearRect(0, 0, options.image.width, options.image.height);+ generatedPixels.ctx.drawImage(bitmap, 0, 0, options.image.width, options.image.height);+ } finally {+ bitmap.close();+ }+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }++ const checked = validateGuard();+ if ('result' in checked) {+ return checked.result;+ }+ const { document, liveLayer } = checked;+ const image = structuredClone(options.image);+ const origin = { ...options.origin };+ const rect = { height: image.height, width: image.width, ...origin };+ const source = { bitmap: image, offset: origin, type: 'paint' } as const;+ const identityTransform: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++ const publishSnapshot = (+ contract: CanvasLayerContract,+ prepared: ReturnType<LayerCacheStore['prepareReplacement']>,+ publishOptions: { discardPersistence: boolean; persist: boolean }+ ): void => {+ dispatchPreparedMutation(+ { layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },+ () => getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,+ () => mirror.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ );+ if (publishOptions.discardPersistence) {+ try {+ bitmapStore.discardLayer(liveLayer.id);+ } catch {+ // Persistence generation cancellation is ancillary once the durable+ // contract has been accepted by the reducer.+ }+ }+ try {+ clearFilterPreview(liveLayer.id);+ } catch {+ // A transient preview is ancillary to the committed document/cache.+ }+ installGeneratedPaintCache(prepared, publishOptions.persist);+ };++ const applySnapshot = (+ contract: CanvasLayerContract,+ snapshot: { pixels: RasterSurface; rect: Rect },+ publishOptions: { discardPersistence: boolean; persist: boolean }+ ): void => {+ const prepared = prepareGeneratedPaintCache(liveLayer.id, snapshot.rect, snapshot.pixels);+ publishSnapshot(contract, prepared, publishOptions);+ };++ if (options.target === 'replace') {+ const beforePixels = captureLayerCache(liveLayer, document);+ if (!beforePixels || beforePixels === 'not-ready') {+ return { status: 'stale' };+ }+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }++ const before = structuredClone(liveLayer);+ let after: CanvasLayerContract;+ if (liveLayer.type === 'raster') {+ const { adjustments: _adjustments, ...base } = structuredClone(liveLayer);+ after = { ...base, source, transform: identityTransform };+ } else {+ after = { ...structuredClone(liveLayer), source, transform: identityTransform };+ }+ const afterPixels = { pixels: generatedPixels, rect };+ const preparedAfter = prepareGeneratedPaintCache(liveLayer.id, rect, generatedPixels);++ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ const finalCheck = validateGuard();+ if ('result' in finalCheck) {+ return finalCheck.result;+ }++ endNudgeBurst();+ publishSnapshot(after, preparedAfter, { discardPersistence: true, persist: false });+ history.push({+ bytes:+ beforePixels.rect.width * beforePixels.rect.height * 4 ++ afterPixels.rect.width * afterPixels.rect.height * 4 ++ 256,+ label: 'Replace layer with workflow result',+ redo: () => applySnapshot(after, afterPixels, { discardPersistence: true, persist: false }),+ replayFailureAtomic: true,+ undo: () =>+ applySnapshot(before, beforePixels, {+ discardPersistence: false,+ persist: layerNeedsPixelPersistence(before),+ }),+ });+ return { layerId: liveLayer.id, status: 'committed' };+ }++ const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);+ if (sourceIndex < 0) {+ return { status: 'missing' };+ }+ const layerId = createLayerId();+ const selectedLayerId = document.selectedLayerId;+ const copy: CanvasLayerContract = {+ blendMode: 'normal',+ id: layerId,+ isEnabled: true,+ isLocked: false,+ name: `${liveLayer.name} workflow result`,+ opacity: 1,+ source,+ transform: identityTransform,+ type: 'raster',+ };+ const publishCopy = (prepared: ReturnType<LayerCacheStore['prepareReplacement']>): void => {+ dispatchPreparedMutation(+ { index: sourceIndex, layer: copy, type: 'addCanvasLayer' },+ () => getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,+ () => mirror.getDocument()?.layers.some((candidate) => candidate === copy) === true+ );+ installGeneratedPaintCache(prepared, false);+ };+ const applyCopy = (): void => {+ const prepared = prepareGeneratedPaintCache(layerId, rect, generatedPixels);+ publishCopy(prepared);+ };+ const preparedCopy = prepareGeneratedPaintCache(layerId, rect, generatedPixels);++ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ const finalCheck = validateGuard();+ if ('result' in finalCheck) {+ return finalCheck.result;+ }++ endNudgeBurst();+ publishCopy(preparedCopy);+ history.push({+ bytes: rect.width * rect.height * 4 + 256,+ label: 'Copy workflow result to raster layer',+ redo: applyCopy,+ replayFailureAtomic: true,+ undo: () => {+ dispatchPreparedMutation(+ { id: selectedLayerId, type: 'setCanvasSelectedLayer' },+ () => getReducerDocument()?.selectedLayerId === selectedLayerId,+ () => mirror.getDocument()?.selectedLayerId === selectedLayerId+ );+ dispatchPreparedMutation(+ { ids: [layerId], type: 'removeCanvasLayers' },+ () => getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,+ () => mirror.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ );+ },+ });+ return { layerId, status: 'committed' };+ } catch (error) {+ if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {+ return { status: 'aborted' };+ }+ return { message: error instanceof Error ? error.message : String(error), status: 'failed' };+ }+ };+const booleanMergeRasterLayers = async (upperLayerId: string,operation: BooleanRasterOperation@@ -4598,6 +4867,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {attach,cancelTextEdit,cancelTransform,+ commitGeneratedImageResult,commitOpenTextSession,commitLayerConversion,commitLayerCopy,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex ee4565cf4f..26e5cbe6ed 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -405,6 +405,26 @@ describe('compositeDocument', () => {expect(drawImages).toHaveLength(1);expect(drawImages[0]!.args).toEqual([staged.canvas, 5, 5, 40, 40]);});++ it('draws a placed staged preview at its candidate opacity and keeps the pending outline opaque', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ const target = backend.createSurface(200, 200);+ const staged = backend.createSurface(23, 17);++ compositeDocument(target, makeDoc([]), caches, VIEW, {+ stagedPreview: {+ opacity: 0.35,+ rect: { height: 34, width: 46, x: -8, y: 13 },+ surface: staged,+ },+ });++ const drawImages = target.callLog.filter((entry) => entry.op === 'drawImage');+ expect(drawImages).toHaveLength(1);+ expect(drawImages[0]!.args).toEqual([staged.canvas, -8, 13, 46, 34]);+ expect(findSet(target.callLog, 'globalAlpha')).toEqual([0.35, 1]);+ });});describe('compositeDocument — raster adjustments', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex c64e4218f4..ca1a34acc9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -80,8 +80,8 @@ const STAGED_PREVIEW_OUTLINE_DASH = 6;/** Optional inputs to {@link compositeDocument}. */export interface CompositeOptions {- /** A staged generation candidate to draw over its bbox (document space). */- stagedPreview?: { surface: RasterSurface; rect: Rect } | null;+ /** A staged generation candidate to draw at its placement (document space). */+ stagedPreview?: { surface: RasterSurface; rect: Rect; opacity?: number } | null;/*** The cached checkerboard pattern tile (see {@link createCheckerboardTile}) to* fill the ENTIRE viewport with (the canvas is an unbounded plane — the checker@@ -360,6 +360,7 @@ export const compositeDocument = (if (staged) {ctx.save();setTransformFromMat(ctx, view);+ ctx.globalAlpha = staged.opacity ?? 1;ctx.drawImage(staged.surface.canvas, staged.rect.x, staged.rect.y, staged.rect.width, staged.rect.height);// Keep the outline visually constant regardless of zoom by dividing the// document-space stroke by the view scale (√det of the linear part).diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.test.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.test.tsindex 51e553e140..4d11fcf874 100644--- a/invokeai/frontend/webv2/src/workbench/gallery/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.test.ts@@ -1,6 +1,74 @@-import { describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { imageMakeDurableChanges, imageSaveToGalleryChanges } from './api';+const mocks = vi.hoisted(() => ({+ apiFetchJson: vi.fn(),+}));++vi.mock('@workbench/backend/http', () => ({+ absolutizeApiUrl: (url: string) => `https://api.test${url}`,+ apiFetch: vi.fn(),+ apiFetchJson: mocks.apiFetchJson,+ apiFetchRaw: vi.fn(),+ sleep: vi.fn(),+}));++import { getGalleryImageByName, imageMakeDurableChanges, imageSaveToGalleryChanges } from './api';++describe('getGalleryImageByName', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ });++ it('encodes the image name, forwards the abort signal, and maps the backend image', async () => {+ const controller = new AbortController();+ mocks.apiFetchJson.mockResolvedValue({+ board_id: 'board-1',+ created_at: '2026-07-09T12:00:00.000Z',+ height: 360,+ image_category: 'general',+ image_name: 'folder/workflow result.png',+ image_url: '/images/workflow-result.png',+ is_intermediate: false,+ starred: true,+ thumbnail_url: '/thumbnails/workflow-result.webp',+ width: 640,+ });++ await expect(getGalleryImageByName('folder/workflow result.png', controller.signal)).resolves.toEqual({+ boardId: 'board-1',+ height: 360,+ imageCategory: 'general',+ imageName: 'folder/workflow result.png',+ imageUrl: 'https://api.test/images/workflow-result.png',+ queuedAt: '2026-07-09T12:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ starred: true,+ thumbnailUrl: 'https://api.test/thumbnails/workflow-result.webp',+ width: 640,+ });+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/images/i/folder%2Fworkflow%20result.png', {+ signal: controller.signal,+ });+ });++ it('propagates backend lookup errors', async () => {+ const error = new Error('404 image not found');+ mocks.apiFetchJson.mockRejectedValue(error);++ await expect(getGalleryImageByName('missing.png')).rejects.toBe(error);+ });++ it('propagates request aborts', async () => {+ const controller = new AbortController();+ const error = new DOMException('The operation was aborted.', 'AbortError');+ mocks.apiFetchJson.mockRejectedValue(error);++ const result = getGalleryImageByName('workflow.png', controller.signal);+ controller.abort();++ await expect(result).rejects.toBe(error);+ });+});describe('imageSaveToGalleryChanges', () => {it('promotes an intermediate candidate to a durable, gallery-visible image', () => {@@ -11,10 +79,9 @@ describe('imageSaveToGalleryChanges', () => {});describe('imageMakeDurableChanges', () => {- it('clears is_intermediate WITHOUT touching image_category (durable but not in gallery)', () => {- // Applying a control-filter preview makes the chosen image the layer's new- // source: it must survive GC (is_intermediate: false) but stay out of the- // gallery images view (no image_category change).+ it('clears is_intermediate without changing the existing image category', () => {+ // A utility result adopted by the canvas must survive GC, while its existing+ // category continues to determine whether it appears in Images or Assets.const body = imageMakeDurableChanges();expect(body).toEqual({ is_intermediate: false });expect('image_category' in body).toBe(false);diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.tsindex 208f109aaf..9db903b084 100644--- a/invokeai/frontend/webv2/src/workbench/gallery/api.ts+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.ts@@ -226,6 +226,12 @@ export const getGalleryImagesByNames = async (imageNames: string[]): Promise<Galreturn body.map(mapImage);};+export const getGalleryImageByName = async (imageName: string, signal?: AbortSignal): Promise<GalleryImage> => {+ const body = await apiFetchJson<BackendImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`, { signal });++ return mapImage(body);+};+/*** Date virtual boards have no offset-paginated DTO endpoint; list the ordered* names for the date, slice the requested window, then bulk-hydrate DTOs.@@ -317,20 +323,19 @@ export const imageSaveToGalleryChanges = (): { is_intermediate: false; image_cat});/**- * The `ImageRecordChanges` body that makes an intermediate image durable WITHOUT- * surfacing it in the gallery: clearing `is_intermediate` stops it being- * garbage-collected, but (unlike {@link imageSaveToGalleryChanges}) it leaves- * `image_category` untouched so it stays out of the gallery's images view. Used- * when applying a control-filter preview: the chosen image becomes the layer's- * new source (durable), while the discarded previews GC away as intermediates.+ * The `ImageRecordChanges` body that makes an intermediate image durable without+ * changing its category. Clearing `is_intermediate` stops garbage collection;+ * where the image appears is determined by its existing category. Used when a+ * utility result becomes a canvas source while discarded previews remain+ * intermediate and can be collected.*/export const imageMakeDurableChanges = (): { is_intermediate: false } => ({is_intermediate: false,});/**- * Makes a single intermediate image durable (survives GC) without adding it to- * the gallery, via `PATCH /api/v1/images/i/{image_name}`. Resolves once the PATCH+ * Makes a single intermediate image durable (survives GC) without changing its+ * category, via `PATCH /api/v1/images/i/{image_name}`. Resolves once the PATCH* succeeds; the caller commits the layer-source swap only after this settles so a* failed PATCH never strands the layer pointing at a soon-to-be-collected image.*/diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 3db4099860..d17692a32d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -192,6 +192,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {isVisible: stagingArea.isVisible,progressImage,selectedImageName: selectedCandidate?.imageName ?? null,+ selectedPlacement: selectedCandidate?.placement ?? null,});const previewKey = stagedPreviewKey(previewSource);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.tsindex f65c3a7636..eb34798ed1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts@@ -20,6 +20,18 @@ describe('selectStagedPreviewSource', () => {expect(selectStagedPreviewSource({ ...base, selectedImageName: 'img-1' })).toEqual({ imageName: 'img-1' });});+ it('carries the selected candidate placement into the image preview', () => {+ const placement = { height: 240, opacity: 0.4, width: 320, x: 11, y: 17 };++ expect(+ selectStagedPreviewSource({+ ...base,+ selectedImageName: 'img-1',+ selectedPlacement: placement,+ })+ ).toEqual({ imageName: 'img-1', placement });+ });+it('returns null for a selected candidate when the preview is hidden', () => {expect(selectStagedPreviewSource({ ...base, isVisible: false, selectedImageName: 'img-1' })).toBeNull();});@@ -80,4 +92,16 @@ describe('stagedPreviewKey', () => {stagedPreviewKey({ dataUrl: 'BB', height: 8, width: 8 }));});++ it('includes every image placement field', () => {+ const placement = { height: 240, opacity: 0.4, width: 320, x: 11, y: 17 };+ const original = stagedPreviewKey({ imageName: 'a', placement });++ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a' }));+ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a', placement: { ...placement, x: 12 } }));+ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a', placement: { ...placement, y: 18 } }));+ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a', placement: { ...placement, width: 321 } }));+ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a', placement: { ...placement, height: 241 } }));+ expect(original).not.toBe(stagedPreviewKey({ imageName: 'a', placement: { ...placement, opacity: 0.5 } }));+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.tsindex 24d8b472fc..e976c4e189 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts@@ -6,6 +6,7 @@*/import type { StagedPreviewInput } from '@workbench/canvas-engine/engine';+import type { CanvasPlacementContract } from '@workbench/types';/** Inputs to {@link selectStagedPreviewSource}. */export interface StagedPreviewSelection {@@ -17,6 +18,8 @@ export interface StagedPreviewSelection {isVisible: boolean;/** The currently selected staged candidate's image name, if any. */selectedImageName: string | null;+ /** The selected candidate's world-space placement, if it has one. */+ selectedPlacement?: CanvasPlacementContract | null;/** The current bbox size (document px) — progress frames scale to fill it. */bboxWidth: number;bboxHeight: number;@@ -34,9 +37,12 @@ export const selectStagedPreviewSource = ({isVisible,progressImage,selectedImageName,+ selectedPlacement,}: StagedPreviewSelection): StagedPreviewInput | null => {if (isVisible && selectedImageName) {- return { imageName: selectedImageName };+ return selectedPlacement+ ? { imageName: selectedImageName, placement: selectedPlacement }+ : { imageName: selectedImageName };}if (isGenerationInFlight && progressImage && bboxWidth > 0 && bboxHeight > 0) {// Progress frames are low-res latents of the bbox region; scale to fill it.@@ -55,7 +61,11 @@ export const stagedPreviewKey = (source: StagedPreviewInput | null): string => {return 'none';}if ('imageName' in source) {- return `image:${source.imageName}`;+ const { placement } = source;++ return placement+ ? `image:${source.imageName}:${placement.x}:${placement.y}:${placement.width}:${placement.height}:${placement.opacity}`+ : `image:${source.imageName}`;}return `data:${source.width}x${source.height}:${source.dataUrl}`;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 0a3eab3d71..bb48ef1ef3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -71,6 +71,7 @@ import {getRegionalGuidanceReferenceImagePatch,} from './layerOps';import { requestLayerProperties } from './layerPropertiesRequestStore';+import { RunLayerWorkflowDialog, useLayerWorkflowAvailability } from './RunLayerWorkflowDialog';import { SelectObjectDialog } from './SelectObjectDialog';type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];@@ -165,8 +166,8 @@ interface LayerMenuProps {* visibility + lock toggles, and delete. Merge-down uses global z-adjacency* (compositing order); the arrange actions map to a splice inside the global array.*- * The rename dialog is a SIBLING of `Menu.Root` (not inside its portal) so it- * survives the menu closing when "Rename" is chosen.+ * Sibling dialogs live beside `Menu.Root` (not inside its portal) so they+ * survive the menu closing after their action is chosen.*/const LayerMenu = ({dispatch,@@ -186,6 +187,7 @@ const LayerMenu = ({const { t } = useTranslation();const notify = useNotify();const base = useSelectedModelBase();+ const workflowAvailability = useLayerWorkflowAvailability();const canvas = useActiveProjectSelector((project) => project.canvas);const queueItems = useActiveProjectSelector((project) => project.queue.items);const { document } = canvas;@@ -257,14 +259,25 @@ const LayerMenu = ({const actionState = useMemo<LayerContextActionState>(() => ({+ canRunWorkflow: workflowAvailability.canRunWorkflow,document,hasEngine: engine !== null,hasSupportedContent,+ hasWorkflowBindings: workflowAvailability.hasWorkflowBindings,index,interactionLocked,layer,}),- [document, engine, hasSupportedContent, index, interactionLocked, layer]+ [+ document,+ engine,+ hasSupportedContent,+ index,+ interactionLocked,+ layer,+ workflowAvailability.canRunWorkflow,+ workflowAvailability.hasWorkflowBindings,+ ]);const actions = useMemo(() => getLayerContextActions(actionState), [actionState]);const menuLayout = useMemo(() => getLayerContextMenuLayout(actions), [actions]);@@ -376,6 +389,7 @@ const LayerMenu = ({const openRename = useCallback(() => setDialogKind('rename'), [setDialogKind]);const closeDialog = useCallback(() => setDialogKind(null), [setDialogKind]);+ const openRunWorkflow = useCallback(() => setDialogKind('run-workflow'), [setDialogKind]);const openSelectObject = useCallback(() => setDialogKind('select-object'), [setDialogKind]);const submitRename = useCallback((name: string) => {@@ -589,6 +603,7 @@ const LayerMenu = ({mergeDown: handleMerge,openProperties: handleOpenProperties,openRename,+ openRunWorkflow,openSelectObject,patchConfig: handleLayerConfigAction,rasterize: handleRasterize,@@ -618,6 +633,7 @@ const LayerMenu = ({handleToggleVisibility,handleTransform,openRename,+ openRunWorkflow,openSelectObject,reorder,]@@ -678,6 +694,15 @@ const LayerMenu = ({{dialogKind === 'select-object' ? (<SelectObjectDialog engine={engine} isOpen layerId={layer.id} onClose={closeDialog} />) : null}+ {dialogKind === 'run-workflow' ? (+ <RunLayerWorkflowDialog+ availability={workflowAvailability}+ engine={engine}+ isOpen+ layerId={layer.id}+ onClose={closeDialog}+ />+ ) : null}</>);};@@ -709,12 +734,11 @@ export interface CanvasLayerContextMenuTarget {* it; `null` closes the menu. The layer and its global index are resolved from* `target.layerId` against the live layer list, so the shared items get the exact* same inputs the panel passes. Keyed by layer id so switching target resets the- * menu's rename state.+ * menu's sibling-dialog state.*- * Choosing "Rename" closes the menu, which nulls `target`. The rename dialog lives- * inside {@link LayerMenu} (a sibling of the menu), so it must survive that: the- * wrapper owns the rename-in-flight flag and keeps rendering against the last-known- * (sticky) target until the dialog closes (F1).+ * Choosing a sibling-dialog action closes the menu, which nulls `target`. The+ * wrapper therefore owns the dialog-in-flight state and keeps rendering against+ * the last-known (sticky) target until the dialog closes (F1).*/export const CanvasLayerContextMenu = ({dispatch,@@ -775,8 +799,8 @@ export const CanvasLayerContextMenu = ({layer={layer}layers={layers}lazyMount- // The menu itself is visible only while the live target is set; once "Rename"- // closes it (target → null), the subtree stays mounted for the dialog.+ // The menu itself is visible only while the live target is set; once a+ // sibling dialog closes it (target → null), the subtree stays mounted.open={!!target}positioning={positioning}unmountOnExitdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.tsnew file mode 100644index 0000000000..8f9115ada3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts@@ -0,0 +1,72 @@+import type { WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';++import { describe, expect, it } from 'vitest';++import { getLayerWorkflowFailureKey, reconcileLayerWorkflowDialogSelection } from './RunLayerWorkflowDialog';++const binding = (nodeId: string, fieldName = 'image', label = `${nodeId} → ${fieldName}`): WorkflowImageBinding => ({+ fieldName,+ label,+ nodeId,+});++describe('reconcileLayerWorkflowDialogSelection', () => {+ it('preserves a still-runnable input and output by field identity when availability refreshes', () => {+ const refreshedInput = binding('input', 'image', 'Refreshed input');+ const refreshedOutput = binding('output', 'image', 'Refreshed output');++ expect(+ reconcileLayerWorkflowDialogSelection(+ {+ destination: 'staging',+ input: binding('input', 'image', 'Old input'),+ output: binding('output', 'image', 'Old output'),+ },+ [refreshedOutput],+ () => [refreshedInput]+ )+ ).toEqual({ destination: 'staging', input: refreshedInput, output: refreshedOutput });+ });++ it('keeps the selected output and clears its input when that output has no runnable inputs', () => {+ const selectedOutput = binding('selected-output');+ const fallbackOutput = binding('fallback-output');+ const fallbackInput = binding('fallback-input');++ expect(+ reconcileLayerWorkflowDialogSelection(+ { destination: 'copy-raster', input: binding('stale-input'), output: selectedOutput },+ [selectedOutput, fallbackOutput],+ (output) => (output.nodeId === fallbackOutput.nodeId ? [fallbackInput] : [])+ )+ ).toEqual({ destination: 'copy-raster', input: null, output: selectedOutput });+ });++ it('falls back to the first runnable pair when the selected output disappeared', () => {+ const fallbackOutput = binding('fallback-output');+ const fallbackInput = binding('fallback-input');++ expect(+ reconcileLayerWorkflowDialogSelection(+ { destination: 'replace', input: binding('stale-input'), output: binding('removed-output') },+ [fallbackOutput],+ () => [fallbackInput]+ )+ ).toEqual({ destination: 'replace', input: fallbackInput, output: fallbackOutput });+ });+});++describe('getLayerWorkflowFailureKey', () => {+ it.each([+ ['graph', 'widgets.layers.runWorkflow.graphFailure'],+ ['hydrate', 'widgets.layers.runWorkflow.hydrationFailure'],+ ['durability', 'widgets.layers.runWorkflow.durabilityFailure'],+ ['export', 'widgets.layers.runWorkflow.failed'],+ ['upload', 'widgets.layers.runWorkflow.failed'],+ ['gallery', 'widgets.layers.runWorkflow.failed'],+ ['staging', 'widgets.layers.runWorkflow.failed'],+ ['commit', 'widgets.layers.runWorkflow.failed'],+ ] as const)('maps %s failures to %s', (stage, key) => {+ expect(getLayerWorkflowFailureKey(stage)).toBe(key);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsxnew file mode 100644index 0000000000..a674cb9a49--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx@@ -0,0 +1,512 @@+import type { SelectValueChangeDetails } from '@chakra-ui/react';+import type { CanvasEngine } from '@workbench/canvas-engine/engine';+import type { ProjectGraphState } from '@workbench/workflows/types';+import type { FormEvent } from 'react';++import { chakra, createListCollection, Dialog, Portal, Stack, Text } from '@chakra-ui/react';+import { socketHub } from '@workbench/backend/socketHub';+import { runUtilityGraph } from '@workbench/canvas-engine/backend/utilityQueue';+import { Button, CloseButton, Field, Select } from '@workbench/components/ui';+import { getGalleryImageByName, makeImageDurable, saveImageToGallery } from '@workbench/gallery/api';+import { useNotify } from '@workbench/useNotify';+import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import {+ buildLayerWorkflowGraph,+ getDefaultLayerWorkflowSelection,+ getLayerWorkflowInputs,+ getLayerWorkflowOutputs,+ getRunnableLayerWorkflowInputs,+ reconcileLayerWorkflowSelection,+ type GetRunnableLayerWorkflowInputs,+ type LayerWorkflowSelection,+ type WorkflowImageBinding,+} from '@workbench/workflows/layerWorkflow';+import { useInvocationTemplatesSnapshot, type InvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { createLayerActionSession } from './layerActionSession';+import {+ runLayerWorkflow,+ type LayerWorkflowDestination,+ type LayerWorkflowFailureStage,+ type RunLayerWorkflowResult,+} from './runLayerWorkflow';++const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;+const EMPTY_BINDINGS: readonly WorkflowImageBinding[] = [];++const bindingKey = (binding: WorkflowImageBinding): string => JSON.stringify([binding.nodeId, binding.fieldName]);+const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));++export interface LayerWorkflowAvailability {+ canRunWorkflow: boolean;+ document: ProjectGraphState;+ getRunnableInputs(output: WorkflowImageBinding): readonly WorkflowImageBinding[];+ hasWorkflowBindings: boolean;+ inputs: readonly WorkflowImageBinding[];+ outputs: readonly WorkflowImageBinding[];+ templatesSnapshot: InvocationTemplatesSnapshot;+}++/**+ * Every layer row observes the same immutable graph/template objects. Cache the+ * expensive injected-graph readiness probes by those identities so a long+ * layer list does the work once, while each row still gets live eligibility.+ */+const availabilityCache = new WeakMap<+ ProjectGraphState,+ WeakMap<InvocationTemplatesSnapshot, LayerWorkflowAvailability>+>();++const getLayerWorkflowAvailability = (+ document: ProjectGraphState,+ templatesSnapshot: InvocationTemplatesSnapshot+): LayerWorkflowAvailability => {+ let byTemplates = availabilityCache.get(document);++ if (!byTemplates) {+ byTemplates = new WeakMap();+ availabilityCache.set(document, byTemplates);+ }++ const cached = byTemplates.get(templatesSnapshot);++ if (cached) {+ return cached;+ }++ const inputs =+ templatesSnapshot.status === 'loaded'+ ? getLayerWorkflowInputs(document, templatesSnapshot.templates)+ : EMPTY_BINDINGS;+ const outputs =+ templatesSnapshot.status === 'loaded'+ ? getLayerWorkflowOutputs(document, templatesSnapshot.templates)+ : EMPTY_BINDINGS;+ const runnableByOutput = new Map<string, readonly WorkflowImageBinding[]>();++ for (const output of outputs) {+ runnableByOutput.set(bindingKey(output), getRunnableLayerWorkflowInputs(document, templatesSnapshot, output));+ }++ const availability: LayerWorkflowAvailability = {+ canRunWorkflow: [...runnableByOutput.values()].some((runnableInputs) => runnableInputs.length > 0),+ document,+ getRunnableInputs: (output) => runnableByOutput.get(bindingKey(output)) ?? EMPTY_BINDINGS,+ hasWorkflowBindings: inputs.length > 0 && outputs.length > 0,+ inputs,+ outputs,+ templatesSnapshot,+ };++ byTemplates.set(templatesSnapshot, availability);+ return availability;+};++export const useLayerWorkflowAvailability = (): LayerWorkflowAvailability => {+ const document = useActiveProjectSelector((project) => project.projectGraph, Object.is);+ const templatesSnapshot = useInvocationTemplatesSnapshot();++ return getLayerWorkflowAvailability(document, templatesSnapshot);+};++interface RunLayerWorkflowDialogProps {+ availability: LayerWorkflowAvailability;+ engine: CanvasEngine | null;+ isOpen: boolean;+ layerId: string;+ onClose(): void;+}++interface SelectionState {+ availability: LayerWorkflowAvailability;+ selection: LayerWorkflowSelection;+}++const createDefaultSelection = (availability: LayerWorkflowAvailability): LayerWorkflowSelection =>+ getDefaultLayerWorkflowSelection(availability.outputs, availability.getRunnableInputs);++export const reconcileLayerWorkflowDialogSelection = (+ current: LayerWorkflowSelection,+ outputs: readonly WorkflowImageBinding[],+ getRunnableInputs: GetRunnableLayerWorkflowInputs+): LayerWorkflowSelection => {+ const selectedOutput = current.output;+ const currentOutput = selectedOutput+ ? outputs.find((output) => bindingKey(output) === bindingKey(selectedOutput))+ : undefined;++ if (currentOutput) {+ return reconcileLayerWorkflowSelection(current, currentOutput, getRunnableInputs(currentOutput));+ }++ return {+ ...getDefaultLayerWorkflowSelection(outputs, getRunnableInputs),+ destination: current.destination,+ };+};++const SUCCESS_KEYS: Record<LayerWorkflowDestination, string> = {+ 'copy-raster': 'widgets.layers.runWorkflow.copySuccess',+ gallery: 'widgets.layers.runWorkflow.gallerySuccess',+ replace: 'widgets.layers.runWorkflow.replaceSuccess',+ staging: 'widgets.layers.runWorkflow.stagingSuccess',+};++const FAILURE_KEYS: Record<Exclude<RunLayerWorkflowResult['status'], 'completed' | 'failed'>, string> = {+ aborted: 'widgets.layers.runWorkflow.aborted',+ busy: 'widgets.layers.runWorkflow.busy',+ disabled: 'widgets.layers.runWorkflow.disabled',+ empty: 'widgets.layers.runWorkflow.empty',+ locked: 'widgets.layers.runWorkflow.locked',+ missing: 'widgets.layers.runWorkflow.missing',+ 'not-ready': 'widgets.layers.runWorkflow.notReady',+ stale: 'widgets.layers.runWorkflow.stale',+ unsupported: 'widgets.layers.runWorkflow.unsupported',+};++export const getLayerWorkflowFailureKey = (stage: LayerWorkflowFailureStage): string => {+ switch (stage) {+ case 'graph':+ return 'widgets.layers.runWorkflow.graphFailure';+ case 'hydrate':+ return 'widgets.layers.runWorkflow.hydrationFailure';+ case 'durability':+ return 'widgets.layers.runWorkflow.durabilityFailure';+ default:+ return 'widgets.layers.runWorkflow.failed';+ }+};++export const RunLayerWorkflowDialog = ({+ availability,+ engine,+ isOpen,+ layerId,+ onClose,+}: RunLayerWorkflowDialogProps) => {+ const { t } = useTranslation();+ const notify = useNotify();+ const dispatch = useWorkbenchDispatch();+ const projectId = useActiveProjectSelector((project) => project.id);+ const [session] = useState(createLayerActionSession);+ const [selectionState, setSelectionState] = useState<SelectionState>(() => ({+ availability,+ selection: createDefaultSelection(availability),+ }));+ const [isRunning, setIsRunning] = useState(false);+ const [error, setError] = useState<string | null>(null);++ let selection = selectionState.selection;++ if (selectionState.availability !== availability) {+ selection = reconcileLayerWorkflowDialogSelection(selection, availability.outputs, availability.getRunnableInputs);+ setSelectionState({ availability, selection });+ }++ const runnableInputs = selection.output ? availability.getRunnableInputs(selection.output) : EMPTY_BINDINGS;+ const inputCollection = useMemo(+ () =>+ createListCollection({+ items: runnableInputs.map((binding) => ({ label: binding.label, value: bindingKey(binding) })),+ }),+ [runnableInputs]+ );+ const outputCollection = useMemo(+ () =>+ createListCollection({+ items: availability.outputs.map((binding) => ({ label: binding.label, value: bindingKey(binding) })),+ }),+ [availability.outputs]+ );+ const destinationCollection = useMemo(+ () =>+ createListCollection<{ label: string; value: LayerWorkflowDestination }>({+ items: [+ { label: t('widgets.layers.runWorkflow.gallery'), value: 'gallery' },+ { label: t('widgets.layers.runWorkflow.staging'), value: 'staging' },+ { label: t('widgets.layers.runWorkflow.replace'), value: 'replace' },+ { label: t('widgets.layers.runWorkflow.copyRaster'), value: 'copy-raster' },+ ],+ }),+ [t]+ );+ const inputValue = useMemo(() => (selection.input ? [bindingKey(selection.input)] : []), [selection.input]);+ const outputValue = useMemo(() => (selection.output ? [bindingKey(selection.output)] : []), [selection.output]);+ const destinationValue = useMemo(() => [selection.destination], [selection.destination]);++ const close = useCallback(() => {+ session.cancel();+ onClose();+ }, [onClose, session]);++ const contentRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (!node) {+ return;+ }+ return () => {+ session.cancel();+ };+ },+ [session]+ );++ const handleOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (!open) {+ close();+ }+ },+ [close]+ );++ const handleInputChange = useCallback(+ ({ value }: SelectValueChangeDetails) => {+ const input = runnableInputs.find((binding) => bindingKey(binding) === value[0]);++ if (!input) {+ return;+ }++ setSelectionState((current) => ({+ availability,+ selection: { ...current.selection, input },+ }));+ setError(null);+ },+ [availability, runnableInputs]+ );++ const handleOutputChange = useCallback(+ ({ value }: SelectValueChangeDetails) => {+ const output = availability.outputs.find((binding) => bindingKey(binding) === value[0]);++ if (!output) {+ return;+ }++ setSelectionState((current) => ({+ availability,+ selection: reconcileLayerWorkflowSelection(current.selection, output, availability.getRunnableInputs(output)),+ }));+ setError(null);+ },+ [availability]+ );++ const handleDestinationChange = useCallback(+ ({ value }: SelectValueChangeDetails) => {+ const destination = value[0] as LayerWorkflowDestination | undefined;++ if (!destination || !destinationCollection.items.some((item) => item.value === destination)) {+ return;+ }++ setSelectionState((current) => ({+ availability,+ selection: { ...current.selection, destination },+ }));+ setError(null);+ },+ [availability, destinationCollection.items]+ );++ const runContext = useMemo(+ () => ({+ availability,+ close,+ dispatch,+ engine,+ layerId,+ notify,+ projectId,+ selection,+ session,+ t,+ }),+ [availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t]+ );++ const run = useCallback(async (): Promise<void> => {+ const { availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t } = runContext;+ const { input, output } = selection;++ if (!engine || !input || !output) {+ return;+ }++ const request = session.begin();++ if (!request) {+ return;+ }++ const destination = selection.destination;+ setError(null);+ setIsRunning(true);++ try {+ const executorDeps = engine.getCompositeExecutorDeps();+ const result = await runLayerWorkflow({+ deps: {+ appendStaging: (targetProjectId, candidate) =>+ dispatch({ candidate, projectId: targetProjectId, type: 'appendCanvasStagingCandidate' }),+ buildGraph: buildLayerWorkflowGraph,+ commitGenerated: (options) => engine.commitGeneratedImageResult(options),+ createRequestId: () => crypto.randomUUID(),+ exportLayer: (targetLayerId) => engine.exportBakedLayerBlob(targetLayerId, { includeDisabled: true }),+ getImage: getGalleryImageByName,+ isGuardCurrent: (guard) => engine.isLayerExportGuardCurrent(guard),+ makeDurable: makeImageDurable,+ runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),+ saveToGallery: saveImageToGallery,+ touchGallery: (targetProjectId) =>+ dispatch({ projectId: targetProjectId, type: 'touchGalleryImagesRefresh' }),+ uploadIntermediate: async (blob, signal) => {+ if (signal?.aborted) {+ throw new DOMException('Layer workflow aborted', 'AbortError');+ }+ const uploaded = await executorDeps.uploadImage(blob);+ if (signal?.aborted) {+ throw new DOMException('Layer workflow aborted', 'AbortError');+ }+ return { imageName: uploaded.imageName };+ },+ },+ destination,+ document: availability.document,+ input,+ layerId,+ output,+ projectId,+ signal: request.signal,+ templatesSnapshot: availability.templatesSnapshot,+ });++ if (!session.isCurrent(request.token)) {+ return;+ }++ if (result.status === 'completed') {+ notify.success(t(SUCCESS_KEYS[destination]));+ close();+ return;+ }++ if (result.status === 'failed') {+ setError(t(getLayerWorkflowFailureKey(result.stage), { message: result.message }));+ return;+ }++ setError(t(FAILURE_KEYS[result.status]));+ } catch (error) {+ if (session.isCurrent(request.token)) {+ setError(t('widgets.layers.runWorkflow.failed', { message: messageOf(error) }));+ }+ } finally {+ if (session.isCurrent(request.token)) {+ setIsRunning(false);+ }+ session.finish(request.token);+ }+ }, [runContext]);++ const handleSubmit = useCallback(+ (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ void run();+ },+ [run]+ );++ const readinessMessage = !availability.hasWorkflowBindings+ ? t('widgets.layers.runWorkflow.noBindings')+ : !selection.input || !selection.output+ ? t('widgets.layers.runWorkflow.notReady')+ : null;+ const canRun = engine !== null && !isRunning && readinessMessage === null;++ return (+ <Dialog.Root lazyMount open={isOpen} placement="center" size="sm" unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content ref={contentRef} bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">+ <chakra.form onSubmit={handleSubmit}>+ <Dialog.Header>+ <Dialog.Title fontSize="sm" fontWeight="700">+ {t('widgets.layers.runWorkflow.title')}+ </Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="4">+ <Field id="layer-workflow-output" label={t('widgets.layers.runWorkflow.output')}>+ <Select+ aria-label={t('widgets.layers.runWorkflow.output')}+ collection={outputCollection}+ disabled={isRunning || availability.outputs.length === 0}+ positioning={SELECT_POSITIONING}+ size="sm"+ value={outputValue}+ onValueChange={handleOutputChange}+ />+ </Field>+ <Field id="layer-workflow-input" label={t('widgets.layers.runWorkflow.input')}>+ <Select+ aria-label={t('widgets.layers.runWorkflow.input')}+ collection={inputCollection}+ disabled={isRunning || runnableInputs.length === 0}+ positioning={SELECT_POSITIONING}+ size="sm"+ value={inputValue}+ onValueChange={handleInputChange}+ />+ </Field>+ <Field id="layer-workflow-destination" label={t('widgets.layers.runWorkflow.destination')}>+ <Select+ aria-label={t('widgets.layers.runWorkflow.destination')}+ collection={destinationCollection}+ disabled={isRunning}+ positioning={SELECT_POSITIONING}+ size="sm"+ value={destinationValue}+ onValueChange={handleDestinationChange}+ />+ </Field>+ {readinessMessage ? (+ <Text color="fg.error" fontSize="xs" role="alert">+ {readinessMessage}+ </Text>+ ) : null}+ {error ? (+ <Text color="fg.error" fontSize="xs" role="alert">+ {error}+ </Text>+ ) : null}+ {isRunning ? (+ <Text color="fg.muted" fontSize="xs" role="status">+ {t('widgets.layers.runWorkflow.running')}+ </Text>+ ) : null}+ </Stack>+ </Dialog.Body>+ <Dialog.Footer gap="2">+ <Button size="xs" type="button" variant="ghost" onClick={close}>+ {t('widgets.layers.runWorkflow.cancel')}+ </Button>+ <Button disabled={!canRun} loading={isRunning} size="xs" type="submit" variant="solid">+ {t('widgets.layers.runWorkflow.run')}+ </Button>+ </Dialog.Footer>+ </chakra.form>+ <Dialog.CloseTrigger asChild>+ <CloseButton aria-label={t('widgets.layers.runWorkflow.cancel')} color="fg.muted" size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 67270c3969..8f51f66cec 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -66,9 +66,11 @@ const makeState = (): LayerContextActionState => {const document = overrides.document ?? makeDocument([layer]);return {+ canRunWorkflow: true,document,hasEngine: true,hasSupportedContent: true,+ hasWorkflowBindings: true,index: document.layers.findIndex((entry) => entry.id === layer.id),interactionLocked: false,layer,@@ -88,6 +90,7 @@ const makeEffects = (): LayerContextActionEffects => ({mergeDown: vi.fn(),openProperties: vi.fn(),openRename: vi.fn(),+ openRunWorkflow: vi.fn(),openSelectObject: vi.fn(),patchConfig: vi.fn(),rasterize: vi.fn(),@@ -210,6 +213,35 @@ describe('layer context action registry', () => {'widgets.layers.selectObject.targetSelection','widgets.layers.selectObject.title','widgets.layers.selectObject.unsupported',+ 'widgets.layers.runWorkflow.aborted',+ 'widgets.layers.runWorkflow.busy',+ 'widgets.layers.runWorkflow.cancel',+ 'widgets.layers.runWorkflow.copyRaster',+ 'widgets.layers.runWorkflow.copySuccess',+ 'widgets.layers.runWorkflow.destination',+ 'widgets.layers.runWorkflow.durabilityFailure',+ 'widgets.layers.runWorkflow.disabled',+ 'widgets.layers.runWorkflow.empty',+ 'widgets.layers.runWorkflow.failed',+ 'widgets.layers.runWorkflow.gallery',+ 'widgets.layers.runWorkflow.gallerySuccess',+ 'widgets.layers.runWorkflow.graphFailure',+ 'widgets.layers.runWorkflow.hydrationFailure',+ 'widgets.layers.runWorkflow.input',+ 'widgets.layers.runWorkflow.locked',+ 'widgets.layers.runWorkflow.missing',+ 'widgets.layers.runWorkflow.noBindings',+ 'widgets.layers.runWorkflow.notReady',+ 'widgets.layers.runWorkflow.output',+ 'widgets.layers.runWorkflow.replace',+ 'widgets.layers.runWorkflow.replaceSuccess',+ 'widgets.layers.runWorkflow.run',+ 'widgets.layers.runWorkflow.running',+ 'widgets.layers.runWorkflow.staging',+ 'widgets.layers.runWorkflow.stagingSuccess',+ 'widgets.layers.runWorkflow.stale',+ 'widgets.layers.runWorkflow.title',+ 'widgets.layers.runWorkflow.unsupported',];for (const key of keys) {@@ -240,6 +272,16 @@ describe('layer context action registry', () => {expect(Object.values(effects).filter((effect) => effect.mock.calls.length > 0)).toEqual([effects.openSelectObject]);});+ it('opens Run Workflow through the registry without starting work itself', () => {+ const effects = makeEffects();+ const context = makeRuntimeContext(rasterLayer, { effects });++ getLayerContextActionDefinition('run-workflow').handler(context);++ expect(effects.openRunWorkflow).toHaveBeenCalledOnce();+ expect(Object.values(effects).filter((effect) => effect.mock.calls.length > 0)).toEqual([effects.openRunWorkflow]);+ });+it('dispatches parameterized registry handlers through injected effects', () => {const effects = makeEffects();const context = makeRuntimeContext(rasterLayer, { effects });@@ -301,6 +343,34 @@ describe('getLayerContextActions', () => {).toBe(false);});+ it.each([+ ['raster', true],+ ['control', true],+ ['inpaint_mask', false],+ ['regional_guidance', false],+ ] as const)('exposes Run Workflow only for exportable %s content with compatible bindings', (type, expected) => {+ const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'run-workflow');+ expect(Boolean(action)).toBe(expected);+ });++ it('hides Run Workflow when the active workflow has no compatible image bindings', () => {+ expect(+ getLayerContextActions(makeState(rasterLayer, { hasWorkflowBindings: false })).some(+ (action) => action.id === 'run-workflow'+ )+ ).toBe(false);+ });++ it.each([+ ['no runnable binding', { canRunWorkflow: false }],+ ['missing engine', { hasEngine: false }],+ ['locked layer', { layer: { ...rasterLayer, isLocked: true } }],+ ['locked interaction', { interactionLocked: true }],+ ] as const)('disables Run Workflow for %s', (_label, overrides) => {+ const layer = 'layer' in overrides ? overrides.layer : rasterLayer;+ expect(byId(getLayerContextActions(makeState(layer, overrides)), 'run-workflow').isDisabled).toBe(true);+ });+it.each([['missing engine', { hasEngine: false }],['locked layer', { layer: { ...rasterLayer, isLocked: true } }],@@ -369,6 +439,7 @@ describe('getLayerContextActions', () => {'extract-masked-area','filter','select-object',+ 'run-workflow','intersect','cutout','cutaway',@@ -416,6 +487,7 @@ describe('getLayerContextActions', () => {'adjustments','filter','select-object',+ 'run-workflow','crop-to-bbox','convert-to-control','intersect',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 8995b6f402..bea9ff11c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -21,6 +21,7 @@ import {ScanSearchIcon,SlidersHorizontalIcon,Trash2Icon,+ WorkflowIcon,} from 'lucide-react';import type { LayerMoveKind } from './layerGroups';@@ -45,6 +46,7 @@ export type LayerContextActionId =| 'extract-masked-area'| 'filter'| 'select-object'+ | 'run-workflow'| 'intersect'| 'cutout'| 'cutaway'@@ -75,9 +77,11 @@ export type LayerContextMenuSectionId = 'quick' | 'primary' | 'operations' | 'ouexport type LayerContextSubmenuId = 'arrange' | 'add-modifiers' | 'add-regional' | 'boolean' | 'copy-to' | 'convert-to';export interface LayerContextActionState {+ canRunWorkflow: boolean;document: CanvasDocumentContractV2;hasEngine: boolean;hasSupportedContent: boolean;+ hasWorkflowBindings: boolean;index: number;interactionLocked: boolean;layer: CanvasLayerContract;@@ -87,6 +91,7 @@ export interface LayerContextActionEffects {reorder(kind: LayerMoveKind, actionId: LayerContextActionId): void;duplicate(): void;openRename(): void;+ openRunWorkflow(): void;openSelectObject(): void;transform(): void;fitToBbox(): void;@@ -429,6 +434,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinisection: 'primary',supportedLayerTypes: RASTER_AND_CONTROL,},+ {+ defaultLabel: 'Run workflow',+ handler: ({ effects }) => effects.openRunWorkflow(),+ icon: WorkflowIcon,+ id: 'run-workflow',+ isEnabled: (context) => context.canRunWorkflow && hasMutablePixels(context),+ isVisible: (context) => context.hasWorkflowBindings && context.hasSupportedContent,+ labelKey: 'widgets.layers.actions.runWorkflow',+ order: 42,+ section: 'primary',+ supportedLayerTypes: RASTER_AND_CONTROL,+ },{defaultLabel: 'Toggle transparency effect',getDefaultLabel: (context) =>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 2ad190f45d..807dc531c8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -29,9 +29,11 @@ const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 =const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>getLayerContextActions({+ canRunWorkflow: true,document: makeDocument([...layers]),hasEngine: true,hasSupportedContent: true,+ hasWorkflowBindings: true,index: layers.indexOf(layer),interactionLocked: false,layer,@@ -65,7 +67,7 @@ describe('getLayerContextMenuLayout', () => {},{id: 'primary',- items: ['transform', 'rename', 'fit-to-bbox', 'adjustments', 'filter', 'select-object'],+ items: ['transform', 'rename', 'fit-to-bbox', 'adjustments', 'filter', 'select-object', 'run-workflow'],presentation: 'list',},{@@ -113,7 +115,15 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(control)[1]).toEqual({id: 'primary',- items: ['transform', 'rename', 'fit-to-bbox', 'filter', 'select-object', 'control-transparency-effect'],+ items: [+ 'transform',+ 'rename',+ 'fit-to-bbox',+ 'filter',+ 'select-object',+ 'run-workflow',+ 'control-transparency-effect',+ ],presentation: 'list',});expect(summarize(control)[2]).toEqual({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.tsnew file mode 100644index 0000000000..97342e4b10--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts@@ -0,0 +1,365 @@+import type { CommitGeneratedImageResult, LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { GalleryImage } from '@workbench/gallery/api';+import type { WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';+import type { InvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import type { ProjectGraphState } from '@workbench/workflows/types';++import { describe, expect, it, vi } from 'vitest';++import {+ runLayerWorkflow,+ type LayerWorkflowDestination,+ type RunLayerWorkflowDeps,+ type RunLayerWorkflowOptions,+} from './runLayerWorkflow';++const guard = {+ cacheVersion: 1,+ documentGeneration: 2,+ layer: { id: 'layer-1' },+ layerId: 'layer-1',+ projectId: 'project-1',+} as LayerExportGuard;+const document = { id: 'workflow-1' } as ProjectGraphState;+const templatesSnapshot = { error: null, status: 'loaded', templates: {} } as InvocationTemplatesSnapshot;+const input: WorkflowImageBinding = { fieldName: 'image', label: 'Input · Image', nodeId: 'input-node' };+const output: WorkflowImageBinding = { fieldName: 'image', label: 'Output · Image', nodeId: 'output-node' };+const sourceBlob = new Blob(['source'], { type: 'image/png' });+const image: GalleryImage = {+ boardId: 'none',+ height: 160,+ imageCategory: 'other',+ imageName: 'workflow-output.png',+ imageUrl: '/full/workflow-output.png',+ queuedAt: '2026-07-09T12:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ starred: false,+ thumbnailUrl: '/thumb/workflow-output.png',+ width: 240,+};++const createDeps = () => {+ const order: string[] = [];+ const deps: RunLayerWorkflowDeps = {+ appendStaging: vi.fn(() => order.push('append-staging')),+ buildGraph: vi.fn(() => {+ order.push('build-graph');+ return { graph: { edges: [], id: 'layer-workflow', nodes: {} }, outputNodeId: 'capture' };+ }),+ commitGenerated: vi.fn(() => {+ order.push('commit-generated');+ return Promise.resolve<CommitGeneratedImageResult>({ layerId: 'result-layer', status: 'committed' });+ }),+ createRequestId: vi.fn(() => 'request-7'),+ exportLayer: vi.fn<RunLayerWorkflowDeps['exportLayer']>(() => {+ order.push('export');+ return Promise.resolve({ blob: sourceBlob, guard, rect: { height: 60, width: 80, x: 11, y: 22 }, status: 'ok' });+ }),+ getImage: vi.fn(() => {+ order.push('get-image');+ return Promise.resolve(image);+ }),+ isGuardCurrent: vi.fn(() => true),+ makeDurable: vi.fn(() => {+ order.push('make-durable');+ return Promise.resolve();+ }),+ runGraph: vi.fn<RunLayerWorkflowDeps['runGraph']>(() => {+ order.push('run-graph');+ return Promise.resolve({ imageName: image.imageName, origin: 'webv2:util:test' });+ }),+ saveToGallery: vi.fn<RunLayerWorkflowDeps['saveToGallery']>(() => {+ order.push('save-gallery');+ return Promise.resolve({ ...image, imageCategory: 'general' as const });+ }),+ touchGallery: vi.fn(() => order.push('touch-gallery')),+ uploadIntermediate: vi.fn(() => {+ order.push('upload');+ return Promise.resolve({ imageName: 'layer-input.png' });+ }),+ };+ return { deps, order };+};++const createOptions = (+ destination: LayerWorkflowDestination,+ deps: RunLayerWorkflowDeps,+ signal?: AbortSignal+): RunLayerWorkflowOptions => ({+ deps,+ destination,+ document,+ input,+ layerId: 'layer-1',+ output,+ projectId: 'project-1',+ signal,+ templatesSnapshot,+});++describe('runLayerWorkflow', () => {+ it('runs the captured output to Gallery and refreshes the captured project', async () => {+ const { deps, order } = createDeps();++ await expect(runLayerWorkflow(createOptions('gallery', deps))).resolves.toEqual({+ imageName: image.imageName,+ status: 'completed',+ });++ expect(order).toEqual([+ 'export',+ 'upload',+ 'build-graph',+ 'run-graph',+ 'get-image',+ 'save-gallery',+ 'touch-gallery',+ ]);+ expect(deps.buildGraph).toHaveBeenCalledWith({+ document,+ imageName: 'layer-input.png',+ input,+ output,+ templatesSnapshot,+ });+ expect(deps.touchGallery).toHaveBeenCalledWith('project-1');+ expect(deps.makeDurable).not.toHaveBeenCalled();+ });++ it('appends a durable orphan staging candidate at the source origin and native result dimensions', async () => {+ const { deps, order } = createDeps();++ await expect(runLayerWorkflow(createOptions('staging', deps))).resolves.toEqual({+ imageName: image.imageName,+ status: 'completed',+ });++ expect(order).toEqual([+ 'export',+ 'upload',+ 'build-graph',+ 'run-graph',+ 'get-image',+ 'make-durable',+ 'append-staging',+ ]);+ expect(deps.appendStaging).toHaveBeenCalledWith('project-1', {+ ...image,+ placement: { height: 160, opacity: 1, width: 240, x: 11, y: 22 },+ sourceQueueItemId: 'layer-workflow:request-7',+ });+ });++ it.each([+ ['replace', 'replace'],+ ['copy-raster', 'copy-raster'],+ ] as const)('promotes then commits the %s destination', async (destination, target) => {+ const { deps, order } = createDeps();++ await expect(runLayerWorkflow(createOptions(destination, deps))).resolves.toEqual({+ imageName: image.imageName,+ status: 'completed',+ });++ expect(order).toEqual([+ 'export',+ 'upload',+ 'build-graph',+ 'run-graph',+ 'get-image',+ 'make-durable',+ 'commit-generated',+ ]);+ expect(deps.commitGenerated).toHaveBeenCalledWith({+ guard,+ image: { height: image.height, imageName: image.imageName, width: image.width },+ origin: { x: 11, y: 22 },+ signal: undefined,+ target,+ });+ });++ it.each(['missing', 'disabled', 'unsupported', 'empty', 'not-ready'] as const)(+ 'maps an export %s result without starting the workflow',+ async (status) => {+ const { deps } = createDeps();+ vi.mocked(deps.exportLayer).mockResolvedValue({ status });++ await expect(runLayerWorkflow(createOptions('gallery', deps))).resolves.toEqual({ status });++ expect(deps.uploadIntermediate).not.toHaveBeenCalled();+ }+ );++ it('stops with stale after hydration when the source guard changed', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.isGuardCurrent).mockReturnValueOnce(true).mockReturnValueOnce(true).mockReturnValueOnce(false);++ await expect(runLayerWorkflow(createOptions('staging', deps))).resolves.toEqual({ status: 'stale' });++ expect(deps.makeDurable).not.toHaveBeenCalled();+ expect(deps.appendStaging).not.toHaveBeenCalled();+ });++ it('does not append staging when the guard changes during durability', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.isGuardCurrent).mockImplementation(() => vi.mocked(deps.makeDurable).mock.calls.length === 0);++ await expect(runLayerWorkflow(createOptions('staging', deps))).resolves.toEqual({ status: 'stale' });++ expect(deps.makeDurable).toHaveBeenCalledOnce();+ expect(deps.appendStaging).not.toHaveBeenCalled();+ });++ it('checks cancellation at every async boundary and forwards the signal', async () => {+ const controller = new AbortController();+ const { deps } = createDeps();+ vi.mocked(deps.getImage).mockImplementation((_imageName, signal) => {+ expect(signal).toBe(controller.signal);+ controller.abort();+ return Promise.resolve(image);+ });++ await expect(runLayerWorkflow(createOptions('staging', deps, controller.signal))).resolves.toEqual({+ status: 'aborted',+ });++ expect(deps.uploadIntermediate).toHaveBeenCalledWith(sourceBlob, controller.signal);+ expect(deps.runGraph).toHaveBeenCalledWith(+ expect.objectContaining({ outputNodeId: 'capture', signal: controller.signal })+ );+ expect(deps.makeDurable).not.toHaveBeenCalled();+ });++ it.each(['export', 'upload', 'run', 'hydrate', 'durability'] as const)(+ 'stops routing when canceled during %s',+ async (boundary) => {+ const controller = new AbortController();+ const { deps } = createDeps();++ if (boundary === 'export') {+ vi.mocked(deps.exportLayer).mockImplementation(() => {+ controller.abort();+ return Promise.resolve({+ blob: sourceBlob,+ guard,+ rect: { height: 60, width: 80, x: 11, y: 22 },+ status: 'ok',+ });+ });+ } else if (boundary === 'upload') {+ vi.mocked(deps.uploadIntermediate).mockImplementation(() => {+ controller.abort();+ return Promise.resolve({ imageName: 'layer-input.png' });+ });+ } else if (boundary === 'run') {+ vi.mocked(deps.runGraph).mockImplementation(() => {+ controller.abort();+ return Promise.resolve({ imageName: image.imageName, origin: 'webv2:util:test' });+ });+ } else if (boundary === 'hydrate') {+ vi.mocked(deps.getImage).mockImplementation(() => {+ controller.abort();+ return Promise.resolve(image);+ });+ } else {+ vi.mocked(deps.makeDurable).mockImplementation(() => {+ controller.abort();+ return Promise.resolve();+ });+ }++ await expect(runLayerWorkflow(createOptions('staging', deps, controller.signal))).resolves.toEqual({+ status: 'aborted',+ });+ expect(deps.appendStaging).not.toHaveBeenCalled();+ expect(deps.commitGenerated).not.toHaveBeenCalled();+ }+ );++ it('does not route when durability promotion fails', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.makeDurable).mockRejectedValue(new Error('promotion failed'));++ await expect(runLayerWorkflow(createOptions('staging', deps))).resolves.toEqual({+ message: 'promotion failed',+ stage: 'durability',+ status: 'failed',+ });+ expect(deps.appendStaging).not.toHaveBeenCalled();+ });++ it('does not refresh Gallery when saving the output fails', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.saveToGallery).mockRejectedValue(new Error('save failed'));++ await expect(runLayerWorkflow(createOptions('gallery', deps))).resolves.toEqual({+ message: 'save failed',+ stage: 'gallery',+ status: 'failed',+ });+ expect(deps.touchGallery).not.toHaveBeenCalled();+ });++ it('preserves an authoritative successful engine commit after a late abort', async () => {+ const controller = new AbortController();+ const { deps } = createDeps();+ vi.mocked(deps.commitGenerated).mockImplementation(() => {+ controller.abort();+ return Promise.resolve({ layerId: 'result-layer', status: 'committed' });+ });++ await expect(runLayerWorkflow(createOptions('replace', deps, controller.signal))).resolves.toEqual({+ imageName: image.imageName,+ status: 'completed',+ });+ });++ it.each(['missing', 'locked', 'stale', 'unsupported', 'busy', 'aborted'] as const)(+ 'maps a generated-image commit %s result',+ async (status) => {+ const { deps } = createDeps();+ vi.mocked(deps.commitGenerated).mockResolvedValue({ status });++ await expect(runLayerWorkflow(createOptions('replace', deps))).resolves.toEqual({ status });+ }+ );++ it('maps generated-image commit failures and unexpected API failures', async () => {+ const commit = createDeps();+ vi.mocked(commit.deps.commitGenerated).mockResolvedValue({ message: 'draw failed', status: 'failed' });+ await expect(runLayerWorkflow(createOptions('replace', commit.deps))).resolves.toEqual({+ message: 'draw failed',+ stage: 'commit',+ status: 'failed',+ });++ const hydrate = createDeps();+ vi.mocked(hydrate.deps.getImage).mockRejectedValue(new Error('metadata failed'));+ await expect(runLayerWorkflow(createOptions('gallery', hydrate.deps))).resolves.toEqual({+ message: 'metadata failed',+ stage: 'hydrate',+ status: 'failed',+ });+ });++ it('identifies graph-build failures for specific UI feedback', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.buildGraph).mockImplementation(() => {+ throw new Error('workflow is not ready');+ });++ await expect(runLayerWorkflow(createOptions('gallery', deps))).resolves.toEqual({+ message: 'workflow is not ready',+ stage: 'graph',+ status: 'failed',+ });+ });++ it('maps AbortError failures to aborted', async () => {+ const { deps } = createDeps();+ vi.mocked(deps.runGraph).mockRejectedValue(new DOMException('canceled', 'AbortError'));++ await expect(runLayerWorkflow(createOptions('gallery', deps))).resolves.toEqual({ status: 'aborted' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.tsnew file mode 100644index 0000000000..fbab125a59--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts@@ -0,0 +1,204 @@+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-engine/backend/utilityQueue';+import type {+ CommitGeneratedImageOptions,+ CommitGeneratedImageResult,+ ExportBakedLayerBlobResult,+ LayerExportGuard,+} from '@workbench/canvas-engine/engine';+import type { GalleryImage } from '@workbench/gallery/api';+import type { CanvasStagingCandidateContract } from '@workbench/types';+import type {+ BuildLayerWorkflowGraphOptions,+ BuiltLayerWorkflowGraph,+ LayerWorkflowDestination,+ WorkflowImageBinding,+} from '@workbench/workflows/layerWorkflow';+import type { InvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import type { ProjectGraphState } from '@workbench/workflows/types';++export type { LayerWorkflowDestination } from '@workbench/workflows/layerWorkflow';++export type LayerWorkflowFailureStage =+ | 'export'+ | 'upload'+ | 'graph'+ | 'hydrate'+ | 'durability'+ | 'gallery'+ | 'staging'+ | 'commit';++export type RunLayerWorkflowResult =+ | { status: 'completed'; imageName: string }+ | {+ status: 'aborted' | 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'locked' | 'stale' | 'busy';+ }+ | { status: 'failed'; message: string; stage: LayerWorkflowFailureStage };++export interface RunLayerWorkflowDeps {+ exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;+ buildGraph(options: BuildLayerWorkflowGraphOptions): BuiltLayerWorkflowGraph;+ runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;+ getImage(imageName: string, signal?: AbortSignal): Promise<GalleryImage>;+ makeDurable(imageName: string): Promise<void>;+ saveToGallery(imageName: string): Promise<GalleryImage>;+ touchGallery(projectId: string): void;+ appendStaging(projectId: string, candidate: CanvasStagingCandidateContract): void;+ commitGenerated(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;+ isGuardCurrent(guard: LayerExportGuard): boolean;+ createRequestId(): string;+}++export interface RunLayerWorkflowOptions {+ layerId: string;+ projectId: string;+ document: ProjectGraphState;+ templatesSnapshot: InvocationTemplatesSnapshot;+ input: WorkflowImageBinding;+ output: WorkflowImageBinding;+ destination: LayerWorkflowDestination;+ signal?: AbortSignal;+ deps: RunLayerWorkflowDeps;+}++const isAbortError = (error: unknown): boolean =>+ typeof error === 'object' && error !== null && 'name' in error && error.name === 'AbortError';++const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));++const stopped = (+ signal: AbortSignal | undefined,+ guard: LayerExportGuard,+ isGuardCurrent: (guard: LayerExportGuard) => boolean+): { status: 'aborted' | 'stale' } | null => {+ if (signal?.aborted) {+ return { status: 'aborted' };+ }+ if (!isGuardCurrent(guard)) {+ return { status: 'stale' };+ }+ return null;+};++export const runLayerWorkflow = async (options: RunLayerWorkflowOptions): Promise<RunLayerWorkflowResult> => {+ const { deps, signal } = options;+ let failureStage: LayerWorkflowFailureStage = 'export';+ if (signal?.aborted) {+ return { status: 'aborted' };+ }++ try {+ const exported = await deps.exportLayer(options.layerId);+ if (signal?.aborted) {+ return { status: 'aborted' };+ }+ if (exported.status !== 'ok') {+ return exported;+ }++ let canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ failureStage = 'upload';+ const uploaded = await deps.uploadIntermediate(exported.blob, signal);+ canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ failureStage = 'graph';+ const built = deps.buildGraph({+ document: options.document,+ imageName: uploaded.imageName,+ input: options.input,+ output: options.output,+ templatesSnapshot: options.templatesSnapshot,+ });+ canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ const output = await deps.runGraph({ graph: built.graph, outputNodeId: built.outputNodeId, signal });+ canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ failureStage = 'hydrate';+ const image = await deps.getImage(output.imageName, signal);+ canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ if (options.destination === 'gallery') {+ // Saving is itself the authoritative external mutation. Once it succeeds,+ // refresh the captured project and report success even if the dialog closes+ // in the same tick.+ failureStage = 'gallery';+ await deps.saveToGallery(image.imageName);+ try {+ deps.touchGallery(options.projectId);+ } catch {+ // Refresh is ancillary once the backend has authoritatively saved the image.+ }+ return { imageName: image.imageName, status: 'completed' };+ }++ failureStage = 'durability';+ // Promotion must precede any canvas reference. If cancellation/staleness+ // wins after this non-abortable PATCH, leave the output durable but+ // unreferenced: arbitrary workflow outputs may echo/cache an existing image,+ // and the image API has no ownership token or compare-and-swap with which to+ // safely delete or mark it intermediate again.+ await deps.makeDurable(image.imageName);+ canceled = stopped(signal, exported.guard, deps.isGuardCurrent);+ if (canceled) {+ return canceled;+ }++ if (options.destination === 'staging') {+ failureStage = 'staging';+ deps.appendStaging(options.projectId, {+ ...image,+ placement: {+ height: image.height,+ opacity: 1,+ width: image.width,+ x: exported.rect.x,+ y: exported.rect.y,+ },+ sourceQueueItemId: `layer-workflow:${deps.createRequestId()}`,+ });+ return { imageName: image.imageName, status: 'completed' };+ }++ failureStage = 'commit';+ const committed = await deps.commitGenerated({+ guard: exported.guard,+ image: { height: image.height, imageName: image.imageName, width: image.width },+ origin: { x: exported.rect.x, y: exported.rect.y },+ signal,+ target: options.destination,+ });+ // The engine performs the last abort/guard check immediately before its+ // structural mutation. Preserve that authoritative result instead of+ // relabeling a successful commit after a late dialog close.+ if (committed.status === 'committed') {+ return { imageName: image.imageName, status: 'completed' };+ }+ if (committed.status === 'failed') {+ return { ...committed, stage: 'commit' };+ }+ return committed;+ } catch (error) {+ if (signal?.aborted || isAbortError(error)) {+ return { status: 'aborted' };+ }+ return { message: messageOf(error), stage: failureStage, status: 'failed' };+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 1a54dceab7..b7950a738b 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -6,6 +6,7 @@ import type {CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,+ CanvasStagingCandidateContract,GeneratedImageContract,GraphContract,Project,@@ -74,6 +75,15 @@ const createImage = (imageName: string, sourceQueueItemId: string): GeneratedImawidth: 512,});+const createStagingCandidate = (+ imageName: string,+ sourceQueueItemId: string,+ placement: CanvasStagingCandidateContract['placement']+): CanvasStagingCandidateContract => ({+ ...createImage(imageName, sourceQueueItemId),+ placement,+});+const getProject = (state: WorkbenchState, projectId: string): Project => {const project = state.projects.find((candidate) => candidate.id === projectId);@@ -481,6 +491,72 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(activeProject.queue.items).toEqual([]);});+ it('appends a workflow candidate to its explicit project and selects its resolved staging slot', () => {+ let state = createInitialWorkbenchState();+ const originProjectId = state.activeProjectId;+ const firstCandidate = createStagingCandidate('first.png', 'layer-workflow:first', {+ height: 100,+ opacity: 1,+ width: 200,+ x: 5,+ y: 7,+ });+ const appendedCandidate = createStagingCandidate('second.png', 'layer-workflow:second', {+ height: 240,+ opacity: 0.45,+ width: 320,+ x: 11,+ y: 17,+ });++ state = workbenchReducer(state, { type: 'createProject' });+ const activeProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ candidate: firstCandidate,+ projectId: originProjectId,+ type: 'appendCanvasStagingCandidate',+ });+ state = workbenchReducer(state, {+ candidate: appendedCandidate,+ projectId: originProjectId,+ type: 'appendCanvasStagingCandidate',+ });++ const originProject = getProject(state, originProjectId);+ const slots = getCanvasStagingSlots(originProject.canvas, originProject.queue.items);++ expect(state.activeProjectId).toBe(activeProjectId);+ expect(originProject.canvas.stagingArea.pendingImages).toEqual([firstCandidate, appendedCandidate]);+ expect(originProject.canvas.stagingArea.pendingImageIds).toEqual(['first.png', 'second.png']);+ expect(originProject.canvas.stagingArea.isVisible).toBe(true);+ expect(originProject.canvas.stagingArea.selectedImageIndex).toBe(1);+ expect(slots[originProject.canvas.stagingArea.selectedImageIndex]).toMatchObject({+ candidate: { imageName: 'second.png', placement: appendedCandidate.placement },+ kind: 'candidate',+ });+ expect(getProject(state, activeProjectId).canvas.stagingArea.pendingImages).toEqual([]);+ });++ it('accepts a workflow candidate at its own placement, scale, and opacity', () => {+ let state = withEmptyCanvas(createInitialWorkbenchState());+ const projectId = state.activeProjectId;+ const candidate = createStagingCandidate('dimension-changing-result.png', 'layer-workflow:request-1', {+ height: 200,+ opacity: 0.35,+ width: 300,+ x: 31,+ y: 47,+ });++ state = workbenchReducer(state, { candidate, projectId, type: 'appendCanvasStagingCandidate' });+ state = workbenchReducer(state, { type: 'acceptStagedImage' });++ const acceptedLayer = getActiveProject(state).canvas.document.layers[0];++ expect(getRasterLayerImageName(acceptedLayer)).toBe('dimension-changing-result.png');+ expect(getRasterLayerPlacement(acceptedLayer)).toEqual(candidate.placement);+ });+it('keeps submitted Generate snapshots immutable after later settings changes', () => {let state = submitGenerate(primeGenerate(undefined, { positivePrompt: 'first prompt', shouldRandomizeSeed: true }));const firstQueueItem = getActiveProject(state).queue.items[0];@@ -566,10 +642,11 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(project.canvas.stagingArea.isVisible).toBe(false);});- it('cycles staged canvas candidates and accepts the selected one at the bbox origin', () => {+ it('normalizes ordinary queue results to the bbox origin and native image size', () => {let state = submitGenerate(primeGenerate());const queueItem = getActiveProject(state).queue.items[0];+ state = workbenchReducer(state, { bbox: { height: 256, width: 256, x: 40, y: 24 }, type: 'setCanvasBbox' });state = workbenchReducer(state, {images: [createImage('candidate-1.png', queueItem.id), createImage('candidate-2.png', queueItem.id)],projectId: getActiveProject(state).id,@@ -579,16 +656,20 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = workbenchReducer(state, { direction: -1, type: 'cycleStagedImage' });expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ expect(getActiveProject(state).canvas.stagingArea.pendingImages[1]?.placement).toEqual({+ height: 768,+ opacity: 1,+ width: 512,+ x: 40,+ y: 24,+ });- // Move the bbox first so we can prove the accepted layer lands at its origin.- state = workbenchReducer(state, { bbox: { height: 256, width: 256, x: 40, y: 24 }, type: 'setCanvasBbox' });state = workbenchReducer(state, { type: 'acceptStagedImage' });let project = getActiveProject(state);const acceptedLayer = project.canvas.document.layers[0];expect(getRasterLayerImageName(acceptedLayer)).toBe('candidate-2.png');- // The v2 accept places the raster at the bbox origin, unscaled (P0.2 Deliverable 3).expect(getRasterLayerPlacement(acceptedLayer)).toEqual({ height: 768, opacity: 1, width: 512, x: 40, y: 24 });// Project undo/redo leaves the engine-owned canvas alone.@@ -646,6 +727,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(slots.map((slot) => slot.kind)).toEqual(['candidate', 'placeholder']);expect(slots[0]).toMatchObject({ itemIndex: 1, kind: 'candidate', queueItemId: queueItem.id });expect(updatedProject.canvas.stagingArea.pendingImages[0]).toMatchObject({ sourceBackendItemId: 11 });+ expect(updatedProject.canvas.stagingArea.pendingImages[0]?.placement).toEqual({+ height: 768,+ opacity: 1,+ width: 512,+ x: updatedProject.canvas.document.bbox.x,+ y: updatedProject.canvas.document.bbox.y,+ });expect(slots[1]).toMatchObject({ itemIndex: 2, queueItemId: queueItem.id });});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 05c9f8d819..fc06592d17 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -213,6 +213,7 @@ type WorkbenchAction =}| { type: 'markQueueItemBackendCancelled'; projectId: string; queueItemId: string; backendItemId: number }| { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }+ | { type: 'appendCanvasStagingCandidate'; projectId: string; candidate: CanvasStagingCandidateContract }| { type: 'setStagedImageIndex'; imageIndex: number }| { type: 'cycleStagedImage'; direction: -1 | 1 }| { type: 'discardSelectedStagedImage' }@@ -590,8 +591,16 @@ const stageCanvasResultImages = (return project;}+ const { bbox } = project.canvas.document;const incomingImages = images.map((image, index) =>- normalizeStagingCandidate(image, project.canvas.document, sourceBackendItemIds?.[index])+ normalizeStagingCandidate(+ {+ ...image,+ placement: { height: image.height, opacity: 1, width: image.width, x: bbox.x, y: bbox.y },+ },+ project.canvas.document,+ sourceBackendItemIds?.[index]+ ));const existingImages = project.canvas.stagingArea.pendingImages;const existingImageKeys = new Set(existingImages.map((image) => `${image.sourceQueueItemId}:${image.imageName}`));@@ -623,6 +632,32 @@ const stageCanvasResultImages = (};};+const appendCanvasStagingCandidate = (project: Project, candidate: CanvasStagingCandidateContract): Project => {+ const appendedCandidate = normalizeStagingCandidate(candidate, project.canvas.document);+ const pendingImages = [...project.canvas.stagingArea.pendingImages, appendedCandidate];+ const candidateKey = `${appendedCandidate.sourceQueueItemId}:${appendedCandidate.imageName}`;+ const slots = getCanvasStagingSlots(getCanvasWithPendingImages(project.canvas, pendingImages), project.queue.items);+ const selectedImageIndex = slots+ .map((slot) => (slot.kind === 'candidate' ? `${slot.candidate.sourceQueueItemId}:${slot.candidate.imageName}` : ''))+ .lastIndexOf(candidateKey);++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ areThumbnailsVisible: true,+ isVisible: true,+ pendingImageIds: pendingImages.map((image) => image.imageName),+ pendingImages,+ selectedImageIndex,+ sourceQueueItemId: appendedCandidate.sourceQueueItemId,+ },+ },+ };+};+const clampCanvasStagingSelection = (project: Project): Project => {const slotCount = getCanvasStagingSlotCount(project.canvas, project.queue.items);const placeholderIndex =@@ -2747,6 +2782,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}));}+ case 'appendCanvasStagingCandidate': {+ return updateProjectById(state, action.projectId, (project) =>+ appendCanvasStagingCandidate(project, action.candidate)+ );+ }case 'setStagedImageIndex': {return updateActiveProject(state, (project) => {const selectedImageIndex = clampStagedImageIndex(@@ -3049,21 +3089,27 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)const acceptedAt = now();// Canvas mutations are engine-owned and no longer participate in project- // undo, so accept does not `pushUndo`. The layer lands at the bbox origin- // (transform x/y = bbox x/y, unscaled), on top, and becomes selected.- const { bbox } = project.canvas.document;+ // undo, so accept does not `pushUndo`. Candidate-specific placement is+ // applied to the new top-most layer, which becomes selected.+ const { placement } = stagedImage;const layer: CanvasRasterLayerContractV2 = {blendMode: 'normal',id: createId('layer'),isEnabled: true,isLocked: false,name: `Layer ${project.canvas.document.layers.length + 1}`,- opacity: 1,+ opacity: placement.opacity,source: {image: { height: stagedImage.height, imageName: stagedImage.imageName, width: stagedImage.width },type: 'image',},- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },+ transform: {+ rotation: 0,+ scaleX: stagedImage.width === 0 ? 1 : placement.width / stagedImage.width,+ scaleY: stagedImage.height === 0 ? 1 : placement.height / stagedImage.height,+ x: placement.x,+ y: placement.y,+ },type: 'raster',};diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.tsindex ef16a554f4..84e931fc46 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts@@ -227,6 +227,63 @@ describe('getProjectGraphReadiness', () => {})).toEqual({ canInvoke: false, reasons: ['"optional-constrained" has invalid input "count".'] });});++ it('treats only explicitly externally satisfied connection inputs as ready', () => {+ const connectionTemplate = template('connection-sink', {+ image: input('image', {+ input: 'connection',+ required: true,+ title: 'Layer image',+ type: { batch: false, cardinality: 'SINGLE', name: 'ImageField' },+ }),+ mask: input('mask', {+ input: 'connection',+ required: true,+ title: 'Mask image',+ type: { batch: false, cardinality: 'SINGLE', name: 'ImageField' },+ }),+ });+ const node = buildInvocationNode(connectionTemplate, { x: 0, y: 0 });+ const doc = { ...createProjectGraph('external-input'), nodes: [{ ...node, id: 'sink' }] };+ const snapshot: InvocationTemplatesSnapshot = {+ error: null,+ status: 'loaded',+ templates: { 'connection-sink': connectionTemplate },+ };++ expect(getProjectGraphReadiness(doc, snapshot, { externallySatisfiedInputs: new Set(['sink:image']) })).toEqual({+ canInvoke: false,+ reasons: ['"connection-sink" is missing a connection for "Mask image".'],+ });+ expect(+ getProjectGraphReadiness(doc, snapshot, {+ externallySatisfiedInputs: new Set(['sink:image', 'sink:mask']),+ })+ ).toEqual({ canInvoke: true, reasons: [] });+ });++ it('does not let external satisfaction bypass a required direct value', () => {+ const directTemplate = template('direct-sink', {+ image: input('image', {+ input: 'direct',+ required: true,+ title: 'Layer image',+ type: { batch: false, cardinality: 'SINGLE', name: 'ImageField' },+ }),+ });+ const node = buildInvocationNode(directTemplate, { x: 0, y: 0 });+ const doc = { ...createProjectGraph('external-direct'), nodes: [{ ...node, id: 'sink' }] };+ const snapshot: InvocationTemplatesSnapshot = {+ error: null,+ status: 'loaded',+ templates: { 'direct-sink': directTemplate },+ };++ expect(getProjectGraphReadiness(doc, snapshot, { externallySatisfiedInputs: new Set(['sink:image']) })).toEqual({+ canInvoke: false,+ reasons: ['"direct-sink" is missing required input "Layer image".'],+ });+ });});describe('compileProjectGraph', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.tsindex 49bdffde6c..7da1cbeb7f 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts@@ -57,9 +57,15 @@ export interface ProjectGraphReadiness {reasons: string[];}+export interface ProjectGraphReadinessOptions {+ /** Required connection inputs supplied by an ephemeral caller after document compilation. */+ externallySatisfiedInputs?: ReadonlySet<string>;+}+export const getProjectGraphReadiness = (document: ProjectGraphState,- templatesSnapshot: InvocationTemplatesSnapshot+ templatesSnapshot: InvocationTemplatesSnapshot,+ options: ProjectGraphReadinessOptions = {}): ProjectGraphReadiness => {if (templatesSnapshot.status === 'error') {return { canInvoke: false, reasons: ['Node definitions failed to load from the backend.'] };@@ -103,7 +109,7 @@ export const getProjectGraphReadiness = (}if (inputTemplate.input === 'connection') {- if (inputTemplate.required) {+ if (inputTemplate.required && !options.externallySatisfiedInputs?.has(`${node.id}:${inputTemplate.name}`)) {reasons.push(`"${getNodeDisplayName(node, templates)}" is missing a connection for "${inputTemplate.title}".`);diff --git a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.tsnew file mode 100644index 0000000000..5e5b45d8e4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.ts@@ -0,0 +1,433 @@+import { describe, expect, it } from 'vitest';++import type { InvocationTemplatesSnapshot } from './templates';+import type {+ FieldInputTemplate,+ FieldOutputTemplate,+ InvocationTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowEdge,+ WorkflowInvocationNode,+} from './types';++import { buildConnectorNode, buildInvocationNode, createProjectGraph } from './document';+import {+ buildLayerWorkflowGraph,+ getDefaultLayerWorkflowSelection,+ getLayerWorkflowInputs,+ getLayerWorkflowOutputs,+ getRunnableLayerWorkflowInputs,+ reconcileLayerWorkflowSelection,+ type WorkflowImageBinding,+} from './layerWorkflow';++const imageType = { batch: false, cardinality: 'SINGLE' as const, name: 'ImageField' };++const input = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name,+ type: imageType,+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});++const output = (name: string, overrides: Partial<FieldOutputTemplate> = {}): FieldOutputTemplate => ({+ description: '',+ name,+ title: name,+ type: imageType,+ ...overrides,+});++const template = (+ type: string,+ inputs: Record<string, FieldInputTemplate> = {},+ outputs: Record<string, FieldOutputTemplate> = {}+): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs,+ nodePack: 'invokeai',+ outputs,+ outputType: `${type}_output`,+ tags: [],+ title: type,+ type,+ useCache: true,+ version: '1.0.0',+});++const node = (+ id: string,+ invocationTemplate: InvocationTemplate,+ options: { fieldLabels?: Record<string, string>; label?: string } = {}+): WorkflowInvocationNode => {+ const built = buildInvocationNode(invocationTemplate, { x: 0, y: 0 });++ for (const [fieldName, label] of Object.entries(options.fieldLabels ?? {})) {+ const instance = built.data.inputs[fieldName];++ if (instance) {+ instance.label = label;+ }+ }++ return { ...built, data: { ...built.data, label: options.label ?? '' }, id };+};++const document = (nodes: WorkflowInvocationNode[], edges: WorkflowEdge[] = []): ProjectGraphState => ({+ ...createProjectGraph('layer-workflow-test', 'Layer Workflow'),+ edges,+ nodes,+});++const loaded = (templates: InvocationTemplates): InvocationTemplatesSnapshot => ({+ error: null,+ status: 'loaded',+ templates,+});++const binding = (nodeId: string, fieldName: string, label = ''): WorkflowImageBinding => ({+ fieldName,+ label,+ nodeId,+});++describe('layer workflow binding discovery', () => {+ it('finds unconnected image inputs across all input modes in document and UI order', () => {+ const sourceTemplate = template('source', {}, { image: output('image', { title: 'Image' }) });+ const sinkTemplate = template('sink', {+ directEdgeTarget: input('directEdgeTarget', { input: 'any', title: 'Connected directly', uiOrder: 0 }),+ directOptional: input('directOptional', { input: 'direct', title: 'Optional image', uiOrder: 1 }),+ directRequired: input('directRequired', { input: 'direct', required: true, title: 'Required image', uiOrder: 2 }),+ anyAvailable: input('anyAvailable', { input: 'any', title: 'Any image', uiOrder: 3 }),+ connectionOnly: input('connectionOnly', {+ input: 'connection',+ required: true,+ title: 'Connection image',+ uiOrder: 4,+ }),+ connectorTarget: input('connectorTarget', {+ input: 'connection',+ title: 'Connected through connector',+ uiOrder: 5,+ }),+ collection: input('collection', {+ title: 'Image collection',+ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' },+ uiOrder: 6,+ }),+ batch: input('batch', {+ title: 'Image batch',+ type: { batch: true, cardinality: 'SINGLE', name: 'ImageField' },+ uiOrder: 7,+ }),+ text: input('text', {+ title: 'Text',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ uiOrder: 8,+ }),+ });+ const otherTemplate = template('other', {+ image: input('image', { input: 'direct', title: 'Other image', uiOrder: 0 }),+ });+ const unknownTemplate = template('unknown', { image: input('image', { title: 'Unknown image' }) });+ const source = node('source', sourceTemplate);+ const sink = node('sink', sinkTemplate, {+ fieldLabels: { directOptional: 'Custom image field' },+ label: 'Custom sink',+ });+ const unknown = node('unknown', unknownTemplate);+ const other = node('other', otherTemplate);+ const connector = { ...buildConnectorNode({ x: 0, y: 0 }), id: 'connector' };+ const doc = {+ ...document([sink, unknown, other, source]),+ nodes: [sink, connector, unknown, other, source],+ edges: [+ {+ id: 'direct',+ source: 'source',+ sourceHandle: 'image',+ target: 'sink',+ targetHandle: 'directEdgeTarget',+ type: 'default',+ },+ {+ id: 'connector-in',+ source: 'source',+ sourceHandle: 'image',+ target: 'connector',+ targetHandle: 'in',+ type: 'default',+ },+ {+ id: 'connector-out',+ source: 'connector',+ sourceHandle: 'out',+ target: 'sink',+ targetHandle: 'connectorTarget',+ type: 'default',+ },+ ],+ } satisfies ProjectGraphState;+ const templates = { other: otherTemplate, sink: sinkTemplate, source: sourceTemplate };++ expect(getLayerWorkflowInputs(doc, templates)).toEqual([+ binding('sink', 'directOptional', 'Custom sink → Custom image field'),+ binding('sink', 'directRequired', 'Custom sink → Required image'),+ binding('sink', 'anyAvailable', 'Custom sink → Any image'),+ binding('sink', 'connectionOnly', 'Custom sink → Connection image'),+ binding('other', 'image', 'other → Other image'),+ ]);+ });++ it('finds only single non-batch image outputs and skips image primitive nodes', () => {+ const processorTemplate = template(+ 'processor',+ {},+ {+ first: output('first', { title: 'First image' }),+ collection: output('collection', {+ title: 'Image collection',+ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' },+ }),+ second: output('second', { title: 'Second image' }),+ batch: output('batch', {+ title: 'Image batch',+ type: { batch: true, cardinality: 'SINGLE', name: 'ImageField' },+ }),+ text: output('text', {+ title: 'Text',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ }),+ }+ );+ const otherTemplate = template('other', {}, { image: output('image', { title: 'Other image' }) });+ const primitiveTemplate = template('image', {}, { image: output('image', { title: 'Primitive image' }) });+ const unknownTemplate = template('unknown', {}, { image: output('image') });+ const doc = document([+ node('processor', processorTemplate, { label: 'Custom processor' }),+ node('primitive', primitiveTemplate),+ node('unknown', unknownTemplate),+ node('other', otherTemplate),+ ]);+ const templates = { image: primitiveTemplate, other: otherTemplate, processor: processorTemplate };++ expect(getLayerWorkflowOutputs(doc, templates)).toEqual([+ binding('processor', 'first', 'Custom processor → First image'),+ binding('processor', 'second', 'Custom processor → Second image'),+ binding('other', 'image', 'other → Other image'),+ ]);+ });++ it('probes every candidate after sentinel injection and keeps a valid candidate after an invalid first one', () => {+ const processorTemplate = template(+ 'processor',+ {+ optionalFirst: input('optionalFirst', { input: 'direct', title: 'Optional first', uiOrder: 0 }),+ requiredSecond: input('requiredSecond', {+ input: 'direct',+ required: true,+ title: 'Required second',+ uiOrder: 1,+ }),+ },+ { image: output('image', { title: 'Result' }) }+ );+ const doc = document([node('processor', processorTemplate)]);+ const outputBinding = getLayerWorkflowOutputs(doc, { processor: processorTemplate })[0]!;++ expect(getRunnableLayerWorkflowInputs(doc, loaded({ processor: processorTemplate }), outputBinding)).toEqual([+ binding('processor', 'requiredSecond', 'processor → Required second'),+ ]);+ });+});++describe('layer workflow dialog selection', () => {+ it('defaults to Gallery and the first output that has a runnable input', () => {+ const firstOutput = binding('first-output', 'image', 'First output');+ const secondOutput = binding('second-output', 'image', 'Second output');+ const secondInput = binding('second-input', 'image', 'Second input');++ expect(+ getDefaultLayerWorkflowSelection([firstOutput, secondOutput], (candidate) =>+ candidate.nodeId === secondOutput.nodeId ? [secondInput] : []+ )+ ).toEqual({ destination: 'gallery', input: secondInput, output: secondOutput });+ });++ it('returns an empty Gallery selection when no output has a runnable input', () => {+ expect(getDefaultLayerWorkflowSelection([binding('output', 'image')], () => [])).toEqual({+ destination: 'gallery',+ input: null,+ output: null,+ });+ });++ it('preserves the current input by identity when it remains runnable for a changed output', () => {+ const currentInput = binding('input', 'image', 'Old label');+ const changedOutput = binding('changed-output', 'image', 'Changed output');+ const refreshedInput = binding('input', 'image', 'Refreshed label');++ expect(+ reconcileLayerWorkflowSelection(+ { destination: 'staging', input: currentInput, output: binding('old-output', 'image') },+ changedOutput,+ [refreshedInput, binding('fallback', 'image')]+ )+ ).toEqual({ destination: 'staging', input: refreshedInput, output: changedOutput });+ });++ it('falls back to the first runnable input for a changed output', () => {+ const changedOutput = binding('changed-output', 'image', 'Changed output');+ const firstRunnable = binding('first-input', 'image', 'First input');++ expect(+ reconcileLayerWorkflowSelection(+ { destination: 'copy-raster', input: binding('old-input', 'image'), output: binding('old-output', 'image') },+ changedOutput,+ [firstRunnable, binding('second-input', 'image')]+ )+ ).toEqual({ destination: 'copy-raster', input: firstRunnable, output: changedOutput });+ });+});++describe('buildLayerWorkflowGraph', () => {+ it('injects a direct-capable input before readiness without mutating the document', () => {+ const processorTemplate = template(+ 'processor',+ {+ image: input('image', { input: 'direct', required: true, title: 'Layer image' }),+ },+ { result: output('result', { title: 'Result image' }) }+ );+ const processor = node('processor', processorTemplate);+ delete processor.data.inputs.image;+ const doc = document([processor]);+ const before = structuredClone(doc);+ const built = buildLayerWorkflowGraph({+ document: doc,+ imageName: 'layer.png',+ input: binding('processor', 'image'),+ output: binding('processor', 'result'),+ templatesSnapshot: loaded({ processor: processorTemplate }),+ });++ expect(doc).toEqual(before);+ expect(built.graph.nodes.processor).toMatchObject({+ image: { image_name: 'layer.png' },+ is_intermediate: true,+ type: 'processor',+ });+ expect(built.graph.nodes[built.outputNodeId]).toMatchObject({+ id: built.outputNodeId,+ is_intermediate: true,+ type: 'image',+ });+ expect(built.graph.edges).toContainEqual({+ destination: { field: 'image', node_id: built.outputNodeId },+ source: { field: 'result', node_id: 'processor' },+ });+ expect(Object.values(built.graph.nodes).every((graphNode) => graphNode.is_intermediate === true)).toBe(true);+ });++ it('externally satisfies only the selected connection input and appends collision-safe source and capture nodes', () => {+ const sinkTemplate = template('sink', {+ image: input('image', { input: 'connection', required: true, title: 'Layer image' }),+ });+ const resultTemplate = template('result', {}, { image: output('image', { title: 'Result image' }) });+ const doc = document([node('layer-workflow-source', sinkTemplate), node('layer-workflow-output', resultTemplate)]);+ const built = buildLayerWorkflowGraph({+ document: doc,+ imageName: 'layer.png',+ input: binding('layer-workflow-source', 'image'),+ output: binding('layer-workflow-output', 'image'),+ templatesSnapshot: loaded({ result: resultTemplate, sink: sinkTemplate }),+ });++ expect(built.outputNodeId).toBe('layer-workflow-output-1');+ expect(built.graph.nodes['layer-workflow-source-1']).toMatchObject({+ id: 'layer-workflow-source-1',+ image: { image_name: 'layer.png' },+ is_intermediate: true,+ type: 'image',+ });+ expect(built.graph.edges).toContainEqual({+ destination: { field: 'image', node_id: 'layer-workflow-source' },+ source: { field: 'image', node_id: 'layer-workflow-source-1' },+ });+ expect(built.graph.edges).toContainEqual({+ destination: { field: 'image', node_id: 'layer-workflow-output-1' },+ source: { field: 'image', node_id: 'layer-workflow-output' },+ });+ });++ it('reports readiness errors that remain after image injection and preserves the document', () => {+ const processorTemplate = template(+ 'processor',+ {+ image: input('image', { input: 'direct', required: true, title: 'Layer image' }),+ prompt: input('prompt', {+ input: 'direct',+ required: true,+ title: 'Prompt',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ }),+ },+ { result: output('result') }+ );+ const doc = document([node('processor', processorTemplate)]);+ const before = structuredClone(doc);++ expect(() =>+ buildLayerWorkflowGraph({+ document: doc,+ imageName: 'layer.png',+ input: binding('processor', 'image'),+ output: binding('processor', 'result'),+ templatesSnapshot: loaded({ processor: processorTemplate }),+ })+ ).toThrow(/missing required input "Prompt"/);+ expect(doc).toEqual(before);+ });++ it('rejects stale input and output bindings', () => {+ const processorTemplate = template(+ 'processor',+ { image: input('image', { input: 'direct', required: true }) },+ { result: output('result') }+ );+ const doc = document([node('processor', processorTemplate)]);+ const options = {+ document: doc,+ imageName: 'layer.png',+ input: binding('processor', 'image'),+ output: binding('processor', 'result'),+ templatesSnapshot: loaded({ processor: processorTemplate }),+ };++ expect(() => buildLayerWorkflowGraph({ ...options, input: binding('processor', 'removed') })).toThrow(+ /input binding is no longer available/i+ );+ expect(() => buildLayerWorkflowGraph({ ...options, output: binding('processor', 'removed') })).toThrow(+ /output binding is no longer available/i+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.tsnew file mode 100644index 0000000000..825b9ac6d7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.ts@@ -0,0 +1,331 @@+import type { BackendGraphContract } from '@workbench/types';++import type { InvocationTemplatesSnapshot } from './templates';+import type {+ FieldInputTemplate,+ FieldOutputTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowInvocationNode,+} from './types';++import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';+import { getResolvedWorkflowEdgesIndexed } from './connectors';+import { createWorkflowGraphIndex } from './graphIndex';+import { isInvocationNode } from './types';++const READINESS_IMAGE_NAME = 'layer-action-readiness.png';+const SOURCE_NODE_ID = 'layer-workflow-source';+const CAPTURE_NODE_ID = 'layer-workflow-output';++export interface WorkflowImageBinding {+ nodeId: string;+ fieldName: string;+ label: string;+}++export type LayerWorkflowDestination = 'gallery' | 'staging' | 'replace' | 'copy-raster';++export interface LayerWorkflowSelection {+ destination: LayerWorkflowDestination;+ input: WorkflowImageBinding | null;+ output: WorkflowImageBinding | null;+}++export type GetRunnableLayerWorkflowInputs = (output: WorkflowImageBinding) => readonly WorkflowImageBinding[];++export interface BuildLayerWorkflowGraphOptions {+ document: ProjectGraphState;+ templatesSnapshot: InvocationTemplatesSnapshot;+ input: WorkflowImageBinding;+ output: WorkflowImageBinding;+ imageName: string;+}++export interface BuiltLayerWorkflowGraph {+ graph: BackendGraphContract;+ outputNodeId: string;+}++const isSingleImageField = (field: FieldInputTemplate | FieldOutputTemplate): boolean =>+ field.type.name === 'ImageField' && field.type.cardinality === 'SINGLE' && !field.type.batch;++const getNodeLabel = (node: WorkflowInvocationNode, templates: InvocationTemplates): string =>+ node.data.label || templates[node.data.type]?.title || node.data.type;++const getInputLabel = (node: WorkflowInvocationNode, field: FieldInputTemplate): string =>+ node.data.inputs[field.name]?.label || field.title || field.name;++const toBinding = (node: WorkflowInvocationNode, fieldName: string, fieldLabel: string, nodeLabel: string) => ({+ fieldName,+ label: `${nodeLabel} → ${fieldLabel}`,+ nodeId: node.id,+});++const isSameBinding = (left: WorkflowImageBinding, right: WorkflowImageBinding): boolean =>+ left.nodeId === right.nodeId && left.fieldName === right.fieldName;++/** Chooses the first output that can actually run, rather than assuming the first output is runnable. */+export const getDefaultLayerWorkflowSelection = (+ outputs: readonly WorkflowImageBinding[],+ getRunnableInputs: GetRunnableLayerWorkflowInputs+): LayerWorkflowSelection => {+ for (const output of outputs) {+ const input = getRunnableInputs(output)[0];++ if (input) {+ return { destination: 'gallery', input, output };+ }+ }++ return { destination: 'gallery', input: null, output: null };+};++/** Reconciles a changed output while preserving a still-runnable input by field identity. */+export const reconcileLayerWorkflowSelection = (+ current: LayerWorkflowSelection,+ output: WorkflowImageBinding,+ runnableInputs: readonly WorkflowImageBinding[]+): LayerWorkflowSelection => {+ const currentInput = current.input;+ const preservedInput = currentInput+ ? runnableInputs.find((candidate) => isSameBinding(candidate, currentInput))+ : undefined;++ return {+ destination: current.destination,+ input: preservedInput ?? runnableInputs[0] ?? null,+ output,+ };+};++const sortInputFields = (fields: FieldInputTemplate[]): FieldInputTemplate[] =>+ fields+ .map((field, index) => ({ field, index }))+ .sort(+ (left, right) =>+ (left.field.uiOrder ?? Number.MAX_SAFE_INTEGER) - (right.field.uiOrder ?? Number.MAX_SAFE_INTEGER) ||+ left.index - right.index+ )+ .map(({ field }) => field);++/** Returns all unconnected, scalar ImageField inputs in document/UI order. */+export const getLayerWorkflowInputs = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): WorkflowImageBinding[] => {+ const index = createWorkflowGraphIndex(document.nodes, document.edges);+ const connectedInputs = new Set(+ getResolvedWorkflowEdgesIndexed(document.edges, index, templates).map(+ (edge) => `${edge.target}:${edge.targetHandle}`+ )+ );+ const bindings: WorkflowImageBinding[] = [];++ for (const candidate of document.nodes) {+ if (!isInvocationNode(candidate)) {+ continue;+ }++ const template = templates[candidate.data.type];++ if (!template) {+ continue;+ }++ for (const field of sortInputFields(Object.values(template.inputs))) {+ if (!isSingleImageField(field) || connectedInputs.has(`${candidate.id}:${field.name}`)) {+ continue;+ }++ bindings.push(+ toBinding(candidate, field.name, getInputLabel(candidate, field), getNodeLabel(candidate, templates))+ );+ }+ }++ return bindings;+};++/** Returns scalar ImageField outputs in document/field order, excluding the image echo primitive. */+export const getLayerWorkflowOutputs = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): WorkflowImageBinding[] => {+ const bindings: WorkflowImageBinding[] = [];++ for (const candidate of document.nodes) {+ if (!isInvocationNode(candidate) || candidate.data.type === 'image') {+ continue;+ }++ const template = templates[candidate.data.type];++ if (!template) {+ continue;+ }++ for (const field of Object.values(template.outputs)) {+ if (!isSingleImageField(field)) {+ continue;+ }++ bindings.push(toBinding(candidate, field.name, field.title || field.name, getNodeLabel(candidate, templates)));+ }+ }++ return bindings;+};++const getAvailableBinding = (+ bindings: WorkflowImageBinding[],+ selected: WorkflowImageBinding+): WorkflowImageBinding | undefined => bindings.find((candidate) => isSameBinding(candidate, selected));++const allocateNodeId = (graph: BackendGraphContract, base: string): string => {+ if (!graph.nodes[base]) {+ return base;+ }++ let suffix = 1;++ while (graph.nodes[`${base}-${suffix}`]) {+ suffix += 1;+ }++ return `${base}-${suffix}`;+};++/**+ * Builds a throwaway backend graph that feeds one workflow image input and+ * captures one workflow image output. The editable workflow document is never+ * mutated.+ */+export const buildLayerWorkflowGraph = (options: BuildLayerWorkflowGraphOptions): BuiltLayerWorkflowGraph => {+ const { document, imageName, input, output, templatesSnapshot } = options;++ if (templatesSnapshot.status !== 'loaded') {+ throw new Error('Workflow node definitions are not loaded.');+ }++ const templates = templatesSnapshot.templates;+ const cloned = structuredClone(document);+ const availableInput = getAvailableBinding(getLayerWorkflowInputs(cloned, templates), input);++ if (!availableInput) {+ throw new Error('The selected workflow input binding is no longer available.');+ }++ const availableOutput = getAvailableBinding(getLayerWorkflowOutputs(cloned, templates), output);++ if (!availableOutput) {+ throw new Error('The selected workflow output binding is no longer available.');+ }++ const inputNode = cloned.nodes.find(+ (candidate): candidate is WorkflowInvocationNode => candidate.id === input.nodeId && isInvocationNode(candidate)+ );+ const inputTemplate = inputNode ? templates[inputNode.data.type]?.inputs[input.fieldName] : undefined;++ if (!inputNode || !inputTemplate) {+ throw new Error('The selected workflow input binding is no longer available.');+ }++ const isConnectionOnly = inputTemplate.input === 'connection';+ const externallySatisfiedInputs = isConnectionOnly ? new Set([`${input.nodeId}:${input.fieldName}`]) : undefined;++ if (!isConnectionOnly) {+ const instance = inputNode.data.inputs[input.fieldName];++ inputNode.data.inputs[input.fieldName] = {+ label: instance?.label ?? '',+ name: input.fieldName,+ ...(instance?.description === undefined ? {} : { description: instance.description }),+ value: { image_name: imageName },+ };+ }++ const readiness = getProjectGraphReadiness(cloned, templatesSnapshot, { externallySatisfiedInputs });++ if (!readiness.canInvoke) {+ throw new Error(`Workflow is not ready: ${readiness.reasons.join(' ')}`);+ }++ const compiled = compileProjectGraph(cloned, templates);+ const graph = compiled.backendGraph;++ if (!graph) {+ throw new Error('Workflow compilation did not produce a backend graph.');+ }++ for (const graphNode of Object.values(graph.nodes)) {+ graphNode.is_intermediate = true;+ }++ if (isConnectionOnly) {+ const sourceNodeId = allocateNodeId(graph, SOURCE_NODE_ID);+ const targetNode = graph.nodes[input.nodeId];++ if (!targetNode) {+ throw new Error('The selected workflow input node was not compiled.');+ }++ delete targetNode[input.fieldName];+ graph.nodes[sourceNodeId] = {+ id: sourceNodeId,+ image: { image_name: imageName },+ is_intermediate: true,+ type: 'image',+ use_cache: false,+ };+ graph.edges.push({+ destination: { field: input.fieldName, node_id: input.nodeId },+ source: { field: 'image', node_id: sourceNodeId },+ });+ }++ if (!graph.nodes[output.nodeId]) {+ throw new Error('The selected workflow output node was not compiled.');+ }++ const outputNodeId = allocateNodeId(graph, CAPTURE_NODE_ID);++ graph.nodes[outputNodeId] = {+ id: outputNodeId,+ is_intermediate: true,+ type: 'image',+ use_cache: false,+ };+ graph.edges.push({+ destination: { field: 'image', node_id: outputNodeId },+ source: { field: output.fieldName, node_id: output.nodeId },+ });++ return { graph, outputNodeId };+};++/** Keeps only inputs that produce a fully runnable graph after sentinel injection. */+export const getRunnableLayerWorkflowInputs = (+ document: ProjectGraphState,+ templatesSnapshot: InvocationTemplatesSnapshot,+ output: WorkflowImageBinding+): WorkflowImageBinding[] => {+ if (templatesSnapshot.status !== 'loaded') {+ return [];+ }++ return getLayerWorkflowInputs(document, templatesSnapshot.templates).filter((input) => {+ try {+ buildLayerWorkflowGraph({+ document,+ imageName: READINESS_IMAGE_NAME,+ input,+ output,+ templatesSnapshot,+ });+ return true;+ } catch {+ return false;+ }+ });+};