Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(webv2): extract stroke commit from the engine composition root
joshistoast0b59e036be77
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex f0c6f2a194..fbab1dd3d4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -190,14 +190,14 @@ import {} from '@workbench/canvas-engine/transform/transformMath';import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';-import type { HistoryEntry } from './history/history';+import type { ImagePatchApply } from './history/imagePatch';import type { CanvasProjectMutation } from './mutationContracts';import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';-import { createImagePatchEntry, type ImagePatchApply } from './history/imagePatch';+import { createStrokeCommit } from './strokeCommit';import { createViewTool } from './tools/viewTool';/**@@ -745,62 +745,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC* pixel restore is needed); redo re-adds the layer, recreates a blank cache,* and re-applies the stroke's `after` pixels.*/- const createComposedPaintEntry = (- created: { layer: CanvasLayerContract; index: number },- event: StrokeCommittedEvent,- label: string- ): HistoryEntry => {- const { afterImageData, dirtyRect, layerId } = event;- const rect: Rect = { height: dirtyRect.height, width: dirtyRect.width, x: dirtyRect.x, y: dirtyRect.y };- const bytes = event.beforeImageData.data.byteLength + afterImageData.data.byteLength + 256;- return {- bytes,- label,- redo: () => {- dispatchCanvasMutation({ index: created.index, layer: created.layer, type: 'addCanvasLayer' });- // Re-create an EMPTY cache marked fresh so the async rasterize pass can't- // clobber the restored stroke; `applyImagePatch` grows it to the stroke's- // content bounds and writes the `after` pixels.- const entry = layerCache.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });- entry.stale = false;- applyImagePatch(layerId, rect, afterImageData);- },- undo: () => {- dispatchCanvasMutation({ ids: [layerId], type: 'removeCanvasLayers' });- },- };- };-- 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()) {- mutationPort.commitEdit({ kind: 'paint' });- 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);- }- };+ const { commitOrdinaryStroke } = createStrokeCommit({+ applyImagePatch,+ commitPaintEdit: () => mutationPort.commitEdit({ kind: 'paint' }),+ dispatchCanvasMutation,+ endNudgeBurst,+ history,+ layerCache,+ markLayerDirty: (layerId) => bitmapStore.markLayerDirty(layerId),+ notifyLayerPainted,+ strokeListeners,+ });// ---- Selection (transient interaction state) + marching ants ------------//diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.tsnew file mode 100644index 0000000000..0b7ec66320--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts@@ -0,0 +1,122 @@+import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';++import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';++import { createStrokeCommit, type CreateStrokeCommitDeps } from './strokeCommit';++/** Dimensions must match the event's dirty rect — `createImagePatchEntry` asserts it. */+const imageData = (bytes = 4): ImageData =>+ ({ data: { byteLength: bytes }, height: 4, width: 4 }) as unknown as ImageData;++const strokeEvent = (overrides: Partial<StrokeCommittedEvent> = {}): StrokeCommittedEvent =>+ ({+ afterImageData: imageData(),+ beforeImageData: imageData(),+ createdLayer: undefined,+ dirtyRect: { height: 4, width: 4, x: 1, y: 2 },+ layerId: 'layer-1',+ tool: 'brush',+ ...overrides,+ }) as unknown as StrokeCommittedEvent;++type TestDeps = {+ -readonly [K in keyof CreateStrokeCommitDeps]: CreateStrokeCommitDeps[K];+} & { history: { isApplying: ReturnType<typeof vi.fn>; push: ReturnType<typeof vi.fn> } };++let deps: TestDeps;+let listener: Mock<(event: StrokeCommittedEvent) => void>;++beforeEach(() => {+ listener = vi.fn<(event: StrokeCommittedEvent) => void>();+ deps = {+ applyImagePatch: vi.fn(),+ commitPaintEdit: vi.fn(),+ dispatchCanvasMutation: vi.fn(() => true),+ endNudgeBurst: vi.fn(),+ history: { isApplying: vi.fn(() => false), push: vi.fn() },+ layerCache: { getOrCreateRect: vi.fn(() => ({ stale: true })) } as unknown as CreateStrokeCommitDeps['layerCache'],+ markLayerDirty: vi.fn(),+ notifyLayerPainted: vi.fn(),+ strokeListeners: new Set<(event: StrokeCommittedEvent) => void>([listener]),+ } as unknown as TestDeps;+});++describe('commitOrdinaryStroke', () => {+ it('ends the nudge burst, repaints, and marks the layer dirty before recording history', () => {+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());+ expect(deps.endNudgeBurst).toHaveBeenCalled();+ expect(deps.notifyLayerPainted).toHaveBeenCalledWith('layer-1');+ expect(deps.markLayerDirty).toHaveBeenCalledWith('layer-1');+ expect(deps.history.push).toHaveBeenCalledTimes(1);+ });++ it('labels the entry by the committing tool', () => {+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ tool: 'eraser' } as Partial<StrokeCommittedEvent>));+ expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ label: 'Eraser stroke' });++ deps.history.push.mockClear();+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());+ expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ label: 'Brush stroke' });+ });++ it('records no history while a replay is applying, but still repaints and notifies', () => {+ deps.history.isApplying = vi.fn(() => true);+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());+ expect(deps.history.push).not.toHaveBeenCalled();+ expect(deps.commitPaintEdit).not.toHaveBeenCalled();+ expect(deps.notifyLayerPainted).toHaveBeenCalled();+ expect(listener).toHaveBeenCalled();+ });++ it('fans the event out to every subscriber', () => {+ const second = vi.fn<(event: StrokeCommittedEvent) => void>();+ deps.strokeListeners = new Set<(event: StrokeCommittedEvent) => void>([listener, second]);+ const event = strokeEvent();+ createStrokeCommit(deps).commitOrdinaryStroke(event);+ expect(listener).toHaveBeenCalledWith(event);+ expect(second).toHaveBeenCalledWith(event);+ });+});++describe('a stroke that auto-created its layer', () => {+ const created = { index: 2, layer: { id: 'layer-1' } as never };++ it('undoes by removing the layer, not just the pixels', () => {+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));+ const entry = deps.history.push.mock.calls[0]?.[0] as { undo(): void };+ entry.undo();+ expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({ ids: ['layer-1'], type: 'removeCanvasLayers' });+ });++ it('redoes by re-adding the layer at its index, then writing the pixels back', () => {+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));+ const entry = deps.history.push.mock.calls[0]?.[0] as { redo(): void };+ entry.redo();+ expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({+ index: 2,+ layer: created.layer,+ type: 'addCanvasLayer',+ });+ expect(deps.applyImagePatch).toHaveBeenCalledWith(+ 'layer-1',+ { height: 4, width: 4, x: 1, y: 2 },+ expect.anything()+ );+ });++ it('marks the re-created cache fresh so an async rasterize cannot clobber the restored stroke', () => {+ const entry_ = { stale: true };+ deps.layerCache = { getOrCreateRect: vi.fn(() => entry_) } as unknown as CreateStrokeCommitDeps['layerCache'];+ createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));+ const entry = deps.history.push.mock.calls[0]?.[0] as { redo(): void };+ entry.redo();+ expect(entry_.stale).toBe(false);+ });++ it('sizes the entry from both pixel buffers plus overhead', () => {+ createStrokeCommit(deps).commitOrdinaryStroke(+ strokeEvent({ afterImageData: imageData(10), beforeImageData: imageData(6), createdLayer: created } as never)+ );+ expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ bytes: 6 + 10 + 256 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsnew file mode 100644index 0000000000..dde4e20a53--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -0,0 +1,97 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { History, HistoryEntry } from '@workbench/canvas-engine/history/history';+import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';+import type { Rect } from '@workbench/canvas-engine/types';++import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';++export interface CreateStrokeCommitDeps {+ readonly history: History;+ readonly layerCache: LayerCacheStore;+ readonly applyImagePatch: ImagePatchApply;+ readonly dispatchCanvasMutation: (mutation: CanvasProjectMutation) => boolean;+ readonly endNudgeBurst: () => void;+ readonly notifyLayerPainted: (layerId: string) => void;+ readonly markLayerDirty: (layerId: string) => void;+ readonly commitPaintEdit: () => void;+ readonly strokeListeners: ReadonlySet<(event: StrokeCommittedEvent) => void>;+}++export interface StrokeCommit {+ /** Records one committed tool stroke: persistence, history, then subscriber fanout. */+ commitOrdinaryStroke(event: StrokeCommittedEvent): void;+}++/**+ * Turns a committed stroke into its durable consequences.+ *+ * A stroke that auto-created its own layer cannot be undone as a plain pixel+ * patch — undo has to remove the layer too — so those get a composed history+ * entry that pairs the layer mutation with the pixel write. Ordinary strokes+ * take the pixel-patch path.+ */+export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit => {+ const { applyImagePatch, dispatchCanvasMutation, history, layerCache } = deps;++ const createComposedPaintEntry = (+ created: { layer: CanvasLayerContract; index: number },+ event: StrokeCommittedEvent,+ label: string+ ): HistoryEntry => {+ const { afterImageData, dirtyRect, layerId } = event;+ const rect: Rect = { height: dirtyRect.height, width: dirtyRect.width, x: dirtyRect.x, y: dirtyRect.y };+ const bytes = event.beforeImageData.data.byteLength + afterImageData.data.byteLength + 256;+ return {+ bytes,+ label,+ redo: () => {+ dispatchCanvasMutation({ index: created.index, layer: created.layer, type: 'addCanvasLayer' });+ // Re-create an EMPTY cache marked fresh so the async rasterize pass can't+ // clobber the restored stroke; `applyImagePatch` grows it to the stroke's+ // content bounds and writes the `after` pixels.+ const entry = layerCache.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });+ entry.stale = false;+ applyImagePatch(layerId, rect, afterImageData);+ },+ undo: () => {+ dispatchCanvasMutation({ ids: [layerId], type: 'removeCanvasLayers' });+ },+ };+ };++ return {+ commitOrdinaryStroke: (event) => {+ // A fresh stroke ends any open nudge-coalescing burst.+ deps.endNudgeBurst();+ deps.notifyLayerPainted(event.layerId);+ // Persistence first: mark the layer dirty so a debounced upload fires even+ // when no external subscriber is attached.+ deps.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()) {+ deps.commitPaintEdit();+ 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 deps.strokeListeners) {+ listener(event);+ }+ },+ };+};