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.

feat(canvas): paint directly on control layers

joshistoast9730be3f7407
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
index b0a68c5ce5..dc0ec9903c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
@@ -370,6 +370,110 @@ describe('createBitmapStore', () => {
h.store.dispose();
});
+ it('suspends debounced dirty work and resumes it only after release', async () => {
+ const h = createHarness();
+ h.store.markLayerDirty(LAYER);
+ const release = h.store.suspendLayer(LAYER);
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(h.uploadImage).not.toHaveBeenCalled();
+ expect(h.dispatch).not.toHaveBeenCalled();
+
+ release();
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.uploadImage).toHaveBeenCalledOnce();
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
+ it('records dirty work marked during suspension without scheduling until release', async () => {
+ const h = createHarness();
+ const release = h.store.suspendLayer(LAYER);
+ h.store.markLayerDirty(LAYER);
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(h.encodeSurface).not.toHaveBeenCalled();
+
+ release();
+ await h.store.flushPendingUploads();
+
+ expect(h.encodeSurface).toHaveBeenCalledOnce();
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
+ it('invalidates an in-flight result and keeps a barrier pending until suspension releases', async () => {
+ const uploads = [createDeferred<CanvasImageUploadResult>(), createDeferred<CanvasImageUploadResult>()];
+ let uploadIndex = 0;
+ const uploadImage = vi.fn(() => uploads[uploadIndex++]!.promise);
+ const h = createHarness({ uploadImage });
+ h.store.markLayerDirty(LAYER);
+ const barrier = h.store.flushPendingUploads();
+ await drainUntil(() => uploadImage.mock.calls.length === 1);
+
+ const release = h.store.suspendLayer(LAYER);
+ let settled = false;
+ void barrier.then(() => {
+ settled = true;
+ });
+ uploads[0]!.resolve({ height: 10, imageName: 'obsolete', width: 10 });
+ await drainUntil(() => settled);
+
+ expect(settled).toBe(false);
+ expect(h.dispatch).not.toHaveBeenCalled();
+ expect(uploadImage).toHaveBeenCalledOnce();
+
+ release();
+ await drainUntil(() => uploadImage.mock.calls.length === 2);
+ uploads[1]!.resolve({ height: 10, imageName: 'fresh', width: 10 });
+ await barrier;
+
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ expect(h.dispatch.mock.calls[0]![0]).toMatchObject({ source: { bitmap: { imageName: 'fresh' } } });
+ h.store.dispose();
+ });
+
+ it('supports nested suspension leases and idempotent release', async () => {
+ const h = createHarness();
+ h.store.markLayerDirty(LAYER);
+ const releaseOuter = h.store.suspendLayer(LAYER);
+ const releaseInner = h.store.suspendLayer(LAYER);
+
+ releaseOuter();
+ releaseOuter();
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(h.uploadImage).not.toHaveBeenCalled();
+
+ releaseInner();
+ await h.store.flushPendingUploads();
+ expect(h.uploadImage).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
+ it.each(['reset', 'dispose'] as const)('%s settles barriers waiting on suspended dirty work', async (ending) => {
+ const h = createHarness();
+ h.store.markLayerDirty(LAYER);
+ h.store.suspendLayer(LAYER);
+ const barrier = h.store.flushPendingUploads();
+ let settled = false;
+ void barrier.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ h.store[ending]();
+ await barrier;
+
+ expect(settled).toBe(true);
+ expect(h.dispatch).not.toHaveBeenCalled();
+ if (ending === 'reset') {
+ h.store.dispose();
+ }
+ });
+
it('a stroke landing while the barrier awaits an in-flight upload is not dropped: the barrier waits for the follow-up flush', async () => {
const deferreds = [createDeferred<CanvasImageUploadResult>(), createDeferred<CanvasImageUploadResult>()];
let call = 0;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
index c8e02f3528..92bd2d67c6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -123,6 +123,11 @@ export interface BitmapStoreDeps {
export interface BitmapStore {
/** Marks a layer dirty and (re)arms its debounce timer. Called on each committed stroke. */
markLayerDirty(layerId: string): void;
+ /**
+ * Temporarily prevents persistence from reading or dispatching `layerId` while
+ * preserving dirty work. Returns an idempotent release; leases may be nested.
+ */
+ suspendLayer(layerId: string): () => void;
/** Cancels pending persistence and invalidates an in-flight result for one layer. */
discardLayer(layerId: string): void;
/** Flushes every dirty layer immediately and resolves once all in-flight uploads settle. */
@@ -212,8 +217,25 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
* tombstones for the lifetime of the engine.
*/
const layerGenerations = new Map<string, number>();
+ /** Active nested persistence-suspension lease count per layer. */
+ const suspensionCounts = new Map<string, number>();
+ /** Barriers waiting for a suspended dirty layer to resume or be reset/disposed. */
+ const suspensionWaiters = new Set<() => void>();
let disposed = false;
+ const isSuspended = (layerId: string): boolean => (suspensionCounts.get(layerId) ?? 0) > 0;
+ const notifySuspensionWaiters = (): void => {
+ const waiters = [...suspensionWaiters];
+ suspensionWaiters.clear();
+ for (const resolve of waiters) {
+ resolve();
+ }
+ };
+ const waitForSuspensionChange = (): Promise<void> =>
+ new Promise((resolve) => {
+ suspensionWaiters.add(resolve);
+ });
+
const clearTimer = (layerId: string): void => {
const handle = debounceTimers.get(layerId);
if (handle !== undefined) {
@@ -446,10 +468,13 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
if (existing) {
return existing;
}
+ if (isSuspended(layerId)) {
+ return Promise.resolve();
+ }
const op = flushLayer(layerId).finally(() => {
inFlight.delete(layerId);
// Re-dirtied during the flush (new stroke) or a failure re-queued it.
- if (dirty.has(layerId) && !disposed) {
+ if (dirty.has(layerId) && !disposed && !isSuspended(layerId)) {
scheduleFlush(layerId);
} else {
// Any invalidated operation for this id has now settled and there is no
@@ -467,7 +492,46 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
}
dirty.add(layerId);
dirtyReason.set(layerId, 'stroke');
- scheduleFlush(layerId);
+ if (!isSuspended(layerId)) {
+ scheduleFlush(layerId);
+ }
+ };
+
+ const suspendLayer = (layerId: string): (() => void) => {
+ if (disposed) {
+ return () => undefined;
+ }
+ const count = suspensionCounts.get(layerId) ?? 0;
+ suspensionCounts.set(layerId, count + 1);
+ if (count === 0) {
+ const hadPendingWork = dirty.has(layerId) || debounceTimers.has(layerId) || inFlight.has(layerId);
+ clearTimer(layerId);
+ if (inFlight.has(layerId)) {
+ layerGenerations.set(layerId, (layerGenerations.get(layerId) ?? 0) + 1);
+ }
+ if (hadPendingWork) {
+ dirty.add(layerId);
+ dirtyReason.set(layerId, 'stroke');
+ }
+ }
+
+ let released = false;
+ return () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ const current = suspensionCounts.get(layerId) ?? 0;
+ if (current <= 1) {
+ suspensionCounts.delete(layerId);
+ if (dirty.has(layerId) && !disposed) {
+ scheduleFlush(layerId);
+ }
+ } else {
+ suspensionCounts.set(layerId, current - 1);
+ }
+ notifySuspensionWaiters();
+ };
};
const discardLayer = (layerId: string): void => {
@@ -499,13 +563,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// forever.
const failedThisBarrier = new Set<string>();
for (let iteration = 0; iteration < MAX_BARRIER_ITERATIONS; iteration += 1) {
- const toFlush = Array.from(dirty).filter((layerId) => !failedThisBarrier.has(layerId));
+ const toFlush = Array.from(dirty).filter((layerId) => !failedThisBarrier.has(layerId) && !isSuspended(layerId));
for (const layerId of toFlush) {
clearTimer(layerId);
void runFlush(layerId);
}
const ops = [...inFlight.values()];
if (ops.length === 0) {
+ if (Array.from(dirty).some((layerId) => isSuspended(layerId))) {
+ await waitForSuspensionChange();
+ continue;
+ }
return;
}
await Promise.all(ops);
@@ -541,6 +609,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
+ suspensionCounts.clear();
+ notifySuspensionWaiters();
// The self-echo map is per-(old)document; a reused layer id in the new
// document must not inherit it. `hashToImage` is content-addressed and kept.
lastApplied.clear();
@@ -554,11 +624,13 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
+ suspensionCounts.clear();
+ notifySuspensionWaiters();
inFlight.clear();
hashToImage.clear();
lastApplied.clear();
layerGenerations.clear();
};
- return { discardLayer, dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset };
+ return { discardLayer, dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset, suspendLayer };
};
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 a7fc78d147..1d3dee4717 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -7,6 +7,7 @@ import type {
} from '@workbench/canvas-engine/render/raster.testStub';
import type { ToolId } from '@workbench/canvas-engine/types';
import type {
+ CanvasControlLayerContract,
CanvasDocumentContractV2,
CanvasInpaintMaskLayerContract,
CanvasLayerContract,
@@ -2040,18 +2041,99 @@ const paintDoc = (): CanvasDocumentContractV2 => ({
width: 100,
});
+type ControlPaintHarnessOverrides = Partial<Omit<CanvasControlLayerContract, 'source' | 'type'>> & {
+ source: CanvasControlLayerContract['source'];
+};
+
+const createControlPaintHarness = (overrides: ControlPaintHarnessOverrides) => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal('Path2D', class FakePath2D {});
+
+ const { source, ...layerOverrides } = overrides;
+ const layer: CanvasControlLayerContract = {
+ adapter: {
+ beginEndStepPct: [0.1, 0.9],
+ controlMode: 'more_control',
+ kind: 'controlnet',
+ model: 'control-model',
+ weight: 0.7,
+ },
+ blendMode: 'screen',
+ filter: { settings: { low: 10 }, type: 'canny' },
+ id: 'control',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Control',
+ opacity: 0.6,
+ source,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ withTransparencyEffect: true,
+ ...layerOverrides,
+ };
+ const document: CanvasDocumentContractV2 = {
+ background: 'transparent',
+ bbox: { height: 100, width: 100, x: 0, y: 0 },
+ height: 100,
+ layers: [layer],
+ selectedLayerId: layer.id,
+ version: 2,
+ width: 100,
+ };
+ const { projectId, store } = createReducerBackedStore(document);
+ const backend = createTestStubRasterBackend();
+ const bitmapStore = createSpyBitmapStore();
+ const engine = createCanvasEngine({
+ backend,
+ bitmapStore,
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ const strokes: StrokeCommittedEvent[] = [];
+ engine.onStrokeCommitted((event) => strokes.push(event));
+ const overlay = createInputCanvas();
+ const screen = createInputCanvas();
+ engine.attach(screen.element, overlay.element);
+
+ return {
+ backend,
+ bitmapStore,
+ engine,
+ overlay,
+ publishInitialCache: async () => {
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+ await flushMicrotasks();
+ },
+ raf,
+ screen,
+ strokes,
+ };
+};
+
/** A minimal in-memory bitmap store: records dirty-marks, never touches the network. */
const createSpyBitmapStore = (): BitmapStore & {
markLayerDirty: Mock<(layerId: string) => void>;
+ releaseSuspendedLayer: Mock<() => void>;
reset: Mock<() => void>;
-} => ({
- discardLayer: vi.fn(),
- dispose: vi.fn(),
- flushPendingUploads: vi.fn(() => Promise.resolve()),
- isSelfEcho: () => false,
- markLayerDirty: vi.fn<(layerId: string) => void>(),
- reset: vi.fn<() => void>(),
-});
+ suspendLayer: Mock<(layerId: string) => () => void>;
+} => {
+ const releaseSuspendedLayer = vi.fn();
+ return {
+ discardLayer: vi.fn(),
+ dispose: vi.fn(),
+ flushPendingUploads: vi.fn(() => Promise.resolve()),
+ isSelfEcho: () => false,
+ markLayerDirty: vi.fn<(layerId: string) => void>(),
+ releaseSuspendedLayer,
+ reset: vi.fn<() => void>(),
+ suspendLayer: vi.fn(() => releaseSuspendedLayer),
+ };
+};
/** A fake canvas that also lets a test fire pointer events at the engine's listeners. */
const createInputCanvas = (
@@ -2111,6 +2193,141 @@ const putImageDataCalls = (surfaces: StubRasterSurface[]): { image: unknown; x:
.map((entry) => ({ image: entry.args[0], x: entry.args[1], y: entry.args[2] }))
);
+describe('engine-owned control pixel editing', () => {
+ it('brushes an empty control in place and never creates a raster layer', () => {
+ const h = createControlPaintHarness({ source: { bitmap: null, type: 'paint' } });
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointermove', pointerAt(40, 40));
+ h.overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));
+
+ expect(h.engine.getDocument()!.layers).toHaveLength(1);
+ expect(h.engine.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });
+ expect(h.strokes).toHaveLength(1);
+ expect(h.strokes[0]!.layerId).toBe('control');
+ expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('control');
+ expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ h.engine.dispose();
+ });
+
+ it('materializes an image control plus brush stroke as one reversible edit', async () => {
+ const h = createControlPaintHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 20 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument()!.layers[0]);
+
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointermove', pointerAt(25, 25));
+ h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }));
+
+ const after = structuredClone(h.engine.getDocument()!.layers[0]);
+ expect(after).toMatchObject({
+ adapter: before && 'adapter' in before ? before.adapter : undefined,
+ filter: before && 'filter' in before ? before.filter : undefined,
+ id: 'control',
+ source: { type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ withTransparencyEffect: true,
+ });
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledWith('control');
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ expect(h.bitmapStore.markLayerDirty.mock.invocationCallOrder[0]).toBeLessThan(
+ h.bitmapStore.releaseSuspendedLayer.mock.invocationCallOrder[0]!
+ );
+
+ h.engine.undo();
+ expect(h.engine.getDocument()!.layers[0]).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.engine.stores.canRedo.get()).toBe(true);
+
+ h.engine.redo();
+ expect(h.engine.getDocument()!.layers[0]).toEqual(after);
+ h.engine.dispose();
+ });
+
+ it.each(['eraser', 'brush'] as const)(
+ 'rolls back a prepared image control when a %s gesture is cancelled',
+ async (tool) => {
+ const h = createControlPaintHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.setTool(tool);
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ h.overlay.fire('pointercancel', pointerAt(5, 5, { buttons: 0 }));
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledWith('control');
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ h.engine.dispose();
+ }
+ );
+
+ it.each([
+ ['locked', { isLocked: true }],
+ ['disabled', { isEnabled: false }],
+ ] as const)('does not mutate or auto-create over a %s control', (_scenario, patch) => {
+ const h = createControlPaintHarness({ source: { bitmap: null, type: 'paint' }, ...patch });
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointerup', pointerAt(20, 20, { buttons: 0 }));
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ h.engine.dispose();
+ });
+
+ it('normalizes a transformed empty control before its first brush stroke', () => {
+ const h = createControlPaintHarness({
+ source: { bitmap: null, type: 'paint' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 30, y: 40 },
+ });
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(35, 45));
+ h.overlay.fire('pointerup', pointerAt(35, 45, { buttons: 0 }));
+ expect(h.engine.getDocument()!.layers[0]).toMatchObject({
+ id: 'control',
+ source: { type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ });
+ h.engine.undo();
+ expect(h.engine.getDocument()!.layers[0]).toMatchObject({
+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 30, y: 40 },
+ });
+ h.engine.dispose();
+ });
+
+ it('does not edit or auto-create when an image control cache is not ready', () => {
+ const h = createControlPaintHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ });
+ h.raf.flush();
+ const before = structuredClone(h.engine.getDocument());
+
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ h.overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));
+
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.getDocument()!.layers).toHaveLength(1);
+ expect(h.strokes).toHaveLength(0);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.bitmapStore.discardLayer).not.toHaveBeenCalled();
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.engine.stores.canRedo.get()).toBe(false);
+ h.engine.dispose();
+ });
+});
+
describe('engine-owned history: stroke → undo → redo', () => {
const drawStroke = () => {
const raf = createControllableRaf();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index f8d5b1c573..a110cbb523 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -135,7 +135,13 @@ import {
import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';
import { createSelectObjectSession } from '@workbench/widgets/layers/selectObjectSession';
-import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';
+import type {
+ ControlPixelEditTransaction,
+ PixelEditPatch,
+ StrokeCommittedEvent,
+ Tool,
+ ToolContext,
+} from './tools/tool';
import { uploadCanvasImage } from './backend/canvasImages';
import { createCanvasOperationController, type CanvasOperationController } from './canvasOperationController';
@@ -151,9 +157,19 @@ import {
isRenderableLayer,
renderableSourceOf,
} from './document/sources';
+import {
+ bakeControlPixelEditSurface,
+ buildMaterializedControlLayer,
+ decideControlPixelEdit,
+} from './editing/controlPixelEdit';
import { createDocumentPatchEntry } from './history/documentPatch';
import { createHistory, type History, type HistoryEntry } from './history/history';
import { createImagePatchEntry, type ImagePatchApply } from './history/imagePatch';
+import {
+ createLayerSnapshotEntry,
+ type LayerPixelSnapshot,
+ type LayerPixelSnapshotApply,
+} from './history/layerSnapshot';
import { createViewTool } from './tools/viewTool';
/**
@@ -1046,6 +1062,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// Engine-owned canvas history (paint pixel patches + structural patches).
// Project-level undo deliberately no longer covers the canvas (Phase 0).
const history: History = createHistory();
+ let openControlPixelEdit: { cancel: () => void; layerId: string } | null = null;
+ const cancelOpenControlPixelEdit = (): void => {
+ openControlPixelEdit?.cancel();
+ };
// Nudge coalescing: a rapid burst of same-layer arrow nudges collapses into a
// single history entry whose inverse restores the burst's ORIGINAL position.
@@ -1176,6 +1196,36 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
};
+ const commitOrdinaryStroke = (event: StrokeCommittedEvent): void => {
+ // A fresh stroke ends any open nudge-coalescing burst.
+ endNudgeBurst();
+ notifyLayerPainted(event.layerId);
+ // Persistence first: mark the layer dirty so a debounced upload fires even
+ // when no external subscriber is attached.
+ bitmapStore.markLayerDirty(event.layerId);
+ // Record the edit on the engine-owned history. Guarded against re-entrancy:
+ // an undo/redo replay routes pixels through `applyImagePatch`, not a fresh
+ // stroke, so this never fires during apply — the guard is belt-and-braces.
+ if (!history.isApplying()) {
+ const label = event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke';
+ history.push(
+ event.createdLayer
+ ? createComposedPaintEntry(event.createdLayer, event, label)
+ : createImagePatchEntry({
+ after: event.afterImageData,
+ apply: applyImagePatch,
+ before: event.beforeImageData,
+ label,
+ layerId: event.layerId,
+ rect: event.dirtyRect,
+ })
+ );
+ }
+ for (const listener of strokeListeners) {
+ listener(event);
+ }
+ };
+
// ---- Selection (transient interaction state) + marching ants ------------
//
// The selection lives on the engine, never the reducer, and is not undoable
@@ -1241,6 +1291,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const toolContext: ToolContext = {
applyTransform: () => applyTransform(),
backend,
+ beginControlPixelEdit: (layerId) => beginControlPixelEdit(layerId),
beginTransformSession: (layerId) => beginTransformSession(layerId),
cancelTextEdit: () => cancelTextEdit(),
cancelTransform: () => cancelTransform(),
@@ -1249,38 +1300,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
createLayerId,
createPath2D: createPath2DImpl,
dispatch: (action) => store.dispatch(action),
- emitStrokeCommitted: (event) => {
- // A fresh stroke ends any open nudge-coalescing burst.
- endNudgeBurst();
- // Persistence first: mark the layer dirty so a debounced upload fires even
- // when no external subscriber is attached.
- bitmapStore.markLayerDirty(event.layerId);
- // Record the edit on the engine-owned history. Guarded against re-entrancy:
- // an undo/redo replay routes pixels through `applyImagePatch`, not a fresh
- // stroke, so this never fires during apply — the guard is belt-and-braces.
- if (!history.isApplying()) {
- const label = event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke';
- history.push(
- event.createdLayer
- ? // The gesture auto-created its paint layer: compose layer creation +
- // stroke into ONE entry, so an undo removes the now-empty layer AND the
- // stroke (skipping the pixel restore — the layer's cache is gone), and a
- // redo re-adds the layer then re-applies the stroke pixels.
- createComposedPaintEntry(event.createdLayer, event, label)
- : createImagePatchEntry({
- after: event.afterImageData,
- apply: applyImagePatch,
- before: event.beforeImageData,
- label,
- layerId: event.layerId,
- rect: event.dirtyRect,
- })
- );
- }
- for (const listener of strokeListeners) {
- listener(event);
- }
- },
+ emitStrokeCommitted: (event) => commitOrdinaryStroke(event),
getDocument: () => mirror.getDocument(),
getSelectionMask: () => selection.mask(),
invalidate: (payload) => scheduler.invalidate(payload),
@@ -2446,6 +2466,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true });
},
onDocumentReplaced: () => {
+ pipeline.cancelActiveGesture();
+ cancelOpenControlPixelEdit();
canvasOperations.invalidateDocument(projectId);
cancelSelectObjectSession();
const previousImageNames = [...mirroredLayerImageNames.values()];
@@ -2461,7 +2483,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
// otherwise commit against the replaced document. Routing through the
// pipeline clears `gestureActive` and runs the tool's `onPointerCancel`, so
// the tool drops its own transient state.
- pipeline.cancelActiveGesture();
// Defensive: a non-bbox active tool won't have cleared a lingering preview.
stores.bboxPreview.set(null);
history.clear();
@@ -2525,6 +2546,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
scheduler.invalidate({ all: true });
},
onLayersChanged: (ids, sourceChangedIds) => {
+ if (openControlPixelEdit && ids.includes(openControlPixelEdit.layerId)) {
+ pipeline.cancelActiveGesture();
+ cancelOpenControlPixelEdit();
+ }
const doc = mirror.getDocument();
for (const id of sourceChangedIds) {
canvasOperations.invalidateSource(projectId, id);
@@ -2647,6 +2672,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const unsubscribeProjectPreviewLifecycle = store.subscribe(() => {
const activeProjectId = store.getState().activeProjectId;
if (lastActiveProjectId === projectId && activeProjectId !== projectId) {
+ pipeline.cancelActiveGesture();
+ cancelOpenControlPixelEdit();
canvasOperations.invalidateProject(projectId);
cancelSelectObjectSession();
rasterDocumentGeneration += 1;
@@ -3997,6 +4024,304 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return current !== undefined && isDeeplyEqual(current, expected);
};
+ const applyControlLayerSnapshot: LayerPixelSnapshotApply = (snapshot) => {
+ const pixels = backend.createSurface(snapshot.rect.width, snapshot.rect.height);
+ if (snapshot.pixels) {
+ pixels.ctx.putImageData(snapshot.pixels, 0, 0);
+ }
+ const prepared = prepareGeneratedPaintCache(snapshot.layer.id, snapshot.rect, pixels);
+ dispatchPreparedMutation(
+ { layer: snapshot.layer, layerId: snapshot.layer.id, type: 'replaceCanvasLayer' },
+ () => documentHasLayerContract(getReducerDocument(), snapshot.layer),
+ () => documentHasLayerContract(mirror.getDocument(), snapshot.layer)
+ );
+ try {
+ bitmapStore.discardLayer(snapshot.layer.id);
+ } catch {
+ // Persistence bookkeeping is ancillary after reducer acceptance.
+ }
+ installGeneratedPaintCache(prepared, snapshot.layer.source.type === 'paint');
+ };
+
+ const beginControlPixelEdit = (layerId: string): ControlPixelEditTransaction | null => {
+ const document = mirror.getDocument();
+ const layer = document?.layers.find((candidate) => candidate.id === layerId);
+ if (
+ !canEditDocument() ||
+ !document ||
+ document.selectedLayerId !== layerId ||
+ !layer ||
+ layer.type !== 'control' ||
+ openControlPixelEdit ||
+ canvasOperations.getSnapshot().status !== 'idle' ||
+ stores.transformSession.get()
+ ) {
+ return null;
+ }
+
+ const contentRect = getSourceContentRect(layer, document);
+ const decision = decideControlPixelEdit({
+ hasSourceContent: !isEmpty(contentRect),
+ isCacheReady: isLayerCacheReadyForOp(layer, document),
+ layer,
+ });
+ if (decision.status === 'rejected') {
+ return null;
+ }
+
+ if (decision.status === 'direct') {
+ let closed = false;
+ let owner: { cancel: () => void; layerId: string };
+ const close = (): boolean => {
+ if (closed || openControlPixelEdit !== owner) {
+ return false;
+ }
+ closed = true;
+ openControlPixelEdit = null;
+ return true;
+ };
+ const commitPatch = (label: string, patch: PixelEditPatch): boolean => {
+ if (closed || openControlPixelEdit !== owner) {
+ return false;
+ }
+ const currentDocument = mirror.getDocument();
+ const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layerId);
+ if (
+ store.getState().activeProjectId !== projectId ||
+ !canEditDocument() ||
+ canvasOperations.getSnapshot().status !== 'idle' ||
+ currentDocument?.selectedLayerId !== layerId ||
+ currentLayer !== layer
+ ) {
+ close();
+ const entry = layerCache.get(layerId);
+ if (entry) {
+ entry.surface.ctx.putImageData(patch.before, patch.rect.x - entry.rect.x, patch.rect.y - entry.rect.y);
+ adjustedSurfaceCache.delete(layerId);
+ scheduler.invalidate({ layers: [layerId] });
+ }
+ return false;
+ }
+ close();
+ endNudgeBurst();
+ notifyLayerPainted(layerId);
+ bitmapStore.markLayerDirty(layerId);
+ if (!history.isApplying()) {
+ history.push(
+ createImagePatchEntry({
+ after: patch.after,
+ apply: applyImagePatch,
+ before: patch.before,
+ label,
+ layerId,
+ rect: patch.rect,
+ })
+ );
+ }
+ return true;
+ };
+ const transaction: ControlPixelEditTransaction = {
+ cancel: () => {
+ close();
+ },
+ commitPatch: (label, patch) => {
+ commitPatch(label, patch);
+ },
+ commitStroke: (event) => {
+ if (event.layerId !== layerId) {
+ transaction.cancel();
+ return;
+ }
+ const label = event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke';
+ if (
+ !commitPatch(label, {
+ after: event.afterImageData,
+ before: event.beforeImageData,
+ rect: event.dirtyRect,
+ })
+ ) {
+ return;
+ }
+ for (const listener of strokeListeners) {
+ listener(event);
+ }
+ },
+ layerId,
+ };
+ owner = { cancel: transaction.cancel, layerId };
+ openControlPixelEdit = owner;
+ return transaction;
+ }
+
+ const originalEntry = layerCache.get(layerId);
+ const originalCache = originalEntry
+ ? {
+ hasPublishedPixels: originalEntry.hasPublishedPixels,
+ lastUsed: originalEntry.lastUsed,
+ rect: { ...originalEntry.rect },
+ stale: originalEntry.stale,
+ surface: originalEntry.surface,
+ version: originalEntry.version,
+ }
+ : null;
+ const beforeRect = originalCache?.rect ?? { ...contentRect };
+ let beforePixels: ImageData | null = null;
+ if (!isEmpty(beforeRect)) {
+ if (!originalEntry) {
+ return null;
+ }
+ try {
+ beforePixels = originalEntry.surface.ctx.getImageData(0, 0, beforeRect.width, beforeRect.height);
+ } catch {
+ return null;
+ }
+ }
+
+ let prepared: ReturnType<LayerCacheStore['prepareReplacement']>;
+ try {
+ if (originalEntry && !isEmpty(originalEntry.rect)) {
+ const baked = bakeControlPixelEditSurface({
+ backend,
+ source: originalEntry.surface,
+ sourceRect: originalEntry.rect,
+ transform: layer.transform,
+ });
+ prepared = prepareGeneratedPaintCache(layerId, baked.rect, baked.surface);
+ } else {
+ const empty = backend.createSurface(0, 0);
+ prepared = prepareGeneratedPaintCache(layerId, { height: 0, width: 0, x: 0, y: 0 }, empty);
+ }
+ } catch {
+ return null;
+ }
+
+ const before: LayerPixelSnapshot = {
+ layer: structuredClone(layer),
+ pixels: beforePixels,
+ rect: beforeRect,
+ };
+ const restoreOriginal = (): void => {
+ if (originalCache) {
+ const current = layerCache.get(layerId);
+ if (current) {
+ current.hasPublishedPixels = originalCache.hasPublishedPixels;
+ current.lastUsed = originalCache.lastUsed;
+ current.rect = { ...originalCache.rect };
+ current.stale = originalCache.stale;
+ current.surface = originalCache.surface;
+ current.version = originalCache.version;
+ }
+ } else {
+ layerCache.delete(layerId);
+ }
+ adjustedSurfaceCache.delete(layerId);
+ transformOverrides.delete(layerId);
+ scheduler.invalidate({ layers: [layerId], overlay: true });
+ };
+ const releasePersistence = bitmapStore.suspendLayer(layerId);
+ try {
+ const previewEntry = originalEntry ?? layerCache.getOrCreateRect(layerId, prepared.rect);
+ previewEntry.surface = prepared.surface;
+ previewEntry.rect = { ...prepared.rect };
+ previewEntry.hasPublishedPixels = true;
+ previewEntry.stale = false;
+ previewEntry.version += 1;
+ adjustedSurfaceCache.delete(layerId);
+ transformOverrides.set(layerId, { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+ scheduler.invalidate({ layers: [layerId], overlay: true });
+ } catch {
+ restoreOriginal();
+ releasePersistence();
+ return null;
+ }
+
+ let closed = false;
+ let owner: { cancel: () => void; layerId: string };
+ const close = (): boolean => {
+ if (closed || openControlPixelEdit !== owner) {
+ return false;
+ }
+ closed = true;
+ openControlPixelEdit = null;
+ return true;
+ };
+ const cancel = (): void => {
+ if (!close()) {
+ return;
+ }
+ restoreOriginal();
+ releasePersistence();
+ };
+ const commit = (label: string, event?: StrokeCommittedEvent): void => {
+ if (!close()) {
+ return;
+ }
+ const currentDocument = mirror.getDocument();
+ const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layerId);
+ const edited = layerCache.get(layerId);
+ if (
+ store.getState().activeProjectId !== projectId ||
+ !canEditDocument() ||
+ canvasOperations.getSnapshot().status !== 'idle' ||
+ currentDocument?.selectedLayerId !== layerId ||
+ currentLayer !== layer ||
+ !edited ||
+ (event && event.layerId !== layerId)
+ ) {
+ restoreOriginal();
+ releasePersistence();
+ return;
+ }
+ let afterPixels: ImageData | null = null;
+ let after: LayerPixelSnapshot;
+ try {
+ if (!isEmpty(edited.rect)) {
+ afterPixels = edited.surface.ctx.getImageData(0, 0, edited.rect.width, edited.rect.height);
+ }
+ const materialized = buildMaterializedControlLayer(layer, edited.rect);
+ after = {
+ layer: materialized,
+ pixels: afterPixels,
+ rect: { ...edited.rect },
+ };
+ dispatchPreparedMutation(
+ { layer: materialized, layerId, type: 'replaceCanvasLayer' },
+ () => documentHasLayerContract(getReducerDocument(), materialized),
+ () => documentHasLayerContract(mirror.getDocument(), materialized)
+ );
+ } catch (error) {
+ restoreOriginal();
+ releasePersistence();
+ throw error;
+ }
+ transformOverrides.delete(layerId);
+ endNudgeBurst();
+ try {
+ notifyLayerPainted(layerId);
+ bitmapStore.markLayerDirty(layerId);
+ if (!history.isApplying()) {
+ history.push(createLayerSnapshotEntry({ after, apply: applyControlLayerSnapshot, before, label }));
+ }
+ } finally {
+ releasePersistence();
+ }
+ if (event) {
+ for (const listener of strokeListeners) {
+ listener(event);
+ }
+ }
+ };
+ const transaction: ControlPixelEditTransaction = {
+ cancel,
+ commitPatch: (label) => commit(label),
+ commitStroke: (event) => commit(event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke', event),
+ layerId,
+ };
+ owner = { cancel, layerId };
+ openControlPixelEdit = owner;
+ return transaction;
+ };
+
const captureLayerCache = (
layer: CanvasLayerContract,
doc: CanvasDocumentContractV2
@@ -6396,6 +6721,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return;
}
disposed = true;
+ pipeline.cancelActiveGesture();
+ cancelOpenControlPixelEdit();
clearOwnedFilterSession();
clearOwnedSelectObjectSession();
canvasOperations.dispose();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
index bff38b0333..16a68580ef 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
@@ -1,7 +1,12 @@
import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';
-import type { StrokeCommittedEvent, Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type {
+ ControlPixelEditTransaction,
+ StrokeCommittedEvent,
+ Tool,
+ ToolContext,
+} from '@workbench/canvas-engine/tools/tool';
import type { PointerInput } from '@workbench/canvas-engine/types';
-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';
+import type { CanvasControlLayerContract, CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';
import type { WorkbenchAction } from '@workbench/workbenchState';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
@@ -52,6 +57,32 @@ const inpaintMaskLayer = (id: string): CanvasLayerContract => ({
type: 'inpaint_mask',
});
+const controlPaintLayer = (id: string): CanvasControlLayerContract => ({
+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { bitmap: null, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ withTransparencyEffect: true,
+});
+
+const controlImageLayer = (id: string): CanvasControlLayerContract => ({
+ ...controlPaintLayer(id),
+ source: { image: { height: 20, imageName: id, width: 20 }, type: 'image' },
+});
+
+const controlTransaction = (): ControlPixelEditTransaction => ({
+ cancel: vi.fn(),
+ commitPatch: vi.fn(),
+ commitStroke: vi.fn(),
+ layerId: 'control',
+});
+
const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({
background: 'transparent',
bbox: { height: 100, width: 100, x: 0, y: 0 },
@@ -80,6 +111,7 @@ const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.
const cancel = (t: Tool, ctx: ToolContext): void => t.onPointerCancel?.(ctx);
interface Harness {
+ beginControlPixelEdit: ReturnType<typeof vi.fn> | null;
ctx: ToolContext;
backend: StubRasterBackend;
layers: LayerCacheStore;
@@ -89,7 +121,10 @@ interface Harness {
createdIds: string[];
}
-const createHarness = (doc: CanvasDocumentContractV2): Harness => {
+const createHarness = (
+ doc: CanvasDocumentContractV2,
+ transaction: ControlPixelEditTransaction | null | undefined = undefined
+): Harness => {
const backend = createTestStubRasterBackend();
const layers = createLayerCacheStore(backend);
const stores = createEngineStores();
@@ -97,10 +132,12 @@ const createHarness = (doc: CanvasDocumentContractV2): Harness => {
const strokes: StrokeCommittedEvent[] = [];
const painted: string[] = [];
const createdIds: string[] = [];
+ const beginControlPixelEdit = transaction === undefined ? null : vi.fn(() => transaction);
let idCounter = 0;
const ctx: ToolContext = {
backend,
+ ...(beginControlPixelEdit ? { beginControlPixelEdit } : {}),
commitStructural: vi.fn(),
createLayerId: () => {
const id = `new-layer-${(idCounter += 1)}`;
@@ -109,7 +146,10 @@ const createHarness = (doc: CanvasDocumentContractV2): Harness => {
},
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
- emitStrokeCommitted: (event) => strokes.push(event),
+ emitStrokeCommitted: (event) => {
+ painted.push(event.layerId);
+ strokes.push(event);
+ },
getDocument: () => doc,
invalidate: vi.fn(),
layers,
@@ -121,7 +161,7 @@ const createHarness = (doc: CanvasDocumentContractV2): Harness => {
viewport: null as never,
};
- return { backend, createdIds, ctx, dispatched, layers, painted, strokes };
+ return { backend, beginControlPixelEdit, createdIds, ctx, dispatched, layers, painted, strokes };
};
const cacheOps = (surface: StubRasterSurface): string[] => surface.callLog.map((entry) => entry.op);
@@ -217,6 +257,42 @@ describe('brush tool: cancel', () => {
});
describe('paint tool: target resolution', () => {
+ it('commits a selected control stroke through its transaction without adding a raster layer', () => {
+ const transaction = controlTransaction();
+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+
+ down(brush, h.ctx, pointer(10, 10));
+ move(brush, h.ctx, pointer(20, 20), [pointer(20, 20)]);
+ up(brush, h.ctx, pointer(20, 20, { buttons: 0 }));
+
+ expect(h.beginControlPixelEdit).toHaveBeenCalledWith('control');
+ expect(transaction.commitStroke).toHaveBeenCalledOnce();
+ expect(transaction.cancel).not.toHaveBeenCalled();
+ expect(h.dispatched).toHaveLength(0);
+ });
+
+ it.each(['pointercancel', 'deactivate'] as const)('rolls back control preparation on %s', (ending) => {
+ const transaction = controlTransaction();
+ const h = createHarness(makeDoc([controlImageLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ if (ending === 'pointercancel') {
+ cancel(brush, h.ctx);
+ } else {
+ brush.onDeactivate?.(h.ctx);
+ }
+ expect(transaction.cancel).toHaveBeenCalledOnce();
+ expect(transaction.commitStroke).not.toHaveBeenCalled();
+ });
+
+ it('does not fall through to raster auto-create when control preparation is rejected', () => {
+ const h = createHarness(makeDoc([controlImageLayer('control')], 'control'), null);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ expect(h.dispatched).toHaveLength(0);
+ });
+
it('auto-creates a paint layer (one dispatch) when the selection is not paintable', () => {
const doc = makeDoc([imageLayer('img1')], 'img1');
const h = createHarness(doc);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 8dd5af8ce0..3b0ccee773 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -17,7 +17,7 @@
import type { PointerInput } from '@workbench/canvas-engine/types';
import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';
-import type { Tool, ToolContext } from './tool';
+import type { StrokeCommittedEvent, Tool, ToolContext } from './tool';
import { createStrokeSession, type StrokeSession } from './strokeSession';
@@ -44,6 +44,8 @@ const MASK_STROKE_COLOR = '#ffffff';
/** The resolved paint target for a gesture. `createdLayer` is set only when auto-created. */
interface PaintTarget {
layerId: string;
+ commit(event: StrokeCommittedEvent): void;
+ cancel(): void;
/** When the gesture auto-created its layer, the created contract + insert index (for history). */
createdLayer?: { layer: CanvasLayerContract; index: number };
/**
@@ -86,7 +88,12 @@ const resolveTarget = (ctx: ToolContext): PaintTarget | null => {
return null;
}
// The cache (if any) keeps its current content extent; the stroke grows it.
- return { layerId: selected.id, transparencyLocked: selected.isTransparencyLocked === true };
+ return {
+ cancel: () => undefined,
+ commit: (event) => ctx.emitStrokeCommitted(event),
+ layerId: selected.id,
+ transparencyLocked: selected.isTransparencyLocked === true,
+ };
}
if (selected && isMaskLayer(selected)) {
@@ -97,7 +104,25 @@ const resolveTarget = (ctx: ToolContext): PaintTarget | null => {
if (selected.isLocked || !selected.isEnabled) {
return null;
}
- return { color: MASK_STROKE_COLOR, forceOpaque: true, layerId: selected.id };
+ return {
+ cancel: () => undefined,
+ color: MASK_STROKE_COLOR,
+ commit: (event) => ctx.emitStrokeCommitted(event),
+ forceOpaque: true,
+ layerId: selected.id,
+ };
+ }
+
+ if (selected?.type === 'control') {
+ const transaction = ctx.beginControlPixelEdit?.(selected.id) ?? null;
+ if (!transaction) {
+ return null;
+ }
+ return {
+ cancel: transaction.cancel,
+ commit: transaction.commitStroke,
+ layerId: transaction.layerId,
+ };
}
// Selection is an image/other raster, another layer type, or nothing: create a
@@ -123,12 +148,18 @@ const resolveTarget = (ctx: ToolContext): PaintTarget | null => {
// grows it from empty to the stroke's content bounds.
const entry = ctx.layers.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });
entry.stale = false;
- return { createdLayer: { index: 0, layer }, layerId };
+ return {
+ cancel: () => undefined,
+ commit: (event) => ctx.emitStrokeCommitted(event),
+ createdLayer: { index: 0, layer },
+ layerId,
+ };
};
/** Creates a brush-family tool from its per-gesture {@link PaintToolSpec}. */
export const createPaintTool = (spec: PaintToolSpec): Tool => {
let session: StrokeSession | null = null;
+ let target: PaintTarget | null = null;
const cursorRadiusDoc = (ctx: ToolContext): number => spec.size(ctx) / 2;
@@ -139,22 +170,25 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
const endSession = (): void => {
session = null;
+ target = null;
};
return {
cursor: () => 'crosshair',
id: spec.id,
- onDeactivate: (ctx) => {
- if (session) {
+ onDeactivate: (ctx, opts) => {
+ if (session && target && !opts?.temporary) {
session.cancel();
+ target.cancel();
endSession();
}
ctx.setOverlayCursor(null);
ctx.invalidate({ overlay: true });
},
onPointerCancel: () => {
- if (session) {
+ if (session && target) {
session.cancel();
+ target.cancel();
endSession();
}
},
@@ -162,35 +196,42 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
if (session || (input.buttons & PRIMARY_BUTTON) === 0) {
return;
}
- const target = resolveTarget(ctx);
+ const resolvedTarget = resolveTarget(ctx);
updateCursorRing(ctx, input);
- if (!target) {
+ if (!resolvedTarget) {
return;
}
// Transparency lock: the eraser is refused (it would alter the locked alpha);
// the brush switches to `source-atop` so colour lands only on existing pixels.
- if (target.transparencyLocked && spec.id === 'eraser') {
+ if (resolvedTarget.transparencyLocked && spec.id === 'eraser') {
return;
}
- const composite = target.transparencyLocked && spec.id === 'brush' ? 'source-atop' : spec.composite;
- session = createStrokeSession({
- // Resolve the selection clip ONCE per gesture: when a selection exists the
- // stroke is masked to it; with none the field is null and the hot path is
- // untouched (no per-point mask lookup).
- clipMask: ctx.getSelectionMask?.() ?? null,
- color: target.color ?? spec.color(ctx),
- composite,
- createdLayer: target.createdLayer ?? null,
- ctx,
- layerId: target.layerId,
- // Mask strokes are forced opaque (an alpha stencil is all-or-nothing); a
- // brush-opacity mask stroke would silently attenuate the denoise strength.
- opacity: target.forceOpaque ? 1 : spec.opacity(ctx),
- size: spec.size(ctx),
- thinning: spec.thinning(ctx),
- tool: spec.id,
- });
- session.addPoints([input]);
+ const composite = resolvedTarget.transparencyLocked && spec.id === 'brush' ? 'source-atop' : spec.composite;
+ target = resolvedTarget;
+ try {
+ session = createStrokeSession({
+ // Resolve the selection clip ONCE per gesture: when a selection exists the
+ // stroke is masked to it; with none the field is null and the hot path is
+ // untouched (no per-point mask lookup).
+ clipMask: ctx.getSelectionMask?.() ?? null,
+ color: target.color ?? spec.color(ctx),
+ composite,
+ createdLayer: target.createdLayer ?? null,
+ ctx,
+ layerId: target.layerId,
+ // Mask strokes are forced opaque (an alpha stencil is all-or-nothing); a
+ // brush-opacity mask stroke would silently attenuate the denoise strength.
+ opacity: target.forceOpaque ? 1 : spec.opacity(ctx),
+ size: spec.size(ctx),
+ thinning: spec.thinning(ctx),
+ tool: spec.id,
+ });
+ session.addPoints([input]);
+ } catch {
+ session?.cancel();
+ target.cancel();
+ endSession();
+ }
},
onPointerMove: (ctx, input, batch) => {
updateCursorRing(ctx, input);
@@ -200,9 +241,17 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
},
onPointerUp: (ctx, input) => {
updateCursorRing(ctx, input);
- if (session) {
- session.commit();
- endSession();
+ if (session && target) {
+ try {
+ const event = session.commit();
+ if (event) {
+ target.commit(event);
+ } else {
+ target.cancel();
+ }
+ } finally {
+ endSession();
+ }
}
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
index 62e409f24f..6304b3a82a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
@@ -1,6 +1,6 @@
import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';
-import type { StrokeCommittedEvent, ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';
import type { PointerInput } from '@workbench/canvas-engine/types';
import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
@@ -41,15 +41,16 @@ const runStroke = (opts: { withMask: boolean }) => {
const entry: LayerCacheEntry = layers.getOrCreate('L', 100, 100);
const mask = opts.withMask ? backend.createSurface(100, 100) : null;
const clipMask = mask ? { rect: { height: 100, width: 100, x: 0, y: 0 }, surface: mask } : null;
- const strokes: StrokeCommittedEvent[] = [];
+ const emitStrokeCommitted = vi.fn();
+ const notifyLayerPainted = vi.fn();
const ctx = {
backend,
createPath2D: (d?: string) => ({ d }) as unknown as Path2D,
- emitStrokeCommitted: (event: StrokeCommittedEvent) => strokes.push(event),
+ emitStrokeCommitted,
invalidate: vi.fn(),
layers,
- notifyLayerPainted: vi.fn(),
+ notifyLayerPainted,
} as unknown as ToolContext;
// Only the scratch is created after this point.
@@ -67,10 +68,10 @@ const runStroke = (opts: { withMask: boolean }) => {
});
session.addPoints([pointer(10, 10)]);
session.addPoints([pointer(40, 10), pointer(40, 40)]);
- session.commit();
+ const event = session.commit();
const scratch = created[0]!;
- return { cache: entry.surface as StubRasterSurface, scratch, strokes };
+ return { cache: entry.surface as StubRasterSurface, emitStrokeCommitted, event, notifyLayerPainted, scratch };
};
const compositeOps = (surface: StubRasterSurface): unknown[] =>
@@ -103,11 +104,10 @@ describe('strokeSession: selection-constrained painting', () => {
expect(compositeOps(withMask.cache)).not.toContain('destination-in');
});
- it('still emits a commit with a dirty rect the mask does not shift', () => {
- const { strokes } = runStroke({ withMask: true });
- expect(strokes).toHaveLength(1);
- expect(strokes[0]!.dirtyRect.width).toBeGreaterThan(0);
- expect(strokes[0]!.dirtyRect.height).toBeGreaterThan(0);
+ it('returns a commit with a dirty rect the mask does not shift', () => {
+ const { event } = runStroke({ withMask: true });
+ expect(event!.dirtyRect.width).toBeGreaterThan(0);
+ expect(event!.dirtyRect.height).toBeGreaterThan(0);
});
});
@@ -117,14 +117,15 @@ describe('strokeSession: content-sized cache growth', () => {
const layers = createLayerCacheStore(backend);
const entry = layers.getOrCreateRect('L', initialRect);
entry.stale = false;
- const strokes: StrokeCommittedEvent[] = [];
+ const emitStrokeCommitted = vi.fn();
+ const notifyLayerPainted = vi.fn();
const ctx = {
backend,
createPath2D: (d?: string) => ({ d }) as unknown as Path2D,
- emitStrokeCommitted: (event: StrokeCommittedEvent) => strokes.push(event),
+ emitStrokeCommitted,
invalidate: vi.fn(),
layers,
- notifyLayerPainted: vi.fn(),
+ notifyLayerPainted,
} as unknown as ToolContext;
const session = createStrokeSession({
clipMask: null,
@@ -137,13 +138,13 @@ describe('strokeSession: content-sized cache growth', () => {
thinning: 0,
tool: 'brush',
});
- return { entry, session, strokes };
+ return { emitStrokeCommitted, entry, notifyLayerPainted, session };
};
it('grows an EMPTY (brand-new) paint cache to the stroke bounds on the first stroke', () => {
- const { entry, session, strokes } = makeSession({ height: 0, width: 0, x: 0, y: 0 });
+ const { entry, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });
session.addPoints([pointer(50, 60)]);
- session.commit();
+ const event = session.commit();
// The cache adopted the stroke's content bounds, snapped OUTWARD to the 64px
// growth-chunk grid — still content-sized (a couple of chunks), NOT an
@@ -167,7 +168,24 @@ describe('strokeSession: content-sized cache growth', () => {
expect(entry.surface.width).toBe(entry.rect.width);
expect(entry.surface.height).toBe(entry.rect.height);
// The committed dirty rect is the same (chunk-padded) layer-local region.
- expect(strokes[0]!.dirtyRect).toEqual(entry.rect);
+ expect(event!.dirtyRect).toEqual(entry.rect);
+ });
+
+ it('returns the completed event without publishing engine side effects', () => {
+ const { emitStrokeCommitted, notifyLayerPainted, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });
+ session.addPoints([pointer(10, 10)]);
+ const event = session.commit();
+
+ expect(event).toMatchObject({ layerId: 'L', tool: 'brush' });
+ expect(event!.dirtyRect.width).toBeGreaterThan(0);
+ expect(event!.dirtyRect.height).toBeGreaterThan(0);
+ expect(emitStrokeCommitted).not.toHaveBeenCalled();
+ expect(notifyLayerPainted).not.toHaveBeenCalled();
+ });
+
+ it('returns null when the gesture produced no dirty pixels', () => {
+ const { session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });
+ expect(session.commit()).toBeNull();
});
it('grows an existing cache to the UNION of its extent and an out-of-extent stroke (negative coords included)', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
index 0fd407885c..211e492d24 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
@@ -75,8 +75,8 @@ export interface StrokeSessionConfig {
export interface StrokeSession {
/** Appends coalesced samples and repaints the accumulated stroke. */
addPoints(inputs: readonly PointerInput[]): void;
- /** Finalizes the stroke, bumps the cache version, and emits the commit event. */
- commit(): void;
+ /** Finalizes the stroke and returns the completed edit for its owner to publish. */
+ commit(): StrokeCommittedEvent | null;
/** Restores the pre-stroke pixels and drops the session without an event. */
cancel(): void;
}
@@ -254,7 +254,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession
paint(true);
const entry = layers.get(layerId);
if (!entry || !accumRect || !beforeImageData) {
- return;
+ return null;
}
const afterImageData = entry.surface.ctx.getImageData(
accumRect.x - entry.rect.x,
@@ -262,8 +262,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession
accumRect.width,
accumRect.height
);
- ctx.notifyLayerPainted(layerId);
- const event: StrokeCommittedEvent = {
+ return {
afterImageData,
beforeImageData,
dirtyRect: accumRect,
@@ -271,7 +270,6 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession
tool,
...(createdLayer ? { createdLayer } : {}),
};
- ctx.emitStrokeCommitted(event);
},
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index accc0983fd..ccda901271 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -53,6 +53,19 @@ export interface StrokeCommittedEvent {
createdLayer?: { layer: CanvasLayerContract; index: number };
}
+export interface PixelEditPatch {
+ rect: Rect;
+ before: ImageData;
+ after: ImageData;
+}
+
+export interface ControlPixelEditTransaction {
+ readonly layerId: string;
+ commitPatch(label: string, patch: PixelEditPatch): void;
+ commitStroke(event: StrokeCommittedEvent): void;
+ cancel(): void;
+}
+
/**
* A transient per-layer transform override the compositor/overlay read at render
* time (a live drag preview that never touches the mirror). The move tool sets
@@ -95,6 +108,8 @@ export interface ToolContext {
* on activate / when a layer is clicked. Absent in minimal test harnesses.
*/
beginTransformSession?(layerId: string): void;
+ /** Prepares direct or transactional pixel editing for a selected control layer. */
+ beginControlPixelEdit?(layerId: string): ControlPixelEditTransaction | null;
/** Updates the active transform session's live transform (drag or numeric edit). */
updateTransformSession?(transform: LayerTransform): void;
/**