Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): add guarded canvas operation sessions
joshistoast507fbcaa713c
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.tsnew file mode 100644index 0000000000..3be63215dd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts@@ -0,0 +1,298 @@+import type { CanvasRasterLayerContractV2 } from '@workbench/types';++import { describe, expect, it, vi } from 'vitest';++import type { LayerExportGuard } from './engine';++import { createCanvasOperationController } from './canvasOperationController';++const layer: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: 'layer-1',+ isEnabled: true,+ isLocked: false,+ name: 'Layer',+ opacity: 1,+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+};++const guard: LayerExportGuard = {+ cacheVersion: 1,+ documentGeneration: 1,+ layer,+ layerId: layer.id,+ projectId: 'project-1',+};++const createDeferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (cause: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++const filterIdentity = { kind: 'filter' as const, layerId: layer.id, projectId: 'project-1' };+const selectObjectIdentity = { kind: 'select-object' as const, layerId: layer.id, projectId: 'project-1' };++describe('createCanvasOperationController', () => {+ it('replaces the active operation and prevents its stale session from affecting the replacement', async () => {+ const firstWork = createDeferred<string>();+ const firstCleanup = vi.fn();+ const secondCleanup = vi.fn();+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const first = controller.start({ cleanupPreview: firstCleanup, guard, identity: filterIdentity })!;+ const publishFirst = vi.fn();+ const pending = first.run(() => firstWork.promise, publishFirst);+ firstCleanup.mockClear();++ const second = controller.start({ cleanupPreview: secondCleanup, guard, identity: selectObjectIdentity })!;++ expect(firstCleanup).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });+ first.cancel();+ firstWork.resolve('old');+ await expect(pending).resolves.toBe('stale');+ expect(publishFirst).not.toHaveBeenCalled();+ expect(secondCleanup).not.toHaveBeenCalled();+ expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });+ second.cancel();+ });++ it('reset aborts work and clears the preview while keeping the operation active', async () => {+ const work = createDeferred<string>();+ const cleanupPreview = vi.fn();+ let signal: AbortSignal | undefined;+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ const pending = session.run((requestSignal) => {+ signal = requestSignal;+ return work.promise;+ }, vi.fn());+ cleanupPreview.mockClear();++ session.reset();++ expect(signal?.aborted).toBe(true);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toEqual({+ error: null,+ identity: filterIdentity,+ phase: 'ready',+ status: 'active',+ });+ work.resolve('late');+ await expect(pending).resolves.toBe('stale');+ });++ it('cancel aborts work, clears the preview, and closes the operation', async () => {+ const work = createDeferred<string>();+ const cleanupPreview = vi.fn();+ let signal: AbortSignal | undefined;+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ const pending = session.run((requestSignal) => {+ signal = requestSignal;+ return work.promise;+ }, vi.fn());+ cleanupPreview.mockClear();++ session.cancel();++ expect(signal?.aborted).toBe(true);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toEqual({ status: 'idle' });+ work.resolve('late');+ await expect(pending).resolves.toBe('stale');+ });++ it('dispose aborts work, clears the preview, and stops notifications', async () => {+ const work = createDeferred<string>();+ const cleanupPreview = vi.fn();+ let signal: AbortSignal | undefined;+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ const pending = session.run((requestSignal) => {+ signal = requestSignal;+ return work.promise;+ }, vi.fn());+ const listener = vi.fn();+ controller.subscribe(listener);+ cleanupPreview.mockClear();+ listener.mockClear();++ controller.dispose();++ expect(signal?.aborted).toBe(true);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toEqual({ status: 'idle' });+ expect(listener).not.toHaveBeenCalled();+ expect(controller.start({ cleanupPreview, guard, identity: filterIdentity })).toBeNull();+ work.resolve('late');+ await expect(pending).resolves.toBe('stale');+ });++ it('publishes only the latest request when completions arrive out of order', async () => {+ const older = createDeferred<string>();+ const newer = createDeferred<string>();+ const publishOlder = vi.fn();+ const publishNewer = vi.fn();+ const signals: AbortSignal[] = [];+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview: vi.fn(), guard, identity: filterIdentity })!;++ const olderPending = session.run((signal) => {+ signals.push(signal);+ return older.promise;+ }, publishOlder);+ const newerPending = session.run((signal) => {+ signals.push(signal);+ return newer.promise;+ }, publishNewer);+ newer.resolve('newer');+ await expect(newerPending).resolves.toBe('published');+ older.resolve('older');+ await expect(olderPending).resolves.toBe('stale');++ expect(signals[0]?.aborted).toBe(true);+ expect(publishOlder).not.toHaveBeenCalled();+ expect(publishNewer).toHaveBeenCalledWith('newer');+ });++ it('rejects an invalid or mismatched export guard without replacing the active operation', () => {+ const isGuardCurrent = vi.fn((candidate: LayerExportGuard) => candidate === guard);+ const controller = createCanvasOperationController({ isGuardCurrent });+ const session = controller.start({ cleanupPreview: vi.fn(), guard, identity: filterIdentity });+ const staleGuard = { ...guard, cacheVersion: 2 };++ expect(session).not.toBeNull();+ expect(controller.start({ cleanupPreview: vi.fn(), guard: staleGuard, identity: filterIdentity })).toBeNull();+ expect(+ controller.start({ cleanupPreview: vi.fn(), guard, identity: { ...filterIdentity, layerId: 'other' } })+ ).toBeNull();+ expect(+ controller.start({ cleanupPreview: vi.fn(), guard, identity: { ...filterIdentity, projectId: 'other' } })+ ).toBeNull();+ expect(controller.getSnapshot()).toMatchObject({ identity: filterIdentity, status: 'active' });+ });++ it('suppresses a result when its guard becomes invalid during work', async () => {+ let current = true;+ const work = createDeferred<string>();+ const publish = vi.fn();+ const cleanupPreview = vi.fn();+ const controller = createCanvasOperationController({ isGuardCurrent: () => current });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ const pending = session.run(() => work.promise, publish);+ cleanupPreview.mockClear();++ current = false;+ work.resolve('stale');++ await expect(pending).resolves.toBe('stale');+ expect(publish).not.toHaveBeenCalled();+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toEqual({ status: 'idle' });+ });++ it.each([+ [+ 'source',+ (controller: ReturnType<typeof createCanvasOperationController>) =>+ controller.invalidateSource('project-1', layer.id),+ ],+ [+ 'layer',+ (controller: ReturnType<typeof createCanvasOperationController>) =>+ controller.invalidateLayer('project-1', layer.id),+ ],+ [+ 'project',+ (controller: ReturnType<typeof createCanvasOperationController>) => controller.invalidateProject('project-1'),+ ],+ [+ 'document',+ (controller: ReturnType<typeof createCanvasOperationController>) => controller.invalidateDocument('project-1'),+ ],+ ])('%s invalidation aborts and cleans the matching operation', async (_reason, invalidate) => {+ const work = createDeferred<string>();+ const cleanupPreview = vi.fn();+ let signal: AbortSignal | undefined;+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ const pending = session.run((requestSignal) => {+ signal = requestSignal;+ return work.promise;+ }, vi.fn());+ cleanupPreview.mockClear();++ invalidate(controller);++ expect(signal?.aborted).toBe(true);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(controller.getSnapshot()).toEqual({ status: 'idle' });+ work.resolve('late');+ await expect(pending).resolves.toBe('stale');+ });++ it('ignores invalidation for a different target', () => {+ const cleanupPreview = vi.fn();+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ controller.start({ cleanupPreview, guard, identity: filterIdentity });++ controller.invalidateSource('project-1', 'other-layer');+ controller.invalidateLayer('other-project', layer.id);+ controller.invalidateProject('other-project');+ controller.invalidateDocument('other-project');++ expect(cleanupPreview).not.toHaveBeenCalled();+ expect(controller.getSnapshot()).toMatchObject({ identity: filterIdentity, status: 'active' });+ });++ it('suppresses a late result after the operation closes', async () => {+ const work = createDeferred<string>();+ const publish = vi.fn();+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview: vi.fn(), guard, identity: selectObjectIdentity })!;+ const pending = session.run(() => work.promise, publish);++ controller.cancel();+ work.resolve('late');++ await expect(pending).resolves.toBe('stale');+ expect(publish).not.toHaveBeenCalled();+ expect(controller.getSnapshot()).toEqual({ status: 'idle' });+ });++ it('publishes an error and allows the same operation to retry', async () => {+ const cleanupPreview = vi.fn();+ const listener = vi.fn();+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });+ const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;+ controller.subscribe(listener);++ await expect(session.run(() => Promise.reject(new Error('graph failed')), vi.fn())).resolves.toBe('error');++ expect(controller.getSnapshot()).toEqual({+ error: 'graph failed',+ identity: filterIdentity,+ phase: 'error',+ status: 'active',+ });++ const publish = vi.fn();+ await expect(session.run(() => Promise.resolve('recovered'), publish)).resolves.toBe('published');+ expect(publish).toHaveBeenCalledWith('recovered');+ expect(controller.getSnapshot()).toEqual({+ error: null,+ identity: filterIdentity,+ phase: 'ready',+ status: 'active',+ });+ expect(listener).toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.tsnew file mode 100644index 0000000000..1e920b8231--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts@@ -0,0 +1,248 @@+import type { LayerExportGuard } from './engine';++export type CanvasOperationIdentity =+ | { kind: 'select-object'; projectId: string; layerId: string }+ | { kind: 'filter'; projectId: string; layerId: string };++export type CanvasOperationState =+ | { status: 'idle' }+ | {+ status: 'active';+ identity: CanvasOperationIdentity;+ phase: 'ready' | 'running' | 'error';+ error: string | null;+ };++export type CanvasOperationRunResult = 'published' | 'stale' | 'error';++export interface CanvasOperationSession {+ run<T>(+ work: (signal: AbortSignal) => Promise<T>,+ publish: (result: T) => void | Promise<void>+ ): Promise<CanvasOperationRunResult>;+ reset(): void;+ cancel(): void;+}++export interface StartCanvasOperationOptions {+ identity: CanvasOperationIdentity;+ guard: LayerExportGuard;+ cleanupPreview(): void;+}++export interface CanvasOperationController {+ getSnapshot(): CanvasOperationState;+ subscribe(listener: () => void): () => void;+ start(options: StartCanvasOperationOptions): CanvasOperationSession | null;+ reset(): void;+ cancel(): void;+ invalidateSource(projectId: string, layerId: string): void;+ invalidateLayer(projectId: string, layerId: string): void;+ invalidateProject(projectId: string): void;+ invalidateDocument(projectId: string): void;+ dispose(): void;+}++export interface CanvasOperationControllerDeps {+ isGuardCurrent(guard: LayerExportGuard): boolean;+}++interface ActiveOperation extends StartCanvasOperationOptions {+ requestController: AbortController | null;+ requestToken: number;+}++const errorMessage = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));++export const createCanvasOperationController = (deps: CanvasOperationControllerDeps): CanvasOperationController => {+ let state: CanvasOperationState = { status: 'idle' };+ let active: ActiveOperation | null = null;+ let disposed = false;+ const listeners = new Set<() => void>();++ const publishState = (next: CanvasOperationState): void => {+ state = next;+ if (disposed) {+ return;+ }+ for (const listener of listeners) {+ listener();+ }+ };++ const cleanupPreview = (operation: ActiveOperation): void => {+ try {+ operation.cleanupPreview();+ } catch {+ // Cleanup is best-effort and must not prevent cancellation or invalidation.+ }+ };++ const close = (operation: ActiveOperation): void => {+ if (active !== operation) {+ return;+ }+ operation.requestToken += 1;+ operation.requestController?.abort();+ operation.requestController = null;+ cleanupPreview(operation);+ active = null;+ publishState({ status: 'idle' });+ };++ const reset = (operation: ActiveOperation): void => {+ if (active !== operation || disposed) {+ return;+ }+ operation.requestToken += 1;+ operation.requestController?.abort();+ operation.requestController = null;+ cleanupPreview(operation);+ publishState({ error: null, identity: operation.identity, phase: 'ready', status: 'active' });+ };++ const isGuardCurrent = (operation: ActiveOperation): boolean => {+ try {+ return deps.isGuardCurrent(operation.guard);+ } catch {+ return false;+ }+ };++ const isCurrentRequest = (operation: ActiveOperation, token: number, controller: AbortController): boolean =>+ !disposed &&+ active === operation &&+ operation.requestToken === token &&+ operation.requestController === controller &&+ !controller.signal.aborted;++ const run = async <T>(+ operation: ActiveOperation,+ work: (signal: AbortSignal) => Promise<T>,+ publish: (result: T) => void | Promise<void>+ ): Promise<CanvasOperationRunResult> => {+ if (disposed || active !== operation) {+ return 'stale';+ }+ if (!isGuardCurrent(operation)) {+ close(operation);+ return 'stale';+ }++ operation.requestToken += 1;+ const token = operation.requestToken;+ operation.requestController?.abort();+ const controller = new AbortController();+ operation.requestController = controller;+ cleanupPreview(operation);+ publishState({ error: null, identity: operation.identity, phase: 'running', status: 'active' });++ try {+ const result = await work(controller.signal);+ if (!isCurrentRequest(operation, token, controller)) {+ return 'stale';+ }+ if (!isGuardCurrent(operation)) {+ close(operation);+ return 'stale';+ }++ await publish(result);+ if (!isCurrentRequest(operation, token, controller)) {+ return 'stale';+ }+ if (!isGuardCurrent(operation)) {+ close(operation);+ return 'stale';+ }++ operation.requestController = null;+ publishState({ error: null, identity: operation.identity, phase: 'ready', status: 'active' });+ return 'published';+ } catch (cause) {+ if (!isCurrentRequest(operation, token, controller)) {+ return 'stale';+ }+ operation.requestController = null;+ publishState({ error: errorMessage(cause), identity: operation.identity, phase: 'error', status: 'active' });+ return 'error';+ }+ };++ const start = (options: StartCanvasOperationOptions): CanvasOperationSession | null => {+ if (+ disposed ||+ options.identity.projectId !== options.guard.projectId ||+ options.identity.layerId !== options.guard.layerId+ ) {+ return null;+ }+ try {+ if (!deps.isGuardCurrent(options.guard)) {+ return null;+ }+ } catch {+ return null;+ }++ if (active) {+ close(active);+ }+ const operation: ActiveOperation = {+ ...options,+ requestController: null,+ requestToken: 0,+ };+ active = operation;+ publishState({ error: null, identity: operation.identity, phase: 'ready', status: 'active' });++ return {+ cancel: () => close(operation),+ reset: () => reset(operation),+ run: (work, publish) => run(operation, work, publish),+ };+ };++ const invalidateTarget = (projectId: string, layerId?: string): void => {+ if (active?.identity.projectId === projectId && (layerId === undefined || active.identity.layerId === layerId)) {+ close(active);+ }+ };++ return {+ cancel: () => {+ if (active) {+ close(active);+ }+ },+ dispose: () => {+ if (disposed) {+ return;+ }+ disposed = true;+ if (active) {+ close(active);+ } else {+ state = { status: 'idle' };+ }+ listeners.clear();+ },+ getSnapshot: () => state,+ invalidateDocument: (projectId) => invalidateTarget(projectId),+ invalidateLayer: (projectId, layerId) => invalidateTarget(projectId, layerId),+ invalidateProject: (projectId) => invalidateTarget(projectId),+ invalidateSource: (projectId, layerId) => invalidateTarget(projectId, layerId),+ reset: () => {+ if (active) {+ reset(active);+ }+ },+ start,+ subscribe: (listener) => {+ if (!disposed) {+ listeners.add(listener);+ }+ return () => listeners.delete(listener);+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 145d6239f3..a4aaa3afb8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -910,13 +910,58 @@ describe('createCanvasEngine', () => {if (exported.status !== 'ok') {throw new Error('expected successful export');}+ const cleanupPreview = vi.fn();+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },+ });setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });engine.dispose();});+ it('invalidates a canvas operation when its layer source changes or its layer is removed', async () => {+ for (const nextLayers of [+ [+ {+ ...makeDoc().layers[0]!,+ source: { image: { height: 10, imageName: 'replacement', width: 10 }, type: 'image' as const },+ },+ ],+ [],+ ]) {+ const document = makeDoc();+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const exported = await engine.exportLayerPixels('a');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }+ const cleanupPreview = vi.fn();+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'select-object', layerId: 'a', projectId: 'p1' },+ });++ setDocument({ ...document, layers: nextLayers });++ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ engine.dispose();+ }+ });+it('invalidates a LayerExportGuard when the document is replaced with the same layer object', async () => {const document = makeDoc();const { setDocument, store } = createReactiveStore(document);@@ -931,10 +976,18 @@ describe('createCanvasEngine', () => {if (exported.status !== 'ok') {throw new Error('expected successful export');}+ const cleanupPreview = vi.fn();+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'select-object', layerId: 'a', projectId: 'p1' },+ });setDocument({ ...document, layers: document.layers }, 1);expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });engine.dispose();});@@ -952,11 +1005,45 @@ describe('createCanvasEngine', () => {if (exported.status !== 'ok') {throw new Error('expected successful export');}+ const cleanupPreview = vi.fn();+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },+ });setActiveProjectId('p2');expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ engine.dispose();+ });++ it('disposes the active canvas operation with the engine', async () => {+ const { engine } = createEngine();+ const exported = await engine.exportLayerPixels('a');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }+ const cleanupPreview = vi.fn();+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },+ });+engine.dispose();++ expect(cleanupPreview).toHaveBeenCalledOnce();+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ expect(+ engine.canvasOperations.start({+ cleanupPreview,+ guard: exported.guard,+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },+ })+ ).toBeNull();});it('does not return an encoded layer blob after its export guard becomes stale', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex ec16a222bc..34922da2c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -107,6 +107,7 @@ import {import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { uploadCanvasImage } from './backend/canvasImages';+import { createCanvasOperationController, type CanvasOperationController } from './canvasOperationController';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { mergeDownMatrix } from './document/mergeDown';@@ -316,6 +317,8 @@ export interface CanvasEngineOptions {/** The public engine handle. */export interface CanvasEngine {readonly projectId: string;+ /** The single active guarded canvas operation and its React-free external-store state. */+ readonly canvasOperations: CanvasOperationController;/** The pan/zoom viewport. */getViewport(): Viewport;/** The transient stores React subscribes to. */@@ -1424,6 +1427,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;};+ const canvasOperations = createCanvasOperationController({ isGuardCurrent: isLayerExportGuardCurrent });+const ensureLayerCaches = (doc: CanvasDocumentContractV2): void => {for (const layer of doc.layers) {// The layer's rasterizable source: a raster/control `source`, or a mask@@ -2233,6 +2238,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {onBboxChanged: () =>scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true }),onDocumentReplaced: () => {+ canvasOperations.invalidateDocument(projectId);const previousImageNames = [...mirroredLayerImageNames.values()];rasterDocumentGeneration += 1;cancelAllLayerRasterizations();@@ -2308,6 +2314,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {},onLayerOrderChanged: () => scheduler.invalidate({ all: true }),onLayersChanged: (ids, sourceChangedIds) => {+ for (const id of sourceChangedIds) {+ canvasOperations.invalidateSource(projectId, id);+ }+ for (const id of ids) {+ canvasOperations.invalidateLayer(projectId, id);+ }const doc = mirror.getDocument();const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);const sourceChanged = new Set(sourceChangedIds);@@ -2425,6 +2437,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const unsubscribeProjectPreviewLifecycle = store.subscribe(() => {const activeProjectId = store.getState().activeProjectId;if (lastActiveProjectId === projectId && activeProjectId !== projectId) {+ canvasOperations.invalidateProject(projectId);rasterDocumentGeneration += 1;cancelAllLayerRasterizations();stores.thumbnailStatus.clear();@@ -5199,6 +5212,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return;}disposed = true;+ canvasOperations.dispose();cancelAllLayerRasterizations();detach();// Drop any open text-edit session (its layer belongs to a document this@@ -5312,6 +5326,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return {applyTransform,booleanMergeRasterLayers,+ canvasOperations,clearCaches,clearHistory,clearMask,