Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(canvas): harden canvas filter operations

joshistoastb49c2e0bc013
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.test.ts
index 192ea0387f..81edb2e48d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.test.ts
@@ -13,6 +13,20 @@ const jsonResponse = (body: unknown, init: { ok?: boolean; status?: number; stat
}) as unknown as Response;
describe('uploadCanvasImage', () => {
+ it('forwards an abort signal to fetch', async () => {
+ const controller = new AbortController();
+ const fetchImpl = vi.fn(() =>
+ Promise.resolve(jsonResponse({ height: 1, image_name: 'uploaded.png', width: 1 }))
+ ) as unknown as typeof fetch;
+
+ await uploadCanvasImage(new Blob(['pixels'], { type: 'image/png' }), {
+ fetch: fetchImpl,
+ signal: controller.signal,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: controller.signal }));
+ });
+
it('POSTs a multipart file to the upload endpoint with the persistence params', async () => {
const fetchImpl = vi.fn(() =>
Promise.resolve(jsonResponse({ height: 64, image_name: 'paint-1.png', width: 128 }, { status: 201 }))
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.ts
index 69477e5882..3fae207ce2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/canvasImages.ts
@@ -41,6 +41,8 @@ export interface UploadCanvasImageOptions {
fileName?: string;
/** Injectable `fetch` implementation (defaults to the global). */
fetch?: typeof globalThis.fetch;
+ /** Cancels the multipart request when its owning operation is superseded. */
+ signal?: AbortSignal;
}
/** Thrown when a canvas-image upload fails (non-2xx or network error). */
@@ -90,8 +92,12 @@ export const uploadCanvasImage = async (
body,
headers,
method: 'POST',
+ signal: options.signal,
});
} catch (error) {
+ if (error instanceof Error && error.name === 'AbortError') {
+ throw error;
+ }
throw new CanvasImageUploadError(
`Canvas image upload failed: ${error instanceof Error ? error.message : String(error)}`,
null
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 5c5e1a888e..58fe81bd9b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -4867,6 +4867,30 @@ describe('mergeVisibleRasterLayers', () => {
engine.dispose();
});
+ it('blocks the group merge without closing an operation and restores it after cancel', async () => {
+ const { engine, raf } = setup(interleavedDoc());
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+ const exported = await engine.exportLayerPixels('upper');
+ if (exported.status !== 'ok') {
+ throw new Error('expected an operation guard');
+ }
+ const session = engine.canvasOperations.start({
+ cleanupPreview: vi.fn(),
+ guard: exported.guard,
+ identity: { kind: 'filter', layerId: 'upper', projectId: engine.projectId },
+ });
+
+ expect(engine.mergeVisibleRasterLayers()).toBe('nothing');
+ expect(engine.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({ identity: { kind: 'filter' }, status: 'active' });
+
+ session?.cancel();
+ expect(engine.mergeVisibleRasterLayers()).toBe('merged');
+ engine.dispose();
+ });
+
it('folds an all-empty run trivially instead of stalling on a half-merged stack (F4)', async () => {
const base = twoPaintDoc();
const doc: CanvasDocumentContractV2 = {
@@ -5876,12 +5900,6 @@ describe('commitRasterFilterResult', () => {
throw new Error('expected a filterable export');
}
const invalidateSource = vi.spyOn(engine.canvasOperations, 'invalidateSource');
- const cleanupPreview = vi.fn(() => invalidateSource.mockClear());
- engine.canvasOperations.start({
- cleanupPreview,
- guard: exported.guard,
- identity: { kind: 'filter', layerId: layer.id, projectId },
- });
const result = await engine.commitRasterFilterResult({
guard: exported.guard,
@@ -5891,7 +5909,6 @@ describe('commitRasterFilterResult', () => {
});
expect(result).toEqual({ layerId: layer.id, status: 'committed' });
- expect(cleanupPreview).toHaveBeenCalledOnce();
expect(invalidateSource).toHaveBeenCalledWith(projectId, layer.id);
expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });
const after = engine.getDocument()!.layers[0]!;
@@ -9070,6 +9087,190 @@ describe('guarded filter previews', () => {
engine.dispose();
});
+ const filterFlowLayer = (
+ type: 'raster' | 'control'
+ ): Extract<CanvasLayerContract, { type: 'raster' | 'control' }> => {
+ const base = {
+ blendMode: 'multiply' as const,
+ filter: { settings: { radius: 2 }, type: 'content_shuffle' },
+ id: 'filter-source',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Filter source',
+ opacity: 0.6,
+ source: {
+ bitmap: { height: 10, imageName: 'filter-source.png', width: 10 },
+ offset: { x: 7, y: -3 },
+ type: 'paint' as const,
+ },
+ transform: { rotation: 12, scaleX: 2, scaleY: 3, x: 40, y: 50 },
+ };
+ return type === 'raster'
+ ? { ...base, type: 'raster' }
+ : {
+ ...base,
+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
+ type: 'control',
+ withTransparencyEffect: true,
+ };
+ };
+
+ const createFilterFlowHarness = async (sourceType: 'raster' | 'control') => {
+ const source = filterFlowLayer(sourceType);
+ const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ filterDeps: {
+ runGraph: vi.fn(() => Promise.resolve({ imageName: 'filtered.png', origin: 'canvas', output: {} })),
+ uploadIntermediate: vi.fn(() => Promise.resolve({ imageName: 'filter-input.png' })),
+ },
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ expect((await engine.exportLayerPixels(source.id)).status).toBe('ok');
+ expect(engine.startFilterOperation(source.id)).toBe('started');
+ await engine.processFilterOperation();
+ expect(engine.stores.filterSession.get()).toMatchObject({
+ preview: { imageName: 'filtered.png' },
+ status: 'ready',
+ });
+ return { document, engine, source };
+ };
+
+ it.each(['raster', 'control'] as const)(
+ 'processes, retries durability, and applies %s with one origin-preserving history entry',
+ async (sourceType) => {
+ const { document, engine, source } = await createFilterFlowHarness(sourceType);
+ const makeDurable = vi
+ .fn<(imageName: string) => Promise<void>>()
+ .mockRejectedValueOnce(new Error('promotion failed'))
+ .mockResolvedValueOnce();
+
+ await engine.commitFilterOperation('apply', makeDurable);
+ expect(engine.stores.filterSession.get()).toMatchObject({
+ error: 'promotion failed',
+ preview: { imageName: 'filtered.png' },
+ status: 'error',
+ });
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({ identity: { kind: 'filter' }, status: 'active' });
+
+ await engine.commitFilterOperation('apply', makeDurable);
+ expect(makeDurable).toHaveBeenCalledTimes(2);
+ expect(engine.stores.filterSession.get()).toBeNull();
+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });
+ expect(engine.getDocument()!.layers[0]).toMatchObject({
+ filter: source.filter,
+ opacity: source.opacity,
+ blendMode: source.blendMode,
+ source: { offset: { x: 7, y: -3 }, type: 'paint' },
+ transform: source.transform,
+ type: sourceType,
+ });
+ expect(engine.stores.canUndo.get()).toBe(true);
+ engine.undo();
+ expect(engine.getDocument()).toEqual(document);
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.dispose();
+ }
+ );
+
+ it.each(['raster', 'control'] as const)(
+ 'processes and saves as %s above the source with one history entry',
+ async (target) => {
+ const { engine, source } = await createFilterFlowHarness('control');
+
+ await engine.commitFilterOperation(target, () => Promise.resolve());
+
+ expect(engine.stores.filterSession.get()).toBeNull();
+ expect(engine.getDocument()!.layers.map((layer) => layer.type)).toEqual([target, 'control']);
+ expect(engine.getDocument()!.layers[0]).toMatchObject({
+ blendMode: source.blendMode,
+ opacity: source.opacity,
+ source: { offset: { x: 7, y: -3 }, type: 'paint' },
+ transform: source.transform,
+ });
+ expect(engine.stores.canUndo.get()).toBe(true);
+ engine.undo();
+ expect(engine.getDocument()!.layers).toEqual([source]);
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.dispose();
+ }
+ );
+
+ it('cancels an in-flight promotion when a replacement operation starts', async () => {
+ const { engine, source } = await createFilterFlowHarness('raster');
+ let resolvePromotion!: () => void;
+ const promotion = new Promise<void>((resolve) => {
+ resolvePromotion = resolve;
+ });
+ const pending = engine.commitFilterOperation('apply', () => promotion);
+ await vi.waitFor(() => expect(engine.stores.filterSession.get()?.status).toBe('committing'));
+
+ expect(engine.startSelectObject(source.id)).toBe('started');
+ resolvePromotion();
+ await pending;
+
+ expect(engine.getDocument()!.layers[0]).toEqual(source);
+ expect(engine.stores.filterSession.get()).toBeNull();
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'select-object' },
+ status: 'active',
+ });
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.dispose();
+ });
+
+ it('aborts an in-flight upload when a newer Process request wins', async () => {
+ const source = filterFlowLayer('raster');
+ const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const uploadSignals: AbortSignal[] = [];
+ let uploadCount = 0;
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ filterDeps: {
+ runGraph: () => Promise.resolve({ imageName: 'newest-filter.png', origin: 'canvas', output: {} }),
+ uploadIntermediate: (_blob, signal) => {
+ if (!signal) {
+ throw new Error('expected upload cancellation signal');
+ }
+ uploadSignals.push(signal);
+ uploadCount += 1;
+ if (uploadCount === 2) {
+ return Promise.resolve({ imageName: 'newest-input.png' });
+ }
+ return new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new DOMException('superseded', 'AbortError')), {
+ once: true,
+ });
+ });
+ },
+ },
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ expect((await engine.exportLayerPixels(source.id)).status).toBe('ok');
+ expect(engine.startFilterOperation(source.id)).toBe('started');
+
+ const older = engine.processFilterOperation();
+ await vi.waitFor(() => expect(uploadSignals).toHaveLength(1));
+ const newer = engine.processFilterOperation();
+ await Promise.all([older, newer]);
+
+ expect(uploadSignals[0]?.aborted).toBe(true);
+ expect(engine.stores.filterSession.get()).toMatchObject({
+ error: null,
+ preview: { imageName: 'newest-filter.png' },
+ status: 'ready',
+ });
+ engine.dispose();
+ });
+
it('makes filter and Select Object operations mutually exclusive', async () => {
const document = { ...emptyDoc(), layers: [guardableLayer('L')] };
const { store } = createReactiveStore(document);
@@ -9119,6 +9320,65 @@ describe('guarded filter previews', () => {
engine.dispose();
});
+ it.each(['filter', 'select-object'] as const)(
+ 'centrally blocks edits and undo during %s, then restores them after cancel',
+ async (kind) => {
+ const layer = guardableLayer('L');
+ const document = { ...emptyDoc(), layers: [layer], selectedLayerId: layer.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ expect((await engine.exportLayerPixels('L')).status).toBe('ok');
+ engine.commitStructural(
+ 'Rename',
+ { id: 'L', patch: { name: 'Renamed' }, type: 'updateCanvasLayer' },
+ { id: 'L', patch: { name: 'L' }, type: 'updateCanvasLayer' }
+ );
+ const guard = engine.captureLayerExportGuard('L');
+ if (!guard) {
+ throw new Error('expected a current operation guard');
+ }
+ const operation = engine.canvasOperations.start({
+ cleanupPreview: vi.fn(),
+ guard,
+ identity: { kind, layerId: 'L', projectId },
+ });
+
+ expect(engine.stores.documentEditingLocked.get()).toBe(true);
+ engine.undo();
+ expect(engine.applyStructuralPreview({ id: 'L', patch: { opacity: 0.2 }, type: 'updateCanvasLayer' })).toBe(
+ false
+ );
+ engine.commitStructural(
+ 'Blocked rename',
+ { id: 'L', patch: { name: 'Blocked' }, type: 'updateCanvasLayer' },
+ { id: 'L', patch: { name: 'Renamed' }, type: 'updateCanvasLayer' }
+ );
+ engine.nudgeSelectedLayer(5, 0);
+ await expect(
+ engine.commitRasterFilterResult({
+ guard,
+ image: { height: 10, imageName: 'unauthorized.png', width: 10 },
+ mode: 'replace',
+ rect: { height: 10, width: 10, x: 0, y: 0 },
+ })
+ ).resolves.toEqual({ status: 'busy' });
+
+ expect(engine.getDocument()!.layers[0]).toMatchObject({ name: 'Renamed', transform: { x: 0 } });
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({ identity: { kind }, status: 'active' });
+
+ operation?.cancel();
+ expect(engine.stores.documentEditingLocked.get()).toBe(false);
+ engine.undo();
+ expect(engine.getDocument()!.layers[0]?.name).toBe('L');
+ engine.dispose();
+ }
+ );
+
it('invalidates the owned filter session when its guarded source changes', async () => {
const layer = guardableLayer('L');
const document = { ...emptyDoc(), layers: [layer] };
@@ -11141,10 +11401,32 @@ describe('engine selection: fill / erase', () => {
engine.dispose();
});
- it.each([
- ['paint', (engine: CanvasEngine) => engine.fillSelection()],
- ['cache clear', (engine: CanvasEngine) => engine.clearCaches()],
- ] as const)('%s cancels a guarded operation and cleans its preview', async (_label, mutate) => {
+ it('blocks paint without closing a guarded operation', async () => {
+ const { engine } = makeEngine(paintDoc());
+ engine.selectAll();
+ engine.fillSelection();
+ const exported = await engine.exportLayerPixels('paint1');
+ if (exported.status !== 'ok') {
+ throw new Error('expected published paint pixels');
+ }
+ const cleanupPreview = vi.fn();
+ engine.canvasOperations.start({
+ cleanupPreview,
+ guard: exported.guard,
+ identity: { kind: 'select-object', layerId: 'paint1', projectId: 'p1' },
+ });
+
+ engine.fillSelection();
+
+ expect(cleanupPreview).not.toHaveBeenCalled();
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'select-object' },
+ status: 'active',
+ });
+ engine.dispose();
+ });
+
+ it('cache clear cancels a guarded operation and cleans its preview', async () => {
const { engine } = makeEngine(paintDoc());
engine.selectAll();
engine.fillSelection();
@@ -11159,7 +11441,7 @@ describe('engine selection: fill / erase', () => {
identity: { kind: 'select-object', layerId: 'paint1', projectId: 'p1' },
});
- await mutate(engine);
+ await engine.clearCaches();
expect(cleanupPreview).toHaveBeenCalledOnce();
expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index ae9f653a24..a27c4a24e1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -591,6 +591,8 @@ export interface CanvasEngine {
* so they share the canvas undo stack with paint edits.
*/
commitStructural(label: string, forward: WorkbenchAction, inverse: WorkbenchAction): void;
+ /** Applies a guarded live structural preview without adding a history entry. */
+ applyStructuralPreview(action: WorkbenchAction): boolean;
/** Adds a contract-built layer while preserving the source layer's live cache pixels. */
commitLayerCopy(label: string, sourceLayerId: string, layer: CanvasLayerContract, index: number): boolean;
/** Converts the expected immutable live layer while preserving its cache pixels through undo/redo. */
@@ -1555,6 +1557,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
canvasOperations = createCanvasOperationController({ isGuardCurrent: isLayerExportGuardCurrent });
+ const documentEditOwner = Symbol('canvas-operation-document-edit-owner');
+ const syncDocumentEditingLock = (): void => {
+ stores.documentEditingLocked.set(canvasOperations.getSnapshot().status === 'active');
+ };
+ const unsubscribeDocumentEditingLock = canvasOperations.subscribe(syncDocumentEditingLock);
+ const canEditDocument = (owner?: symbol): boolean =>
+ owner === documentEditOwner || !stores.documentEditingLocked.get();
const ensureLayerCaches = (doc: CanvasDocumentContractV2): void => {
for (const layer of doc.layers) {
@@ -1727,7 +1736,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const cropLayerToBbox = async (layerId: string): Promise<CropLayerResult> => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return { status: 'busy' };
}
endNudgeBurst();
@@ -1857,6 +1866,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const copyLayerToRaster = async (layerId: string): Promise<string | null> => {
+ if (!canEditDocument()) {
+ return null;
+ }
if (pipeline.isGestureActive()) {
return null;
}
@@ -2964,7 +2976,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (signal?.aborted) {
throw new DOMException('Select Object upload was aborted.', 'AbortError');
}
- const uploaded = await uploadCanvasImage(blob, { isIntermediate: true });
+ const uploaded = await uploadCanvasImage(blob, { isIntermediate: true, signal });
if (signal?.aborted) {
throw new DOMException('Select Object upload was aborted.', 'AbortError');
}
@@ -3050,7 +3062,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
invalidateSelectObjectCommit();
return { status: 'stale' };
}
- const result = await replaceSelectionFromImage(preview.guard, preview.image, preview.rect, owner.controller.signal);
+ const result = await replaceSelectionFromImage(
+ preview.guard,
+ preview.image,
+ preview.rect,
+ owner.controller.signal,
+ documentEditOwner
+ );
if (!isSelectObjectCommitOwnerCurrent(owner)) {
return result;
}
@@ -3105,20 +3123,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
try {
result =
target === 'raster' || target === 'control'
- ? await commitGeneratedImageResult({
- guard: preview.guard,
- image: preview.image,
- origin: { x: preview.rect.x, y: preview.rect.y },
- signal: owner.controller.signal,
- target: target === 'raster' ? 'copy-raster' : 'copy-control',
- })
- : await commitMaskImageResult({
- guard: preview.guard,
- image: preview.image,
- rect: preview.rect,
- signal: owner.controller.signal,
- target,
- });
+ ? await commitGeneratedImageResult(
+ {
+ guard: preview.guard,
+ image: preview.image,
+ origin: { x: preview.rect.x, y: preview.rect.y },
+ signal: owner.controller.signal,
+ target: target === 'raster' ? 'copy-raster' : 'copy-control',
+ },
+ documentEditOwner
+ )
+ : await commitMaskImageResult(
+ {
+ guard: preview.guard,
+ image: preview.image,
+ rect: preview.rect,
+ signal: owner.controller.signal,
+ target,
+ },
+ documentEditOwner
+ );
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (finishSelectObjectCommit(owner)) {
@@ -3226,15 +3250,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
deps: {
clearPreview: () => clearFilterPreview(layer.id),
commit: ({ draft, guard, image, rect, signal, target }) =>
- commitRasterFilterResult({
- filter: draft,
- guard,
- image,
- mode: target === 'apply' ? 'replace' : 'copy',
- rect,
- signal,
- target,
- }),
+ commitRasterFilterResult(
+ {
+ filter: draft,
+ guard,
+ image,
+ mode: target === 'apply' ? 'replace' : 'copy',
+ rect,
+ signal,
+ target,
+ },
+ documentEditOwner
+ ),
controller: canvasOperations,
exportPixels: () => rasterizeLayerPixels(layer.id, { applyAdjustments: true, includeDisabled: true }),
isGuardCurrent: isLayerExportGuardCurrent,
@@ -3250,9 +3277,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
runUtilityGraph({ graph, hub: socketHub, outputNodeId, signal }));
return { imageName: output.imageName };
},
- uploadIntermediate: async (blob) => {
- const uploaded = await (queueDeps?.uploadIntermediate(blob) ??
- uploadCanvasImage(blob, { isIntermediate: true }));
+ uploadIntermediate: async (blob, signal) => {
+ const uploaded = await (queueDeps?.uploadIntermediate(blob, signal) ??
+ uploadCanvasImage(blob, { isIntermediate: true, signal }));
return { imageName: uploaded.imageName };
},
},
@@ -3708,7 +3735,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
layer: CanvasLayerContract,
index: number
): boolean => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return false;
}
endNudgeBurst();
@@ -3772,7 +3799,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
expectedLiveLayer: CanvasLayerContract,
after: CanvasLayerContract
): boolean => {
- if (pipeline.isGestureActive() || expectedLiveLayer.id !== after.id || expectedLiveLayer.type === after.type) {
+ if (
+ !canEditDocument() ||
+ pipeline.isGestureActive() ||
+ expectedLiveLayer.id !== after.id ||
+ expectedLiveLayer.type === after.type
+ ) {
return false;
}
endNudgeBurst();
@@ -3825,8 +3857,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
guard: LayerExportGuard,
image: CanvasImageRef,
rect: Rect,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ owner?: symbol
): Promise<ReplaceSelectionFromImageResult> => {
+ if (!canEditDocument(owner)) {
+ return { status: 'busy' };
+ }
if (signal?.aborted) {
return { status: 'aborted' };
}
@@ -3886,7 +3922,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
};
- const commitMaskImageResult = (options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult> => {
+ const commitMaskImageResult = (
+ options: CommitMaskImageResultOptions,
+ owner?: symbol
+ ): Promise<CommitMaskImageResult> => {
+ if (!canEditDocument(owner)) {
+ return Promise.resolve({ status: 'busy' });
+ }
if (options.signal?.aborted) {
return Promise.resolve({ status: 'aborted' });
}
@@ -3972,7 +4014,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return Promise.resolve({ layerId, status: 'committed' });
};
- const commitRasterFilterResult = async (options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult> => {
+ const commitRasterFilterResult = async (
+ options: CommitRasterFilterOptions,
+ owner?: symbol
+ ): Promise<CommitRasterFilterResult> => {
+ if (!canEditDocument(owner)) {
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
return { status: 'aborted' };
}
@@ -4178,8 +4226,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const commitGeneratedImageResult = async (
- options: CommitGeneratedImageOptions
+ options: CommitGeneratedImageOptions,
+ owner?: symbol
): Promise<CommitGeneratedImageResult> => {
+ if (!canEditDocument(owner)) {
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
return { status: 'aborted' };
}
@@ -4410,7 +4462,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
upperLayerId: string,
operation: BooleanRasterOperation
): Promise<BooleanRasterResult> => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return 'busy';
}
endNudgeBurst();
@@ -4579,7 +4631,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const extractMaskedArea = async (maskLayerId: string): Promise<ExtractMaskedAreaResult> => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return { status: 'busy' };
}
endNudgeBurst();
@@ -4748,7 +4800,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// pixels and dispatches a structural collapse under the open stroke session.
// Matches the commitStructural/nudge guards; this op is not undoable, so the
// guard is doubly important. The pipeline reports gesture state.
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return false;
}
endNudgeBurst();
@@ -4877,6 +4929,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const MAX_MERGE_VISIBLE_STEPS = 256;
const mergeVisibleRasterLayers = (): MergeVisibleResult => {
+ if (!canEditDocument()) {
+ return 'nothing';
+ }
// Mirrors the mergeLayerDown guard: no pixel work under an open gesture.
if (pipeline.isGestureActive()) {
return 'nothing';
@@ -5040,7 +5095,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
* source.
*/
const rasterizeLayer = (layerId: string): boolean => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return false;
}
endNudgeBurst();
@@ -5160,8 +5215,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// entry inside the gesture. The move/bbox tools commit on pointer-UP, by
// which point the pipeline has already cleared the gesture flag (it is reset
// before the active tool's `onPointerUp` runs), so their commits still land.
- const operation = canvasOperations.getSnapshot();
- if (pipeline.isGestureActive() || (operation.status === 'active' && operation.identity.kind === 'filter')) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return;
}
endNudgeBurst();
@@ -5176,6 +5230,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
);
};
+ const applyStructuralPreview = (action: WorkbenchAction): boolean => {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
+ return false;
+ }
+ store.dispatch(action);
+ return true;
+ };
+
/**
* Nudges the selected layer by `(dx, dy)` document pixels as a structural,
* undoable edit. A no-op with no selection or a locked/hidden selected layer.
@@ -5188,7 +5250,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// structural transform under the open stroke session (feeding the cache-wipe
// path) and interleave a history entry inside the gesture. The pipeline
// reports gesture state; while a stroke is in progress this is a no-op.
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return;
}
const doc = mirror.getDocument();
@@ -5318,6 +5380,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
});
const applyTransform = (): void => {
+ if (!canEditDocument()) {
+ return;
+ }
// No-op mid-gesture (guarded like commitStructural/merge): apply writes a
// structural transform (and, for paint, pixels) that must not interleave with
// an open pointer session. Apply lands on Enter/button, after pointer-up.
@@ -5566,6 +5631,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const commitTextEdit = (content: string, styleChanges?: Partial<TextToolOptions>): void => {
+ if (!canEditDocument()) {
+ return;
+ }
// Defensive mid-gesture guard (commit is React-driven on blur/mod+enter, so
// this normally never fires mid-stroke): a structural dispatch must not
// interleave with an open pointer session. Mirrors commitStructural's guard.
@@ -5641,6 +5709,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
* clears the session, and the portal's `onBlur` re-commit then no-ops.
*/
const commitOpenTextSession = (): boolean => {
+ if (!canEditDocument()) {
+ return false;
+ }
const session = stores.textEditSession.get();
if (!session) {
return false;
@@ -5717,6 +5788,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
* (= document space for identity paint layers).
*/
const runMaskedSelectionEdit = (kind: 'fill' | 'erase'): void => {
+ if (!canEditDocument()) {
+ return;
+ }
if (pipeline.isGestureActive()) {
return;
}
@@ -5805,7 +5879,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
/** Clears a mask's live pixels and persisted bitmap while retaining prompts, fill, and modifiers. */
const clearMask = (layerId: string): boolean => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return false;
}
const doc = mirror.getDocument();
@@ -5876,7 +5950,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
* a mask, or locked/hidden. Returns whether it ran.
*/
const invertMask = (layerId: string): boolean => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return false;
}
const doc = mirror.getDocument();
@@ -5964,7 +6038,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// Drop any open text-edit session (its layer belongs to a document this
// engine no longer serves).
stores.textEditSession.set(null);
- // Drop any control-filter previews outright — the engine is going away, so
+ // Drop any guarded filter previews outright — the engine is going away, so
// there's no render loop left to invalidate for them.
filterPreviews.clear();
filterPreviewTokens.clear();
@@ -5984,6 +6058,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
unsubscribeRuleOfThirds();
unsubscribeHistory();
unsubscribeProjectPreviewLifecycle();
+ unsubscribeDocumentEditingLock();
history.clear();
bitmapStore.dispose();
mirror.dispose();
@@ -6070,6 +6145,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
return {
+ applyStructuralPreview,
applyTransform,
booleanMergeRasterLayers,
canvasOperations,
@@ -6149,7 +6225,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// state; while a stroke is in progress these are no-ops.
nudgeSelectedLayer,
redo: () => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return;
}
endNudgeBurst();
@@ -6164,7 +6240,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
stepBrushSize: stepActiveBrushSize,
stores,
undo: () => {
- if (pipeline.isGestureActive()) {
+ if (!canEditDocument() || pipeline.isGestureActive()) {
return;
}
endNudgeBurst();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index b796722d08..5ef871a30c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -535,6 +535,8 @@ export interface EngineStores {
samSession: ScalarStore<SamSessionSnapshot | null>;
/** Active guarded layer-filter session state, independent of any launching view. */
filterSession: ScalarStore<FilterOperationSessionState | null>;
+ /** Whether an engine-owned operation currently excludes ordinary document edits. */
+ documentEditingLocked: ScalarStore<boolean>;
}
const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>
@@ -650,6 +652,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
checkerColors: createScalarStore<CheckerColors>({ ...DEFAULT_CHECKER_COLORS }, checkerColorsEqual),
cursor: createScalarStore<string>('default'),
eraserOptions: createScalarStore<EraserOptions>({ ...DEFAULT_ERASER_OPTIONS }, eraserOptionsEqual),
+ documentEditingLocked: createScalarStore<boolean>(false),
filterSession: createScalarStore<FilterOperationSessionState | null>(null),
hasSelection: createScalarStore<boolean>(false),
invertBrushSizeScroll: createScalarStore<boolean>(false),
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.ts
index e9f1db3dc0..78f65f6aef 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
@@ -218,6 +218,30 @@ describe('compositeDocument', () => {
expect(findSet(target.callLog, 'globalCompositeOperation')).toContain('multiply');
});
+ it('applies control transparency, opacity, and blend mode to a filter preview', () => {
+ const backend = createTestStubRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ caches.getOrCreate('control', 10, 10);
+ const preview = backend.createSurface(10, 10);
+ const target = backend.createSurface(100, 100);
+ const layer = {
+ ...controlLayer('control'),
+ blendMode: 'multiply' as const,
+ opacity: 0.4,
+ withTransparencyEffect: true,
+ };
+
+ compositeDocument(target, makeDoc([layer]), caches, VIEW, {
+ backend,
+ layerPreviews: new Map([['control', preview]]),
+ });
+
+ const draw = target.callLog.find((entry) => entry.op === 'drawImage');
+ expect(draw?.args[0]).not.toBe(preview.canvas);
+ expect(findSet(target.callLog, 'globalAlpha')).toContain(0.4);
+ expect(findSet(target.callLog, 'globalCompositeOperation')).toContain('multiply');
+ });
+
it("maps the 'normal' blend mode to 'source-over'", () => {
const backend = createTestStubRasterBackend();
const caches = createLayerCacheStore(backend);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index b540f4b085..afc9a76b23 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -282,8 +282,13 @@ const drawCachedLayer = (
const preview = opts.onlyLayerId ? null : (opts.layerPreviews?.get(layer.id) ?? null);
if (preview) {
// Non-destructive filter preview: stretch the filtered image over the layer's
- // content footprint (through the already-applied layer transform).
- ctx.drawImage(preview.canvas, origin.x, origin.y, entry.rect.width, entry.rect.height);
+ // content footprint (through the already-applied layer transform), including
+ // the same display-only control transparency effect used after commit.
+ const displayPreview =
+ layer.type === 'control' && layer.withTransparencyEffect && opts.backend
+ ? renderControlTransparency(opts.backend, preview, preview.width, preview.height)
+ : preview;
+ ctx.drawImage(displayPreview.canvas, origin.x, origin.y, entry.rect.width, entry.rect.height);
} else if (isMaskLayer(layer)) {
drawMaskLayer(ctx, layer, entry.surface, origin, opts);
} else if (layer.type === 'control' && layer.withTransparencyEffect && opts.backend) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index a6be453a01..17df03f051 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -36,7 +36,7 @@ import {
canvasSettingsEqual,
resolveCanvasSettings,
} from './canvasSettings';
-import { useCanvasCanRedo, useCanvasCanUndo, useCanvasZoom } from './engineStoreHooks';
+import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';
import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';
import { useCanvasEngine } from './useCanvasEngine';
import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';
@@ -81,13 +81,18 @@ const CanvasHeaderActionsInner = ({
const zoom = useCanvasZoom(engine);
const canUndo = useCanvasCanUndo(engine);
const canRedo = useCanvasCanRedo(engine);
+ const editingLocked = useCanvasDocumentEditingLocked(engine);
const document = useActiveProjectSelector((project) => project.canvas.document);
const modelBase = useActiveProjectSelector(selectModelBase);
const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
const [isNewCanvasOpen, setIsNewCanvasOpen] = useState(false);
const closeNewCanvas = useCallback(() => setIsNewCanvasOpen(false), []);
- const openNewCanvas = useCallback(() => setIsNewCanvasOpen(true), []);
+ const openNewCanvas = useCallback(() => {
+ if (!editingLocked) {
+ setIsNewCanvasOpen(true);
+ }
+ }, [editingLocked]);
const setZoom = (value: number) => {
const viewport = engine.getViewport();
@@ -104,7 +109,7 @@ const CanvasHeaderActionsInner = ({
// manual bbox-tool edit commits. `refit` re-centers the view afterward (legacy
// re-fits the stage after fit-to-layers, but not after fit-to-masks).
const applyFit = (rect: Rect | null, refit: boolean) => {
- if (!rect) {
+ if (editingLocked || !rect) {
return;
}
engine.commitStructural(
@@ -118,6 +123,9 @@ const CanvasHeaderActionsInner = ({
};
const confirmNewCanvas = useCallback(() => {
+ if (editingLocked) {
+ return;
+ }
// A wholesale document replace (seeded with one empty inpaint mask, matching
// Task 42's new-canvas init) at the current dimensions. The engine's mirror
// treats this as a document swap and clears the canvas history by design, so
@@ -126,7 +134,7 @@ const CanvasHeaderActionsInner = ({
document: createNewCanvasStateV2(document.width, document.height).document,
type: 'replaceCanvasDocument',
});
- }, [dispatch, document.height, document.width]);
+ }, [dispatch, document.height, document.width, editingLocked]);
// Commands (hotkey-assignable; catalog ids `canvas.fitBboxToLayers` /
// `canvas.fitBboxToMasks` / `canvas.newSession`). `useEffectEvent` reads the
@@ -193,7 +201,7 @@ const CanvasHeaderActionsInner = ({
<Tooltip content={t('widgets.canvas.controls.fitBboxToLayers')}>
<IconButton
color="fg.muted"
- disabled={!fitLayersRect}
+ disabled={editingLocked || !fitLayersRect}
size="2xs"
variant="ghost"
onClick={() => applyFit(fitLayersRect, true)}
@@ -205,7 +213,7 @@ const CanvasHeaderActionsInner = ({
<Tooltip content={t('widgets.canvas.controls.fitBboxToMasks')}>
<IconButton
color="fg.muted"
- disabled={!fitMasksRect}
+ disabled={editingLocked || !fitMasksRect}
size="2xs"
variant="ghost"
onClick={() => applyFit(fitMasksRect, false)}
@@ -217,13 +225,25 @@ const CanvasHeaderActionsInner = ({
<HeaderDivider />
<Tooltip content={t('widgets.canvas.commands.undo')}>
- <IconButton color="fg.muted" disabled={!canUndo} size="2xs" variant="ghost" onClick={() => engine.undo()}>
+ <IconButton
+ color="fg.muted"
+ disabled={editingLocked || !canUndo}
+ size="2xs"
+ variant="ghost"
+ onClick={() => engine.undo()}
+ >
<Undo2Icon />
</IconButton>
</Tooltip>
<Tooltip content={t('widgets.canvas.commands.redo')}>
- <IconButton color="fg.muted" disabled={!canRedo} size="2xs" variant="ghost" onClick={() => engine.redo()}>
+ <IconButton
+ color="fg.muted"
+ disabled={editingLocked || !canRedo}
+ size="2xs"
+ variant="ghost"
+ onClick={() => engine.redo()}
+ >
<Redo2Icon />
</IconButton>
</Tooltip>
@@ -235,6 +255,7 @@ const CanvasHeaderActionsInner = ({
<IconButton
aria-label={t('widgets.canvas.controls.newSession')}
color="fg.muted"
+ disabled={editingLocked}
size="2xs"
variant="ghost"
>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index e7e0c8b9ab..91b90cde07 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -93,6 +93,16 @@ export const useCanvasCanUndo = (engine: CanvasEngine): boolean => useScalarStor
/** Whether the engine-owned canvas history has an entry to redo (enables the header redo button). */
export const useCanvasCanRedo = (engine: CanvasEngine): boolean => useScalarStore(engine.stores.canRedo);
+/** Whether a SAM/filter operation currently excludes ordinary canvas document edits. */
+export const useCanvasDocumentEditingLocked = (engine: CanvasEngine | null): boolean => {
+ const subscribe = useCallback(
+ (listener: () => void) => engine?.stores.documentEditingLocked.subscribe(listener) ?? (() => undefined),
+ [engine]
+ );
+ const getSnapshot = useCallback(() => engine?.stores.documentEditingLocked.get() ?? false, [engine]);
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+};
+
/**
* The brush tool's current options (size / color / opacity / pressure). Write
* through `engine.stores.brushOptions.set(...)` directly — there is no reducer
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
index 7fb038bdcc..0c9fb2abf8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx
@@ -18,7 +18,7 @@ import {
finishCurveDragResult,
getCurveGridCoordinates,
} from './curveEditorMath';
-import { applyStructural } from './layerOps';
+import { applyStructural, applyStructuralPreview } from './layerOps';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
@@ -84,13 +84,13 @@ const AdjustmentsControls = ({ adjustments, engine, layer }: AdjustmentsControls
const patchLive = useCallback(
(next: CanvasAdjustmentsContract) => {
- dispatch({
+ applyStructuralPreview(engine, dispatch, {
config: { adjustments: next, layerType: 'raster' },
id: layer.id,
type: 'updateCanvasLayerConfig',
});
},
- [dispatch, layer.id]
+ [dispatch, engine, layer.id]
);
const commit = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index 4bbca21491..2b1f19055d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -12,7 +12,7 @@ import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/Workb
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructural } from './layerOps';
+import { applyStructural, applyStructuralPreview } from './layerOps';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
@@ -139,16 +139,20 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
if (next === undefined || !Number.isFinite(next)) {
return;
}
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: { adapter: { weight: next }, layerType: 'control' },
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (weightBeforeRef.current === null) {
weightBeforeRef.current = adapter.weight;
}
- dispatch({
- config: { adapter: { weight: next }, layerType: 'control' },
- id: layer.id,
- type: 'updateCanvasLayerConfig',
- });
},
- [adapter.weight, dispatch, layer.id]
+ [adapter.weight, dispatch, engine, layer.id]
);
const handleWeightChangeEnd = useCallback(
({ value }: SliderValueChangeDetails) => {
@@ -169,16 +173,20 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
if (value.length !== 2) {
return;
}
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: { adapter: { beginEndStepPct: [value[0]!, value[1]!] }, layerType: 'control' },
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (rangeBeforeRef.current === null) {
rangeBeforeRef.current = adapter.beginEndStepPct;
}
- dispatch({
- config: { adapter: { beginEndStepPct: [value[0]!, value[1]!] }, layerType: 'control' },
- id: layer.id,
- type: 'updateCanvasLayerConfig',
- });
},
- [adapter.beginEndStepPct, dispatch, layer.id]
+ [adapter.beginEndStepPct, dispatch, engine, layer.id]
);
const handleRangeChangeEnd = useCallback(
({ value }: SliderValueChangeDetails) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
index cae302d873..6459dc2a46 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
@@ -8,7 +8,7 @@ import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructural } from './layerOps';
+import { applyStructural, applyStructuralPreview } from './layerOps';
/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */
const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
@@ -76,17 +76,20 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)
const handleColorChange = useCallback(
(hex: string) => {
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fill, color: hex } } },
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (fillBeforeRef.current === null) {
fillBeforeRef.current = fill;
}
- // Live, un-recorded update during the drag (mirrors the opacity slider).
- dispatch({
- config: { layerType: 'inpaint_mask', mask: { fill: { ...fill, color: hex } } },
- id: layer.id,
- type: 'updateCanvasLayerConfig',
- });
},
- [dispatch, fill, layer.id]
+ [dispatch, engine, fill, layer.id]
);
const handleColorChangeEnd = useCallback(
@@ -114,12 +117,20 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)
if (next === undefined || !Number.isFinite(next)) {
return;
}
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: noiseConfig(next),
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (noiseBeforeRef.current === null) {
noiseBeforeRef.current = noiseLevel;
}
- dispatch({ config: noiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' });
},
- [dispatch, layer.id, noiseLevel]
+ [dispatch, engine, layer.id, noiseLevel]
);
const handleNoiseChangeEnd = useCallback(
@@ -147,12 +158,20 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)
if (next === undefined || !Number.isFinite(next)) {
return;
}
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: denoiseConfig(next),
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (denoiseBeforeRef.current === null) {
denoiseBeforeRef.current = denoiseLimit;
}
- dispatch({ config: denoiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' });
},
- [dispatch, denoiseLimit, layer.id]
+ [dispatch, denoiseLimit, engine, layer.id]
);
const handleDenoiseChangeEnd = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 451d59beba..5df161734f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -13,7 +13,7 @@ import { uploadGalleryImage } from '@workbench/gallery/api';
import { useModelsSelector } from '@workbench/models/modelsStore';
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
-import { useCanvasOperation, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import {
@@ -190,15 +190,13 @@ const LayerMenu = ({
const canvas = useActiveProjectSelector((project) => project.canvas);
const queueItems = useActiveProjectSelector((project) => project.queue.items);
const { document } = canvas;
- const canvasOperation = useCanvasOperation(engine);
const { bbox } = document;
const documentRect = useMemo(
() => ({ height: document.height, width: document.width, x: 0, y: 0 }),
[document.height, document.width]
);
- const interactionLocked =
- isCanvasInteractionLocked(canvas, queueItems) ||
- (canvasOperation.status === 'active' && canvasOperation.identity.kind === 'filter');
+ const documentEditingLocked = useCanvasDocumentEditingLocked(engine);
+ const interactionLocked = isCanvasInteractionLocked(canvas, queueItems) || documentEditingLocked;
// Re-render when live, not-yet-persisted paint/mask pixels change.
useLayerThumbnailVersion(engine, layer.id);
const hasSupportedContent = engine
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
index 178860ce1d..b175a80df5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
@@ -11,6 +11,7 @@ import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifi
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { canMergeVisibleRasters } from '@workbench/canvas-engine/document/mergeVisible';
import { IconButton, toaster, Tooltip } from '@workbench/components/ui';
+import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
import { useActiveProjectName } from '@workbench/WorkbenchContext';
import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -58,6 +59,7 @@ export const LayerGroupSection = ({
selectedLayerId,
}: LayerGroupSectionProps) => {
const { t } = useTranslation();
+ const editingLocked = useCanvasDocumentEditingLocked(engine);
const sensors = useSensors(useSensor(PointerSensor, POINTER_SENSOR_OPTIONS));
@@ -71,6 +73,9 @@ export const LayerGroupSection = ({
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
+ if (editingLocked) {
+ return;
+ }
const { active, over } = event;
if (!over) {
return;
@@ -87,7 +92,7 @@ export const LayerGroupSection = ({
{ orderedIds: layers.map((layer) => layer.id), type: 'reorderCanvasLayers' }
);
},
- [dispatch, engine, layers, t]
+ [dispatch, editingLocked, engine, layers, t]
);
const handleToggleCollapse = useCallback(() => onToggleCollapse(groupKey), [groupKey, onToggleCollapse]);
@@ -126,6 +131,7 @@ export const LayerGroupSection = ({
<GroupActions
dispatch={dispatch}
engine={engine}
+ editingLocked={editingLocked}
groupKey={groupKey}
groupLayers={groupLayers}
layers={layers}
@@ -171,12 +177,14 @@ export const LayerGroupSection = ({
*/
const GroupActions = ({
dispatch,
+ editingLocked,
engine,
groupKey,
groupLayers,
layers,
}: {
dispatch: Dispatch<WorkbenchAction>;
+ editingLocked: boolean;
engine: CanvasEngine | null;
groupKey: LayerGroupKey;
groupLayers: readonly CanvasLayerContract[];
@@ -189,7 +197,7 @@ const GroupActions = ({
// Enablement uses the SAME planner the engine op executes (`planMergeVisibleRuns`
// over the GLOBAL array — run-splitting depends on interleaved non-participants),
// so the button is enabled exactly when clicking it will merge something.
- const canMerge = !!engine && groupKey === 'raster' && canMergeVisibleRasters(layers);
+ const canMerge = !editingLocked && !!engine && groupKey === 'raster' && canMergeVisibleRasters(layers);
const canExport = !!engine && groupKey === 'raster' && canExportRasterPsd(layers);
const handleNew = useCallback(() => addLayer(groupAddItemId(groupKey)), [addLayer, groupKey]);
@@ -254,7 +262,7 @@ const GroupActions = ({
return (
<GroupActionButton
key={action}
- disabled={!canExport}
+ disabled={editingLocked || !canExport}
icon={FileDownIcon}
label={t('widgets.layers.groupActions.exportPsd')}
onClick={handleExportPsd}
@@ -264,6 +272,7 @@ const GroupActions = ({
return (
<GroupActionButton
key={action}
+ disabled={editingLocked}
icon={allVisible ? EyeIcon : EyeOffIcon}
label={t(allVisible ? 'widgets.layers.groupActions.hideAll' : 'widgets.layers.groupActions.showAll')}
onClick={handleToggleVisibility}
@@ -273,6 +282,7 @@ const GroupActions = ({
return (
<GroupActionButton
key={action}
+ disabled={editingLocked}
icon={PlusIcon}
label={t('widgets.layers.groupActions.new')}
onClick={handleNew}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx
index 3bb4b1f3e5..760ebafda4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx
@@ -5,7 +5,7 @@ import type { Dispatch } from 'react';
import { Popover, Portal, Stack, Switch, Text } from '@chakra-ui/react';
import { IconButton } from '@workbench/components/ui';
-import { useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { SlidersHorizontalIcon } from 'lucide-react';
import { useCallback, useState } from 'react';
@@ -48,8 +48,7 @@ export const LayerPropertiesPopover = ({ dispatch, engine, layer }: LayerPropert
const [triggerOpen, setTriggerOpen] = useState(false);
const request = useLayerPropertiesRequest(layer.id);
const documentRevision = useActiveProjectSelector((project) => project.canvas.documentRevision);
- const operation = useCanvasOperation(engine);
- const isFilterActive = operation.status === 'active' && operation.identity.kind === 'filter';
+ const editingLocked = useCanvasDocumentEditingLocked(engine);
const isOpen = triggerOpen || request !== null;
const handleOpenChange = useCallback(
@@ -74,7 +73,7 @@ export const LayerPropertiesPopover = ({ dispatch, engine, layer }: LayerPropert
<IconButton
aria-label={t('widgets.layers.properties')}
color="fg.subtle"
- disabled={isFilterActive}
+ disabled={editingLocked}
size="2xs"
variant="ghost"
onClick={stopPropagation}
@@ -87,7 +86,7 @@ export const LayerPropertiesPopover = ({ dispatch, engine, layer }: LayerPropert
<Popover.Positioner>
<Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="20rem">
<Popover.Body p="2.5">
- <Stack gap="2">
+ <Stack gap="2" inert={editingLocked}>
<LayerTypeSettings
dispatch={dispatch}
documentRevision={documentRevision}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.test.ts
index 6ec3e0f803..1dcecdff19 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { createEmptyPaintLayer } from './layerOps';
-import { isSameSelection } from './LayersPanelHeader';
+import { isLayerEditingDisabled, isSameSelection } from './LayersPanelHeader';
describe('LayersPanelHeader selection equality', () => {
it('invalidates the selected-layer view when blend mode changes', () => {
@@ -11,3 +11,12 @@ describe('LayersPanelHeader selection equality', () => {
expect(isSameSelection(normal, multiply)).toBe(false);
});
});
+
+describe('LayersPanelHeader editing state', () => {
+ it('disables layer controls without a selection or while engine editing is locked', () => {
+ const layer = createEmptyPaintLayer('Layer', 'layer');
+ expect(isLayerEditingDisabled(null, false)).toBe(true);
+ expect(isLayerEditingDisabled(layer, true)).toBe(true);
+ expect(isLayerEditingDisabled(layer, false)).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
index 24439226d0..456ba5f6d6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
@@ -10,6 +10,7 @@ import type { Dispatch } from 'react';
import { Box, createListCollection, Flex, HStack, NumberInput, Stack } from '@chakra-ui/react';
import { ColorPicker, Field, Select, Slider } from '@workbench/components/ui';
+import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
import {
CANVAS_DENOISING_STRENGTH_KEY,
clampCanvasDenoisingStrength,
@@ -26,7 +27,7 @@ import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { DenoisingStrengthWave } from './DenoisingStrengthWave';
-import { applyStructural, CANVAS_BLEND_MODES } from './layerOps';
+import { applyStructural, applyStructuralPreview, CANVAS_BLEND_MODES } from './layerOps';
const STRENGTH_DEBOUNCE_MS = 250;
const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;
@@ -56,6 +57,9 @@ export const isSameSelection = (left: CanvasLayerContract | null, right: CanvasL
return leftFill === rightFill;
};
+export const isLayerEditingDisabled = (layer: CanvasLayerContract | null, editingLocked: boolean): boolean =>
+ !layer || editingLocked;
+
/**
* The slimmed Photoshop-style region above the layer groups (round 3): exactly two
* rows — the global canvas denoising-strength slider + a per-selection Opacity row
@@ -67,6 +71,7 @@ export const LayersPanelHeader = () => {
const engine = useCanvasEngine();
const dispatch = useWorkbenchDispatch();
const layer = useActiveProjectSelector(selectSelectedLayer, isSameSelection);
+ const editingLocked = useCanvasDocumentEditingLocked(engine);
return (
<Stack gap="0">
@@ -75,8 +80,8 @@ export const LayersPanelHeader = () => {
</Box>
<Box borderBottomWidth={1} px="1.5" py="1">
<Flex align="center" gap="2">
- <BlendModeControl dispatch={dispatch} engine={engine} layer={layer} />
- <OpacityRow dispatch={dispatch} engine={engine} layer={layer} />
+ <BlendModeControl dispatch={dispatch} editingLocked={editingLocked} engine={engine} layer={layer} />
+ <OpacityRow dispatch={dispatch} editingLocked={editingLocked} engine={engine} layer={layer} />
</Flex>
</Box>
</Stack>
@@ -90,15 +95,17 @@ interface BlendModeOption {
const BlendModeControl = ({
dispatch,
+ editingLocked,
engine,
layer,
}: {
dispatch: Dispatch<WorkbenchAction>;
+ editingLocked: boolean;
engine: CanvasEngine | null;
layer: CanvasLayerContract | null;
}) => {
const { t } = useTranslation();
- const disabled = !layer;
+ const disabled = isLayerEditingDisabled(layer, editingLocked);
const blendMode = layer?.blendMode ?? 'normal';
const blendCollection = useMemo(
() =>
@@ -146,10 +153,12 @@ const BlendModeControl = ({
const OpacityRow = ({
dispatch,
+ editingLocked,
engine,
layer,
}: {
dispatch: Dispatch<WorkbenchAction>;
+ editingLocked: boolean;
engine: CanvasEngine | null;
layer: CanvasLayerContract | null;
}) => {
@@ -160,7 +169,7 @@ const OpacityRow = ({
// trigger (both can fire inside one browser event), so `layer.opacity` from the
// render closure can be stale at commit time.
const pendingRef = useRef<{ id: string; before: number; latest: number } | null>(null);
- const disabled = !layer;
+ const disabled = isLayerEditingDisabled(layer, editingLocked);
const opacityPercent = useMemo(() => String(Math.round((layer?.opacity ?? 1) * 100)), [layer?.opacity]);
// Records ONE history entry spanning the pending gesture (a spinner press,
@@ -191,15 +200,22 @@ const OpacityRow = ({
commitPending();
}
const next = clamp01(valueAsNumber / 100);
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ id: layer.id,
+ patch: { opacity: next },
+ type: 'updateCanvasLayer',
+ })
+ ) {
+ return;
+ }
if (pendingRef.current === null) {
pendingRef.current = { before: layer.opacity, id: layer.id, latest: next };
} else {
pendingRef.current.latest = next;
}
- // Live, un-recorded update (mirrors the old opacity slider's drag phase).
- dispatch({ id: layer.id, patch: { opacity: next }, type: 'updateCanvasLayer' });
},
- [commitPending, dispatch, layer]
+ [commitPending, dispatch, engine, layer]
);
// Commit per completed interaction: each spinner click (fires on release, so a
@@ -246,7 +262,9 @@ const OpacityRow = ({
onKeyUp={handleInputKeyUp}
/>
</NumberInput.Root>
- {isMaskLayer(layer) ? <MaskFillSwatch dispatch={dispatch} engine={engine} layer={layer} /> : null}
+ {isMaskLayer(layer) ? (
+ <MaskFillSwatch disabled={editingLocked} dispatch={dispatch} engine={engine} layer={layer} />
+ ) : null}
</HStack>
</Field>
);
@@ -259,10 +277,12 @@ const OpacityRow = ({
*/
const MaskFillSwatch = ({
dispatch,
+ disabled,
engine,
layer,
}: {
dispatch: Dispatch<WorkbenchAction>;
+ disabled: boolean;
engine: CanvasEngine | null;
layer: MaskLayer;
}) => {
@@ -271,19 +291,15 @@ const MaskFillSwatch = ({
const fill = layer.mask.fill;
const patchFill = useCallback(
- (next: CanvasMaskFillContract, record: boolean, before?: CanvasMaskFillContract) => {
+ (next: CanvasMaskFillContract, before: CanvasMaskFillContract) => {
const config =
layer.type === 'inpaint_mask'
? ({ layerType: 'inpaint_mask', mask: { fill: next } } as const)
: ({ layerType: 'regional_guidance', mask: { fill: next } } as const);
- if (!record) {
- dispatch({ config, id: layer.id, type: 'updateCanvasLayerConfig' });
- return;
- }
const inverseConfig =
layer.type === 'inpaint_mask'
- ? ({ layerType: 'inpaint_mask', mask: { fill: before ?? next } } as const)
- : ({ layerType: 'regional_guidance', mask: { fill: before ?? next } } as const);
+ ? ({ layerType: 'inpaint_mask', mask: { fill: before } } as const)
+ : ({ layerType: 'regional_guidance', mask: { fill: before } } as const);
applyStructural(
engine,
dispatch,
@@ -297,30 +313,39 @@ const MaskFillSwatch = ({
const handleColorChange = useCallback(
(hex: string) => {
+ const next = { ...fill, color: hex };
+ const config =
+ layer.type === 'inpaint_mask'
+ ? ({ layerType: 'inpaint_mask', mask: { fill: next } } as const)
+ : ({ layerType: 'regional_guidance', mask: { fill: next } } as const);
+ if (!applyStructuralPreview(engine, dispatch, { config, id: layer.id, type: 'updateCanvasLayerConfig' })) {
+ return;
+ }
if (fillBeforeRef.current === null) {
fillBeforeRef.current = fill;
}
- patchFill({ ...fill, color: hex }, false);
},
- [fill, patchFill]
+ [dispatch, engine, fill, layer.id, layer.type]
);
const handleColorChangeEnd = useCallback(
(hex: string) => {
const before = fillBeforeRef.current ?? fill;
fillBeforeRef.current = null;
- patchFill({ ...before, color: hex }, true, before);
+ patchFill({ ...before, color: hex }, before);
},
[fill, patchFill]
);
return (
- <ColorPicker
- aria-label={t('widgets.layers.maskFill.color')}
- value={fill.color}
- onValueChange={handleColorChange}
- onValueChangeEnd={handleColorChangeEnd}
- />
+ <Box aria-disabled={disabled} inert={disabled} opacity={disabled ? 0.5 : 1}>
+ <ColorPicker
+ aria-label={t('widgets.layers.maskFill.color')}
+ value={fill.color}
+ onValueChange={handleColorChange}
+ onValueChangeEnd={handleColorChangeEnd}
+ />
+ </Box>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index 5f0e520a66..9d106e324b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -20,7 +20,7 @@ import { ImageIcon, PlusIcon, XIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructural, createRegionalReferenceImage } from './layerOps';
+import { applyStructural, applyStructuralPreview, createRegionalReferenceImage } from './layerOps';
/** The regional-guidance fields patchable via `updateCanvasLayerConfig`. */
interface RegionalConfigPatch {
@@ -193,16 +193,20 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
const handleColorChange = useCallback(
(hex: string) => {
+ if (
+ !applyStructuralPreview(engine, dispatch, {
+ config: { layerType: 'regional_guidance', mask: { fill: { ...fill, color: hex } } },
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
if (fillBeforeRef.current === null) {
fillBeforeRef.current = fill;
}
- dispatch({
- config: { layerType: 'regional_guidance', mask: { fill: { ...fill, color: hex } } },
- id: layer.id,
- type: 'updateCanvasLayerConfig',
- });
},
- [dispatch, fill, layer.id]
+ [dispatch, engine, fill, layer.id]
);
const handleColorChangeEnd = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.test.ts
index f168bfc34c..723739aa4e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.test.ts
@@ -29,8 +29,9 @@ describe('runLayerFilter', () => {
expect(receivedSignal).toBe(signal);
return Promise.resolve({ imageName: 'output' });
},
- uploadIntermediate: (receivedBlob) => {
+ uploadIntermediate: (receivedBlob, receivedSignal) => {
expect(receivedBlob).toBe(blob);
+ expect(receivedSignal).toBe(signal);
calls.push('upload');
return Promise.resolve({ imageName: 'input' });
},
@@ -109,6 +110,35 @@ describe('runLayerFilter', () => {
expect(calls).toEqual(['encode', 'upload']);
});
+ it('forwards cancellation into an in-flight upload', async () => {
+ const controller = new AbortController();
+ let uploadSignal: AbortSignal | undefined;
+
+ const pending = runLayerFilter({
+ deps: {
+ encodeSurface: () => Promise.resolve(new Blob()),
+ runFilterGraph: () => Promise.resolve({ imageName: 'output' }),
+ uploadIntermediate: (_blob, signal) => {
+ uploadSignal = signal;
+ return new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
+ });
+ },
+ },
+ filterType: 'canny_edge_detection',
+ input: {
+ rect: { height: 1, width: 1, x: 0, y: 0 },
+ surface: createTestStubRasterBackend().createSurface(1, 1),
+ },
+ signal: controller.signal,
+ });
+ await Promise.resolve();
+ controller.abort();
+
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ expect(uploadSignal).toBe(controller.signal);
+ });
+
it('propagates a filter graph failure', async () => {
const graphError = new Error('graph failed');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.ts
index 805d742609..e1cbab7d87 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerFilterRunner.ts
@@ -18,7 +18,7 @@ export interface RunLayerFilterOptions {
signal?: AbortSignal;
deps: {
encodeSurface(surface: RasterSurface): Promise<Blob>;
- uploadIntermediate(blob: Blob): Promise<{ imageName: string }>;
+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
runFilterGraph(options: {
graph: BackendGraphContract;
outputNodeId: string;
@@ -37,7 +37,7 @@ export const runLayerFilter = async (options: RunLayerFilterOptions): Promise<La
throwIfAborted(options.signal);
const blob = await options.deps.encodeSurface(options.input.surface);
throwIfAborted(options.signal);
- const uploaded = await options.deps.uploadIntermediate(blob);
+ const uploaded = await options.deps.uploadIntermediate(blob, options.signal);
throwIfAborted(options.signal);
const built = buildFilterGraph(options.filterType, uploaded.imageName, options.settings);
const output = await options.deps.runFilterGraph({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
index 2f885be5a8..e57cfa213d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
@@ -5,6 +5,7 @@ import type { WorkbenchAction } from '@workbench/workbenchState';
import { describe, expect, it, vi } from 'vitest';
import {
+ applyStructuralPreview,
applyStructural,
canConvertRasterControl,
canMergeLayerDown,
@@ -193,6 +194,20 @@ describe('applyStructural', () => {
});
});
+describe('applyStructuralPreview', () => {
+ it('routes a live document edit through the engine guard', () => {
+ const action = { id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' } as const;
+ const applyPreview = vi.fn(() => false);
+ const engine = { applyStructuralPreview: applyPreview } as unknown as CanvasEngine;
+ const dispatch = vi.fn();
+
+ expect(applyStructuralPreview(engine, dispatch, action)).toBe(false);
+
+ expect(applyPreview).toHaveBeenCalledWith(action);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
+
describe('createInpaintMaskLayer', () => {
it('builds an empty inpaint mask with the legacy-default diagonal fill', () => {
const layer = createInpaintMaskLayer('Inpaint Mask 1', 'm1');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index 4b22bf3686..1cb28b9d89 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -638,3 +638,16 @@ export const applyStructural = (
dispatch(forward);
}
};
+
+/** Applies a guarded live edit without recording history until the interaction ends. */
+export const applyStructuralPreview = (
+ engine: CanvasEngine | null,
+ dispatch: Dispatch<WorkbenchAction>,
+ action: WorkbenchAction
+): boolean => {
+ if (engine) {
+ return engine.applyStructuralPreview(action);
+ }
+ dispatch(action);
+ return true;
+};