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
perf(canvas): batch config edits and bound value-edit folding
Josh Corbett5bdc4fdd7d54
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.tsindex f639e8293c..a613a63361 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts@@ -387,13 +387,17 @@ const valueEdits = new WeakMap<CanvasStackForests, ValueEditRecord>();/** How many consecutive value edits a consumer that fell behind may still fold instead of diffing forests. */const MAX_FOLDED_VALUE_EDITS = 16;+/** Folding up to this many replaced nodes always beats a forest diff, however small the document. */+const MIN_FOLDED_ENTRIES = 64;/*** The value edits that lead from `previous` to `next`, folded oldest first, or null when any step between them- * restructured the forests or was not recorded.+ * restructured the forests or was not recorded, or when folding would touch more than a quarter of the nodes (a+ * forest diff is then cheaper).*/export const valueEditBetween = (previous: CanvasStackForests, next: CanvasStackForests): CanvasValueEdit | null => {const steps: CanvasValueEdit[] = [];+ let entries = 0;let current = next;while (current !== previous) {const record = valueEdits.get(current);@@ -402,6 +406,10 @@ export const valueEditBetween = (previous: CanvasStackForests, next: CanvasStackreturn null;}steps.push(record.changes);+ entries += record.changes.size;+ if (steps.length > 1 && entries > Math.max(MIN_FOLDED_ENTRIES, indexStacks(next).byId.size / 4)) {+ return null;+ }current = from;}if (steps.length <= 1) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.tsindex 59131b51ed..81abd9a7ad 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts@@ -9,7 +9,11 @@ import type {} from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';@@ -600,6 +604,25 @@ describe('createDocumentMirror: value edits through the reducer', () => {expect(getForestDiffCount()).toBe(0);});+ it('applies a batched config update as one value edit, composing repeated ids in order', () => {+ const { apply, callbacks, mirror } = setup(makeDoc([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')]));+ const invert = [{ id: 'inv', isEnabled: true, type: 'invert' as const }];++ apply({+ type: 'updateCanvasLayerConfigs',+ updates: [+ { config: { adjustments: invert, layerType: 'raster' }, id: 'a' },+ { config: { isTransparencyLocked: true, layerType: 'raster' }, id: 'c' },+ { config: { isTransparencyLocked: true, layerType: 'raster' }, id: 'a' },+ ],+ });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'c'], [], false);+ expect(callbacks.onLayersChanged).toHaveBeenCalledOnce();+ expect(getForestDiffCount()).toBe(0);+ const a = getDocumentLeaves(mirror.getDocument()!).find((leaf) => leaf.id === 'a') as CanvasRasterLayerContractV2;+ expect(a).toMatchObject({ adjustments: invert, isTransparencyLocked: true });+ });+it('reports only the descendants whose inherited flags moved when a group flag flips', () => {const doc = makeDoc([groupContract('g', [rasterLayer('a'), groupContract('h', [rasterLayer('b')], { isEnabled: false })]),@@ -613,6 +636,39 @@ describe('createDocumentMirror: value edits through the reducer', () => {expect(getForestDiffCount()).toBe(0);});+ it('reports the descendants of a group whose lock or display visibility flips', () => {+ const doc = makeDoc([+ groupContract('g', [rasterLayer('a'), rasterLayer('b')]),+ groupContract('m', [layerContract('mask', 'inpaint_mask')]),+ ]);+ const { apply, callbacks } = setup(doc);++ apply({ id: 'g', patch: { isLocked: true }, type: 'updateCanvasLayer' });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'b'], [], false);+ apply({ type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['mask'], [], false);+ expect(getForestDiffCount()).toBe(0);+ });++ it.each<[string, CanvasProjectMutation]>([+ ['blend mode', { id: 'g', patch: { blendMode: 'multiply' }, type: 'updateCanvasLayer' }],+ [+ 'adjustments',+ {+ config: { adjustments: [{ id: 'ga', isEnabled: true, type: 'invert' }], layerType: 'group' },+ id: 'g',+ type: 'updateCanvasLayerConfig',+ },+ ],+ ])('recomposites a group whose %s changes without reporting a pixel change', (_, mutation) => {+ const { apply, callbacks } = setup(makeDoc([groupContract('g', [rasterLayer('a')]), rasterLayer('c')]));++ apply(mutation);+ expect(callbacks.onLayersRecomposite).toHaveBeenLastCalledWith(['a']);+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();+ expect(getForestDiffCount()).toBe(0);+ });+it('fans group appearance edits out on the recomposite channel and stays silent on a rename', () => {const { apply, callbacks } = setup(makeDoc([groupContract('g', [rasterLayer('a'), rasterLayer('b')]), rasterLayer('c')])diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 1b7d89ff41..3b962da173 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -172,6 +172,10 @@ const diffValueEdit = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex, ediconst reflagged: string[] = [];const adjusted: string[] = [];for (const [id, { after, before }] of edit) {+ // Folded steps can hand a node back unchanged.+ if (before === after) {+ continue;+ }if (isGroupNode(after) && isGroupNode(before)) {if (groupFlagsChanged(before, after)) {reflagged.push(id);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.tsindex 1d0cedde7c..01104daae9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts@@ -92,6 +92,20 @@ describe('document tree', () => {expect(valueEditBetween(before, removeNodes(moved, new Set(['r4'])))).toBeNull();});+ it('stops folding once the folded edits would touch more than a quarter of a large forest', () => {+ const before = stacksFrom(Array.from({ length: 400 }, (_, index) => layer(`l${index}`)));+ const fade = (stacks: CanvasStackForests, ids: readonly string[], opacity: number) =>+ updateNodeValues(stacks, new Map(ids.map((id) => [id, (node) => ({ ...node, opacity })])));+ const first = Array.from({ length: 40 }, (_, index) => `l${index}`);+ const once = fade(before, first, 0.5);++ // 80 replaced nodes across two steps stay within a quarter of 400; 110 do not.+ expect(valueEditBetween(before, fade(once, first, 0.4))?.size).toBe(40);+ const wide = Array.from({ length: 70 }, (_, index) => `l${index + 100}`);+ expect(valueEditBetween(before, fade(once, wide, 0.4))).toBeNull();+ expect(valueEditBetween(once, fade(once, wide, 0.4))?.size).toBe(70);+ });+it('removes subtrees and shares the untouched forests', () => {const before = stacks();const after = removeNodes(before, new Set(['g2', 'r4']));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.tsindex fdb1995376..1e3334a9a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts@@ -1,4 +1,5 @@import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { GroupSurfaceContent } from '@workbench/canvas-engine/render/groupCompositeScopes';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -9,6 +10,8 @@ import {} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';import type * as RasterControllerModule from './controllers/rasterController';@@ -49,14 +52,30 @@ const fakeCanvas = (): HTMLCanvasElement => {};const createEngine = (bitmapStore?: BitmapStore) => {- const document = documentFrom([groupContract('group', [layerContract('layer')], { opacity: 0.5 })]);- const canvas = { document, documentRevision: 0, snapshots: [], version: 3 };+ const document = documentFrom([+ groupContract('group', [layerContract('layer')], { opacity: 0.5 }),+ layerContract('other'),+ ]);+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document,+ type: 'replaceCanvasDocument',+ });+ const listeners = new Set<() => void>();const mutationPort = {commitEdit: () => undefined,dispatch: () => false,- getCanvasState: () => canvas,- subscribe: () => () => undefined,+ getCanvasState: () => project.canvas,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },} as unknown as CanvasProjectMutationPort;+ const apply = (mutation: CanvasProjectMutation): void => {+ project = applyCanvasProjectMutation(project, mutation);+ for (const listener of listeners) {+ listener();+ }+ };const { engine } = createCanvasEngine({backend: createTestStubRasterBackend(),bitmapStore,@@ -72,13 +91,14 @@ const createEngine = (bitmapStore?: BitmapStore) => {raster.layers.getOrCreateRect('layer', RECT);raster.layers.publishPixels('layer');const leaves = compileDocumentLeaves(document);+ const start = leaves.findIndex((leaf) => leaf.id === 'layer');raster.groups.get(- { adjustments: [], blendMode: 'normal', children: [], end: 1, id: 'group', opacity: 0.5, start: 0 },- leaves,- leaves.map((leaf) => leaf.worldTransform),+ { adjustments: [], blendMode: 'normal', children: [], end: start + 1, id: 'group', opacity: 0.5, start },+ leaves.slice(start, start + 1),+ [leaves[start]!.worldTransform],NO_GROUP_CONTENT);- return { engine, raster };+ return { apply, engine, raster };};const offscreenDocument = () =>@@ -204,3 +224,14 @@ describe('engine raster resource lifecycle', () => {expect(bitmap.close).toHaveBeenCalledOnce();});});++describe('engine group surfaces', () => {+ it('releases a deleted group surface', () => {+ const { apply, engine, raster } = createEngine();+ expect(raster.memory.snapshot().groupBytes).toBeGreaterThan(0);++ apply({ ids: ['group'], type: 'removeCanvasLayers' });+ expect(raster.memory.snapshot().groupBytes).toBe(0);+ engine.lifecycle.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.tsindex 70ae6e2204..b803f2ca0e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts@@ -9,7 +9,7 @@ import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';import type { LayerCacheStore } from './layerCache';import type { RasterBackend, RasterSurface } from './raster';-import { compositeDocument, prepareComposite, type CompositeOptions, type CompositePreparation } from './compositor';+import { compositeDocument, reusePreparation, type CompositeOptions, type CompositePreparation } from './compositor';/** An RGBA sample, channels in `[0, 255]`. */export interface RgbaSample {@@ -71,9 +71,7 @@ export const createColorSampler = (backend: RasterBackend): ColorSampler => {}scratch ??= backend.createSurface(1, 1);- if (preparation?.document !== doc || preparation.grouped !== !!providers.groupSurface) {- preparation = prepareComposite(doc, providers);- }+ preparation = reusePreparation(preparation, doc, { backend, ...providers });const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -px, f: -py };// Use canonical compositing for placement and display effects, omitting checkerboard/staged previews to// retain transparent empty space.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.tsindex f40816f488..95b6f69fe2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts@@ -133,15 +133,17 @@ describe('frame description over 2,000 nodes', () => {viewport,});const screen = backend.createSurface(100, 100);- const prepare = vi.spyOn(compositor, 'prepareComposite');+ const composite = vi.spyOn(compositor, 'compositeDocument');+ const description = () => composite.mock.calls.at(-1)![4].preparation;const bounds = vi.spyOn(frameDemand, 'committedLeafBounds');const document = createLargeTreeDocument(2_000);frame.draw(screen, document, identity(), null, null);const leafCount = bounds.mock.calls.length;+ const first = description();expect(leafCount).toBeGreaterThan(1_000);frame.draw(screen, document, identity(), null, null, { kind: 'none' });- expect(prepare).toHaveBeenCalledTimes(1);+ expect(description()?.leaves).toBe(first?.leaves);expect(bounds).toHaveBeenCalledTimes(leafCount);const edited = {@@ -149,7 +151,7 @@ describe('frame description over 2,000 nodes', () => {stacks: updateNodeValues(document.stacks, new Map([['l7', (node) => ({ ...node, opacity: 0.5 })]])),};frame.draw(screen, edited, identity(), null, null);- expect(prepare).toHaveBeenCalledTimes(2);+ expect(description()?.document).toBe(edited);expect(bounds.mock.calls.slice(leafCount).map(([leaf]) => leaf.id)).toEqual(['l7']);raster.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex d20695d054..1801a5fb0a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -17,9 +17,8 @@ import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligimport { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import {compositeDocument,- prepareComposite,+ reusePreparation,shouldSmoothAtZoom,- transformOverridesKey,type CompositeOptions,type CompositePreparation,} from '@workbench/canvas-engine/render/compositor';@@ -133,18 +132,13 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFisolationLayerId: string | null,overrides: CompositeOptions['transformOverrides']): CompositePreparation => {- if (- preparation?.document !== doc ||- preparation.isolationLayerId !== isolationLayerId ||- preparation.overridesKey !== transformOverridesKey(overrides)- ) {- preparation = prepareComposite(doc, {- groupSurface: deps.getGroupSurface,- isolationLayerId,- transformOverrides: overrides,- });- }- const plan = preparation;+ const plan = reusePreparation(preparation, doc, {+ backend: deps.backend,+ groupSurface: deps.getGroupSurface,+ isolationLayerId,+ transformOverrides: overrides,+ });+ preparation = plan;const nextMemo = new Map<string, LeafBoundsMemo>();const bounds = plan.leaves.map((leaf, index) => {const matrix = plan.matrices[index]!;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 43596943ac..d061d94dc2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -232,6 +232,13 @@ const isPreparedFor = (preparation.grouped === (!!opts.groupSurface && !isIsolated(opts)) &&preparation.overridesKey === transformOverridesKey(opts.transformOverrides);+/** Reuses `previous` while it still describes `doc` under these options, else prepares a new description. */+export const reusePreparation = (+ previous: CompositePreparation | null | undefined,+ doc: CanvasDocumentContractV3,+ opts: CompositeOptions+): CompositePreparation => (isPreparedFor(previous, doc, opts) ? previous : prepareComposite(doc, opts));+const setTransformFromMat = (ctx: Ctx, m: Mat2d): void => {ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);};@@ -517,7 +524,7 @@ export const compositeDocument = (view: Mat2d,opts: CompositeOptions): void => {- const plan = isPreparedFor(opts.preparation, doc, opts) ? opts.preparation : prepareComposite(doc, opts);+ const plan = reusePreparation(opts.preparation, doc, opts);const targetRect: Rect = { height: target.height, width: target.width, x: 0, y: 0 };const damage = resolveDamage(plan, view, target, opts.damage);if (damage.kind === 'none') {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.tsindex 37dc4cd4a2..6c17290e5f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts@@ -132,6 +132,20 @@ describe('the move outline', () => {expect(dragged).not.toEqual(committed);});+ it('outlines the topmost of several dragged layers', () => {+ harness.state.tool = 'move';+ const doc = documentOf(['a', 'b', 'c']);+ harness.overrides.set('c', { x: 100, y: 100 });+ const onlyC = describeOverlay(doc)?.layerOutline;+ harness.overrides.set('b', { x: 50, y: 50 });+ const bAndC = describeOverlay(doc)?.layerOutline;+ harness.overrides.delete('c');+ const onlyB = describeOverlay(doc)?.layerOutline;++ expect(bAndC).toEqual(onlyB);+ expect(bAndC).not.toEqual(onlyC);+ });+it('is absent when the selected layer is gone', () => {harness.state.tool = 'move';expect(describeOverlay(documentOf([], { selectedLayerId: 'missing' }))?.layerOutline).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex 35dc25fc92..2658b80179 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -67,6 +67,7 @@ const createHarness = (doc: CanvasDocumentContractV3): Harness => {const commits: StructuralCommit[] = [];const stores = createEngineStores();const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,backend: null as never,commitStructural: (label, forward, inverse) => {commits.push({ forward, inverse, label });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex 2ae5b45078..261c602d84 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -97,6 +97,7 @@ const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {const overlayCursors: unknown[] = [];const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,backend,commitStructural: vi.fn(),captureInsertionAnchor: createTestInsertionAnchorCapture('p'),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex 35e5c0593a..914275ee92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -70,6 +70,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {const stores = createEngineStores();let idCounter = 0;const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,backend: null as never,commitStructural: (label, forward, inverse) => {commits.push({ forward, inverse, label });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex c365ce586c..f674b98e9f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -131,6 +131,7 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =stores.bboxGrid.set(options.bboxGrid);}const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,backend: null as never,commitFloatingSelection: commitFloat,commitStructural: (label, forward, inverse) => {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.tsindex 6fdc558e78..e076f5be2f 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@@ -144,6 +144,10 @@ const createHarness = (let idCounter = 0;const ctx: ToolContext = {+ scheduleFrame: (task) => {+ task();+ return () => undefined;+ },backend,...(beginPixelEdit ? { beginPixelEdit } : {}),captureInsertionAnchor: createTestInsertionAnchorCapture('p'),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex 312e0907c0..a45b2971e1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -70,6 +70,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {const layers = createLayerCacheStore(backend);let idCounter = 0;const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,backend,commitStructural: (label, forward, inverse) => {commits.push({ forward, inverse, label });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.tsindex 732f560ca9..cd8441bac8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts@@ -211,7 +211,7 @@ const sweep = (): PointerInput[] => {describe('incremental compositing produces the same coverage as recompositing everything', () => {// Band updates and incremental before-snapshots must preserve interior coverage. Boundary antialiasing may// differ by subpixels across batches; interior gaps or compounded opacity may not. Deliberately shrinking the- // band by 30px fails all four cases.+ // band by 30px fails every case.const cases: {batchSize: number;batchesPerFrame?: number;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.tsindex 3dd1776044..4ef0524cca 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@@ -3,12 +3,19 @@ import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engimport type { ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';+import * as freehand from '@workbench/canvas-engine/freehand';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createStrokeSession } from '@workbench/canvas-engine/tools/strokeSession';import { describe, expect, it, vi } from 'vitest';+/** Renders a scheduled stroke frame immediately; frame timing is covered by the engine tests. */+const runFrameNow = (task: () => void): (() => void) => {+ task();+ return () => undefined;+};+const pointer = (x: number, y: number): PointerInput => ({buttons: 1,documentPoint: { x, y },@@ -55,6 +62,7 @@ const runStroke = (opts: { withMask: boolean }) => {invalidate: vi.fn(),layers,notifyLayerPainted,+ scheduleFrame: runFrameNow,} as unknown as ToolContext;// Only the scratch is created after this point.@@ -130,6 +138,7 @@ describe('strokeSession: bbox-clipped painting', () => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;created.length = 0;@@ -213,6 +222,7 @@ describe('strokeSession: content-sized cache growth', () => {invalidate: vi.fn(),layers,notifyLayerPainted,+ scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({clipMask: null,@@ -326,6 +336,7 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({clipMask: null,@@ -379,6 +390,7 @@ describe('incremental "before" snapshot', () => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({color: '#ff0000',@@ -461,6 +473,7 @@ describe('strokeSession: pressure-dependent opacity', () => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;created.length = 0;@@ -550,6 +563,7 @@ describe('layer transforms', () => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({color: '#ff0000',@@ -599,6 +613,7 @@ describe('tap collapse', () => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({clipMask: null,@@ -735,3 +750,42 @@ describe('frame-coalesced rendering', () => {expect(onRenderError).toHaveBeenCalledWith(failure);});});++describe('strokeSession: incremental decimation', () => {+ it('never re-decimates the whole stroke while it renders frame by frame', () => {+ const decimate = vi.spyOn(freehand, 'decimateSamples');+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', 400, 100);+ const ctx = {+ backend,+ createPath2D: () =>+ ({ closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} }) as unknown as Path2D,+ emitStrokeCommitted: vi.fn(),+ invalidate: vi.fn(),+ layers,+ notifyLayerPainted: vi.fn(),+ scheduleFrame: runFrameNow,+ } as unknown as ToolContext;+ const session = createStrokeSession({+ clipMask: null,+ color: '#ff0000',+ composite: 'source-over',+ ctx,+ hardness: 1,+ layerId: 'L',+ opacity: 1,+ pressureOpacity: false,+ size: 8,+ thinning: 0,+ tool: 'brush',+ });++ for (let x = 0; x < 300; x += 1) {+ session.addPoints([pointer(x, 50)]);+ }+ session.commit();+ expect(decimate).not.toHaveBeenCalled();+ decimate.mockRestore();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex f68b817979..142f54d696 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -117,16 +117,6 @@ const padToChunk = (r: Rect, chunk: number): Rect => {return { height: bottom - y, width: right - x, x, y };};-/** Runs `task` before the next animation frame; synchronous where no frames exist. */-const scheduleAnimationFrame = (task: () => void): (() => void) => {- if (typeof requestAnimationFrame !== 'function') {- task();- return () => undefined;- }- const frame = requestAnimationFrame(() => task());- return () => cancelAnimationFrame(frame);-};-/** The 2D context flavour a {@link RasterSurface} exposes. */type SurfaceContext = RasterSurface['ctx'];@@ -291,7 +281,6 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// Below the travel threshold, preserve the first aim point as a round dab rather than a short capsule.const tapCollapseLength = Math.max(2, localSize * 0.25);let travel = 0;- const scheduleFrame = ctx.scheduleFrame ?? scheduleAnimationFrame;let cancelScheduledFrame: (() => void) | null = null;let closed = false;// Before pixels cover `accumRect` in stable layer-local coordinates, unaffected by backing-store origin shifts.@@ -559,7 +548,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionreturn;}let ran = false;- const cancel = scheduleFrame(() => {+ const cancel = ctx.scheduleFrame(() => {ran = true;renderFrame();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 7f6726b124..e0d6701db6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -74,11 +74,8 @@ export interface ToolContext {getSelectedLayerIds?(): readonly string[];/** Requests a re-render for the given flags. */invalidate(payload: InvalidatePayload): void;- /**- * Runs `task` once before the next composited frame so its invalidations render in that frame; returns a cancel.- * Absent, tools fall back to `requestAnimationFrame`, or run synchronously without one.- */- scheduleFrame?(task: () => void): () => void;+ /** Runs `task` once before the next composited frame so its invalidations render in that frame; returns a cancel. */+ scheduleFrame(task: () => void): () => void;/** Reducer bridge. Painting tools use it for the single gesture-start `addCanvasLayer`. */dispatch(action: CanvasProjectMutation): void;/** Where a layer the tool creates lands: above `aboveId` when it belongs to `stack`, else the stack top. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 5095d5517a..702805664c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -142,6 +142,7 @@ const createHarness = (doc: CanvasDocumentContractV3, zoom = 1, float?: Floating};const ctx: ToolContext = {+ scheduleFrame: () => () => undefined,applyTransform: () => {state.applyCount += 1;},diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 73073e345a..b34597a2ca 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -872,10 +872,13 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProif (!applicable) {return document;}- return mutation.updates.reduce(- (current, update) => mapNode(current, update.id, (node) => patchLayerConfig(node, update.config)),- document- );+ // One value edit for the batch; repeated ids apply their patches in order.+ const patches = new Map<string, (node: CanvasNodeContract) => CanvasNodeContract>();+ for (const { config, id } of mutation.updates) {+ const earlier = patches.get(id);+ patches.set(id, (node) => patchLayerConfig(earlier ? earlier(node) : node, config));+ }+ return mapNodes(document, patches);});case 'convertCanvasLayer': {if (mutation.layer.type !== mutation.targetType) {