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
import type {
CanvasEngineImplementation as CoreCanvasEngineImplementation,
CanvasEngineOptions as CoreCanvasEngineOptions,
} from '@workbench/canvas-engine/engine';
import type { GenerationCompositeHost } from '@workbench/canvas-operations/generationComposite';
import type { BackendGraphContract } from '@workbench/graphContracts';
import { galleryDurability } from '@features/gallery';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
import { createCanvasEngine as createCanvasEngineCore } from '@workbench/canvas-engine/engine';
import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';
import { isUploadProjectNotFound } from '@workbench/canvas-operations/backend/canvasImages';
import { createBoundedCompositeDedupeCache } from '@workbench/canvas-operations/compositeForGeneration';
import { createControlDetectionCoordinator } from '@workbench/canvas-operations/ControlDetectionCoordinator';
import { composeForGeneration } from '@workbench/canvas-operations/generationComposite';
import { controlTypeForDetector } from '@workbench/controlTypes';
import type { CanvasOperationCapability, CanvasOperationImplementation, CanvasUtilityGraphResult } from './contracts';
import { attachCanvasOperations } from './operationAccess';
import { bindCanvasToolMemory, type CanvasToolMemoryPort } from './toolMemory';
export interface CanvasEngineOptions extends Omit<
CoreCanvasEngineOptions,
'uploadImage' | 'uploadIntermediateImage' | 'getMainModelBase' | 'resampleTransform'
> {
/**
* Waits for the owning project identity to be acknowledged by the server, so uploads can carry it as provenance.
* Rejects with an `AbortError` when the project closed.
*/
ensureProjectOnServer(): Promise<void>;
getMainModelBase?: () => string | null;
/** The account's Select Object auto-update preference; the widget layer injects the settings read. */
readSelectObjectAutoUpdate?: () => boolean;
/** Where the account keeps brush, eraser, shape and text options; the engine starts from them and saves changes. */
toolMemory?: CanvasToolMemoryPort;
selectObjectDeps?: {
uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;
runGraph(options: {
graph: BackendGraphContract;
outputNodeId?: string;
signal?: AbortSignal;
}): Promise<CanvasUtilityGraphResult>;
};
controlDetectionDeps?: {
/** Adopts a detected map as canvas-owned pixels; the gallery's canvas-asset transition by default. */
makeDurable(imageName: string): Promise<void>;
};
filterDeps?: {
uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
runGraph(options: {
graph: BackendGraphContract;
outputNodeId?: string;
signal?: AbortSignal;
}): Promise<CanvasUtilityGraphResult>;
};
}
export type CanvasOperationsCapability = CanvasOperationCapability;
/** Settles with `promise`, or rejects with the abort reason as soon as `signal` aborts. */
const raceAbort = <T>(promise: Promise<T>, signal: AbortSignal): Promise<T> =>
new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
signal.removeEventListener('abort', onAbort);
reject(signal.reason);
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then(
(value) => {
signal.removeEventListener('abort', onAbort);
resolve(value);
},
(error: unknown) => {
signal.removeEventListener('abort', onAbort);
reject(error);
}
);
if (signal.aborted) {
onAbort();
}
});
/** How long uploads skip provenance after the server reported the project missing, before trying it again. */
const MISSING_PROJECT_REUSE_MS = 60_000;
/** Private application composition shape; public callers receive the capability-only handle from the registry API. */
export type CanvasEngine = CoreCanvasEngineImplementation;
/** Application composition root: owns SAM/filter sessions, queues, uploads, and their core capability adapters. */
export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine => {
const {
controlDetectionDeps,
ensureProjectOnServer,
filterDeps,
readSelectObjectAutoUpdate,
selectObjectDeps,
toolMemory,
...coreOptions
} = options;
const owner = captureAccountScope();
const uploadLifetime = new AbortController();
let projectMissingAt = -Infinity;
const resolveUploadProjectId = async (): Promise<string | undefined> => {
try {
await ensureProjectOnServer();
return Date.now() - projectMissingAt < MISSING_PROJECT_REUSE_MS ? undefined : options.projectId;
} catch (error) {
// A project the server has not accepted (offline, conflicted, deleted elsewhere) costs the upload its provenance,
// never the edit; only a closed project stops it.
if (error instanceof DOMException && error.name === 'AbortError') {
throw error;
}
return undefined;
}
};
const uploadImage: typeof canvasApplicationPort.uploadImage = async (blob, uploadOptions) => {
assertAccountScopeCurrent(owner);
const signal = AbortSignal.any([
owner.signal,
uploadLifetime.signal,
...(uploadOptions?.signal ? [uploadOptions.signal] : []),
]);
signal.throwIfAborted();
let projectId: string | undefined;
try {
projectId = await raceAbort(resolveUploadProjectId(), signal);
} finally {
assertAccountScopeCurrent(owner);
}
signal.throwIfAborted();
try {
return await canvasApplicationPort.uploadImage(blob, { ...uploadOptions, projectId, signal });
} catch (error) {
// Deleted elsewhere before this editor noticed: the upload still lands, without provenance.
if (projectId === undefined || !isUploadProjectNotFound(error)) {
throw error;
}
assertAccountScopeCurrent(owner);
projectMissingAt = Date.now();
return canvasApplicationPort.uploadImage(blob, { ...uploadOptions, projectId: undefined, signal });
}
};
const composition = createCanvasEngineCore({
...coreOptions,
getMainModelBase: options.getMainModelBase,
resampleTransform: async (surface, target, mode, signal, onProgress) => {
const lifetime = AbortSignal.any([owner.signal, uploadLifetime.signal]);
signal.throwIfAborted();
lifetime.throwIfAborted();
const { createTransformResampler } = await raceAbort(
import('./transformResampling'),
AbortSignal.any([signal, lifetime])
);
signal.throwIfAborted();
lifetime.throwIfAborted();
return createTransformResampler({
lifetime,
backend: options.backend ?? createDomRasterBackend(),
resolveImage: options.imageResolver,
upload: (blob, uploadSignal) => uploadImage(blob, { isIntermediate: true, signal: uploadSignal }),
runGraph: (runOptions) => canvasApplicationPort.runGraph(runOptions),
})(surface, target, mode, signal, onProgress);
},
uploadImage: (blob) => uploadImage(blob),
uploadIntermediateImage: (blob) => uploadImage(blob, { isIntermediate: true }),
});
const { applicationHost: host } = composition;
const core = composition.engine;
const stores = canvasApplicationPort.createOperationStores();
const controller = canvasApplicationPort.createOperationController({
edits: core.edits,
isGuardCurrent: host.isGuardCurrent,
});
const runFilterGraph = async (runOptions: {
graph: BackendGraphContract;
outputNodeId?: string;
signal?: AbortSignal;
}): Promise<CanvasUtilityGraphResult> => {
const output = await (filterDeps?.runGraph(runOptions) ?? canvasApplicationPort.runGraph(runOptions));
return { height: output.height, imageName: output.imageName, width: output.width };
};
let filterCoordinator!: ReturnType<typeof canvasApplicationPort.createFilterCoordinator>;
const selectObjectCoordinator = canvasApplicationPort.createSelectObjectCoordinator({
captureGuard: host.captureGuard,
clearOtherOperation: () => filterCoordinator.cancel(),
clearPreview: host.clearSamPreview,
commitGenerated: (preview, commitOptions) =>
host.commitGenerated({
copyLayerName:
commitOptions.mode === 'copy-raster'
? 'Segmented Object'
: commitOptions.mode === 'copy-control'
? 'Segmented Object Control'
: undefined,
guard: preview.guard,
historyLabel: commitOptions.mode === 'replace' ? 'Replace layer with selected object' : undefined,
image: preview.image,
origin: { x: preview.rect.x, y: preview.rect.y },
signal: commitOptions.signal,
target:
commitOptions.mode === 'replace'
? 'replace'
: commitOptions.mode === 'copy-raster'
? 'copy-raster'
: 'copy-control',
}),
commitMask: (preview, target, signal) =>
host.commitMask({ guard: preview.guard, image: preview.image, rect: preview.rect, signal, target }),
controller,
decodePreview: host.decodeSelectObjectPreview,
exportSource: host.exportBakedLayerBlob,
invalidateOverlay: () => {
const session = stores.samSession.get();
host.setSamInteraction(
session?.input.type === 'visual'
? { input: session.input, pointLabel: session.pointLabel, sourceRect: session.sourceRect }
: null
);
},
isGuardCurrent: host.isGuardCurrent,
isSamToolActive: host.isSamToolActive,
prepareStart: host.prepareSelectObjectStart,
projectId: options.projectId,
readAutoUpdatePreference: readSelectObjectAutoUpdate,
publishPreview: (preview) => host.publishSamPreview(preview),
replaceSelection: (preview, signal) => host.replaceSelection(preview.guard, preview.image, preview.rect, signal),
replaceTemporaryRestoreTool: host.replaceTemporaryRestoreTool,
runGraph: (runOptions) => selectObjectDeps?.runGraph(runOptions) ?? canvasApplicationPort.runGraph(runOptions),
selectLayer: host.selectLayer,
setSamTool: host.setSamTool,
setViewTool: host.setViewTool,
stores,
uploadIntermediate: async (blob, signal) => {
if (selectObjectDeps) {
return selectObjectDeps.uploadIntermediate(blob, signal);
}
if (signal?.aborted) {
throw new DOMException('Select Object upload was aborted.', 'AbortError');
}
const uploaded = await uploadImage(blob, {
isIntermediate: true,
signal,
});
if (signal?.aborted) {
throw new DOMException('Select Object upload was aborted.', 'AbortError');
}
return uploaded;
},
});
filterCoordinator = canvasApplicationPort.createFilterCoordinator({
captureGuard: host.captureGuard,
clearOtherOperation: () => selectObjectCoordinator.cancel(),
clearPreview: host.clearFilterPreview,
controller,
encodeSurface: host.encodeSurface,
getDocument: host.getDocument,
getSessionDeps: (layerId) => ({
commit: ({ draft, guard, image, rect, signal, target }) =>
host.commitFilter({
...(target === 'control' ? { controlCopy: { controlType: controlTypeForDetector(draft) } } : {}),
filter: draft,
guard,
image,
mode: target === 'apply' ? 'replace' : 'copy',
rect,
requireExactImageDimensions: true,
signal,
target,
}),
exportPixels: () => host.exportLayerPixels(layerId, { applyAdjustments: true, includeDisabled: true }),
isGuardCurrent: host.isGuardCurrent,
publishPreview: (imageName, rect, guard, filterType) =>
host.publishFilterPreview(guard.layerId, imageName, rect, guard, filterType),
}),
runFilterGraph,
selectLayer: host.selectLayer,
setViewTool: host.setViewTool,
stores,
uploadIntermediate: async (blob, signal) => {
const uploaded = await (filterDeps?.uploadIntermediate(blob, signal) ??
uploadImage(blob, { isIntermediate: true, signal }));
return { imageName: uploaded.imageName };
},
});
// Any of these may be what refused a detection commit; each release lets a waiting result retry.
const lockStores = [
core.stores.documentEditingLocked,
core.stores.transformSession,
core.stores.textEditSession,
core.stores.documentEpoch,
];
const controlDetection = createControlDetectionCoordinator({
derivation: host,
flushLayerUploads: host.flushLayerUploads,
getDocument: host.getDocument,
makeDurable: controlDetectionDeps?.makeDurable ?? galleryDurability.makeCanvasAsset,
projectId: options.projectId,
runFilterGraph,
subscribeLockChanges: (listener) => {
const unsubscribers = lockStores.map((store) => store.subscribe(listener));
return () => {
for (const unsubscribe of unsubscribers) {
unsubscribe();
}
};
},
});
// Statuses follow the document (deleted layers, undo past a failure); it never schedules detection.
const unsubscribeControlReconcile = core.stores.documentEpoch.subscribe(controlDetection.reconcileWithDocument);
const syncEditingLock = (): void => {
const operation = controller.getSnapshot();
core.stores.documentEditingLocked.set(operation.status === 'active');
core.stores.documentEditingLayerId.set(operation.status === 'active' ? operation.identity.layerId : null);
};
const unsubscribeEditingLock = controller.subscribe(syncEditingLock);
const syncSamInteraction = (): void => {
const session = stores.samSession.get();
host.setSamInteraction(
session?.input.type === 'visual'
? { input: session.input, pointLabel: session.pointLabel, sourceRect: session.sourceRect }
: null
);
};
const unsubscribeSamInteraction = stores.samSession.subscribe(syncSamInteraction);
const unsubscribeToolChanges = host.subscribeToolChanges(({ from, temporary, to }) => {
if (from === 'sam' && to !== 'sam' && !temporary && selectObjectCoordinator.isActive()) {
selectObjectCoordinator.cancel();
}
});
host.setSamInputHandler((input) => selectObjectCoordinator.update({ input }));
host.setEscapeHandler((gestureWasActive) => {
if (gestureWasActive) {
return false;
}
if (filterCoordinator.isActive()) {
filterCoordinator.cancel();
return true;
}
if (selectObjectCoordinator.isActive()) {
selectObjectCoordinator.cancel();
return true;
}
return false;
});
syncEditingLock();
syncSamInteraction();
const compositeDedupe = createBoundedCompositeDedupeCache();
const generationCompositeHost: GenerationCompositeHost = {
captureDocumentSnapshot: () => core.document.captureSnapshot(),
captureRasterSnapshot: (snapshot, layerIds, captureOptions) =>
core.exports.captureRasterSnapshot(snapshot, layerIds, captureOptions),
dedupe: compositeDedupe,
getCompositeExecutorDeps: () => core.exports.getCompositeExecutorDeps(),
};
const operations: CanvasOperationImplementation = {
applyControlLayerIntent: controlDetection.applyIntent,
applySelectObjectSession: selectObjectCoordinator.apply,
cancelFilterOperation: filterCoordinator.cancel,
cancelSelectObjectSession: selectObjectCoordinator.cancel,
commitFilterOperation: filterCoordinator.commit,
composeForGeneration: (composeOptions) => composeForGeneration(generationCompositeHost, composeOptions),
controller,
getControlDetectionStatus: controlDetection.getStatus,
getFilterSessionState: stores.filterSession.get,
getOperationState: controller.getSnapshot,
getSamSessionState: stores.samSession.get,
processFilterOperation: filterCoordinator.process,
processSelectObjectSession: selectObjectCoordinator.process,
resetFilterOperation: filterCoordinator.reset,
resetSelectObjectSession: selectObjectCoordinator.reset,
retryControlDetection: controlDetection.retry,
saveSelectObjectSession: selectObjectCoordinator.save,
setFilterOperationAutoProcess: filterCoordinator.setAutoProcess,
startFilterOperation: filterCoordinator.start,
startSelectObject: selectObjectCoordinator.start,
stores,
subscribeControlDetectionStatus: controlDetection.subscribeStatus,
subscribeFilterSession: stores.filterSession.subscribe,
subscribeOperation: controller.subscribe,
subscribeSamSession: stores.samSession.subscribe,
updateFilterOperation: filterCoordinator.updateDraft,
updateSelectObjectSession: selectObjectCoordinator.update,
uploadIntermediate: async (blob, signal) => {
if (signal?.aborted) {
throw new DOMException('Canvas upload aborted', 'AbortError');
}
const uploaded = await uploadImage(blob, {
isIntermediate: true,
signal,
});
if (signal?.aborted) {
throw new DOMException('Canvas upload aborted', 'AbortError');
}
return { imageName: uploaded.imageName };
},
};
// Saves are dropped once the account changed: the engine outlives it only until the registry disposes it.
const toolMemoryBinding = toolMemory
? bindCanvasToolMemory(core.stores, {
read: () => toolMemory.read(),
...(toolMemory.subscribe ? { subscribe: toolMemory.subscribe } : {}),
write: (changed) => {
if (isAccountScopeCurrent(owner)) {
toolMemory.write(changed);
}
},
})
: null;
let disposed = false;
const disposeOperations = (): void => {
if (disposed) {
return;
}
disposed = true;
toolMemoryBinding?.dispose();
uploadLifetime.abort();
host.setSamInputHandler(null);
host.setEscapeHandler(null);
unsubscribeToolChanges();
unsubscribeSamInteraction();
unsubscribeEditingLock();
unsubscribeControlReconcile();
controlDetection.dispose();
filterCoordinator.dispose();
selectObjectCoordinator.dispose();
controller.dispose();
core.stores.documentEditingLayerId.set(null);
core.stores.documentEditingLocked.set(false);
host.setSamInteraction(null);
};
const lifecycle = {
...core.lifecycle,
activate: () => {
core.lifecycle.activate();
if (!disposed) {
controlDetection.resume();
}
},
beginCooldown: () => {
filterCoordinator.cancel();
selectObjectCoordinator.cancel();
controlDetection.suspend();
controller.invalidateDocument(options.projectId);
return core.lifecycle.beginCooldown();
},
dispose: () => {
disposeOperations();
core.lifecycle.dispose();
},
};
const diagnostics = {
...core.diagnostics,
clearCaches: async () => {
filterCoordinator.cancel();
selectObjectCoordinator.cancel();
await core.diagnostics.clearCaches();
},
};
const engine: CanvasEngine = { ...core, diagnostics, lifecycle };
attachCanvasOperations(engine, operations);
return engine;
};