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
fix(webv2): refresh live engine reads on every document change
Josh Corbett7115fc5384e6
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 6574dfa7f6..b2fdb8c6a8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -129,6 +129,8 @@ export interface CanvasInteractionState {marqueeOptions: MarqueeToolOptions;/** Monotonic signal: some layer published new cache pixels (thumbnails, overview). */layerPixelEpoch: number;+ /** Monotonic signal: the mirrored document changed (an edit, sync or swap), after the engine reacted to it. */+ documentEpoch: number;ruleOfThirds: boolean;shapeOptions: ShapeToolOptions;showBbox: boolean;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 81abd9a7ad..08a69c2d1d 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@@ -696,3 +696,46 @@ describe('createDocumentMirror: value edits through the reducer', () => {expect(getForestDiffCount()).toBe(1);});});++describe('createDocumentMirror: change signal', () => {+ it('signals each document change once, after the other callbacks reacted, and never for staging alone', () => {+ const doc = makeDoc([rasterLayer('a')]);+ const canvas = makeCanvas(doc);+ const store = createFakeStore([{ canvas, id: 'p1' }]);+ const order: string[] = [];+ const callbacks = {+ ...spyCallbacks(),+ onDocumentChanged: vi.fn(() => order.push('document')),+ onLayersChanged: vi.fn(() => order.push('layers')),+ };+ createDocumentMirror(store, 'p1', callbacks);++ store.setState({+ projects: [{ canvas: { ...canvas, document: makeDoc([rasterLayer('a', { opacity: 0.5 })]) }, id: 'p1' }],+ });+ store.setState({+ projects: [{ canvas: { ...store.getState().projects[0]!.canvas, stagingArea: makeStaging() }, id: 'p1' }],+ });++ expect(order).toEqual(['layers', 'document']);+ });++ it('still signals the change when a reaction throws', () => {+ const doc = makeDoc([rasterLayer('a')]);+ const canvas = makeCanvas(doc);+ const store = createFakeStore([{ canvas, id: 'p1' }]);+ const callbacks = {+ ...spyCallbacks(),+ onDocumentChanged: vi.fn(),+ onLayersChanged: vi.fn(() => {+ throw new Error('reaction failed');+ }),+ };+ createDocumentMirror(store, 'p1', callbacks);++ expect(() =>+ store.setState({ projects: [{ canvas: { ...canvas, document: makeDoc([rasterLayer('b')]) }, id: 'p1' }] })+ ).toThrow('reaction failed');+ expect(callbacks.onDocumentChanged).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 3b962da173..554780e03e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -49,6 +49,8 @@ export interface DocumentMirrorCallbacks {* session cleanup.*/onSelectionChanged?(selectedLayerId: string | null): void;+ /** Any change to the mirrored document, after the callbacks above have reacted to it (even when one threw). */+ onDocumentChanged?(): void;}/** The imperative mirror handle. */@@ -255,39 +257,42 @@ export const createDocumentMirror = (const prevSelectedLayerId = prevDoc?.selectedLayerId ?? null;lastDoc = doc;lastRevision = revision;-- if (!prevDoc || !doc) {- callbacks.onDocumentReplaced();- } else if (- revision !== prevRevision ||- prevDoc.width !== doc.width ||- prevDoc.height !== doc.height ||- prevDoc.background !== doc.background- ) {- callbacks.onDocumentReplaced();- } else {- if (prevDoc.stacks !== doc.stacks) {- const edit = valueEditBetween(prevDoc.stacks, doc.stacks);- const prevIndex = getDocumentIndex(prevDoc);- const nextIndex = getDocumentIndex(doc);- const diff = edit ? diffValueEdit(prevIndex, nextIndex, edit) : diffForests(prevIndex, nextIndex);- if (diff.changed.length > 0) {- callbacks.onLayersChanged(diff.changed, diff.sourceChanged, diff.restructured);- } else if (diff.restructured) {- callbacks.onLayerOrderChanged();+ try {+ if (!prevDoc || !doc) {+ callbacks.onDocumentReplaced();+ } else if (+ revision !== prevRevision ||+ prevDoc.width !== doc.width ||+ prevDoc.height !== doc.height ||+ prevDoc.background !== doc.background+ ) {+ callbacks.onDocumentReplaced();+ } else {+ if (prevDoc.stacks !== doc.stacks) {+ const edit = valueEditBetween(prevDoc.stacks, doc.stacks);+ const prevIndex = getDocumentIndex(prevDoc);+ const nextIndex = getDocumentIndex(doc);+ const diff = edit ? diffValueEdit(prevIndex, nextIndex, edit) : diffForests(prevIndex, nextIndex);+ if (diff.changed.length > 0) {+ callbacks.onLayersChanged(diff.changed, diff.sourceChanged, diff.restructured);+ } else if (diff.restructured) {+ callbacks.onLayerOrderChanged();+ }+ if (diff.recompositeOnly.length > 0) {+ callbacks.onLayersRecomposite?.(diff.recompositeOnly);+ }}- if (diff.recompositeOnly.length > 0) {- callbacks.onLayersRecomposite?.(diff.recompositeOnly);+ if (!bboxEqual(prevDoc.bbox, doc.bbox)) {+ callbacks.onBboxChanged();}}- if (!bboxEqual(prevDoc.bbox, doc.bbox)) {- callbacks.onBboxChanged();- }- }- const selectedLayerId = doc?.selectedLayerId ?? null;- if (selectedLayerId !== prevSelectedLayerId) {- callbacks.onSelectionChanged?.(selectedLayerId);+ const selectedLayerId = doc?.selectedLayerId ?? null;+ if (selectedLayerId !== prevSelectedLayerId) {+ callbacks.onSelectionChanged?.(selectedLayerId);+ }+ } finally {+ callbacks.onDocumentChanged?.();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex b1e86aa829..d1cf0b1ddf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -18694,3 +18694,34 @@ describe('floating selection lifecycle', () => {engine.lifecycle.dispose();});});++describe('document epoch', () => {+ it('advances on each document change, once the engine model already reflects it', () => {+ const { setDocument, store } = createReactiveStore(paintDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const seen: (number | undefined)[] = [];+ engine.interaction.subscribe('documentEpoch', () =>+ seen.push(+ engine.document+ .model()+ ?.compileLeaves()+ .find((leaf) => leaf.id === 'paint1')?.layer.opacity+ )+ );+ const before = engine.interaction.get('documentEpoch');+ const dimmed = paintDoc();+ const [layer] = getDocumentLeaves(dimmed);++ setDocument({ ...dimmed, stacks: stacksFrom([{ ...layer!, opacity: 0.25 }]) });++ expect(engine.interaction.get('documentEpoch')).toBe(before + 1);+ expect(seen).toEqual([0.25]);+ engine.lifecycle.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex e570f6c054..b056556d49 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -375,6 +375,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClassoOptions: stores.lassoOptions,marqueeOptions: stores.marqueeOptions,layerPixelEpoch: stores.layerPixelEpoch,+ documentEpoch: stores.documentEpoch,ruleOfThirds: stores.ruleOfThirds,shapeOptions: stores.shapeOptions,showBbox: stores.showBbox,@@ -1399,6 +1400,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// ---- Document mirror ----------------------------------------------------const mirror: DocumentMirror = createDocumentMirror(mutationPort, {+ onDocumentChanged: () => stores.documentEpoch.set(stores.documentEpoch.get() + 1),// Bbox changes need only overlay redraw unless a bbox-relative staged preview must move in the composite.// Explicitly placed candidates stay fixed.onBboxChanged: () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 5387a7416e..3654d6df00 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -431,6 +431,8 @@ export interface EngineStores {thumbnailStatus: KeyedThumbnailStatusStore;/** Monotonic aggregate version for consumers whose eligibility depends on live layer content. */layerPixelEpoch: ScalarStore<number>;+ /** Monotonic version of the mirrored document, for consumers that read the engine's model during render. */+ documentEpoch: ScalarStore<number>;/** Brush tool options (size / color / opacity / pressure). */brushOptions: ScalarStore<BrushOptions>;/** One-way foreground/background mirror for gesture-start reads; the engine never writes it. */@@ -684,6 +686,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =marqueeOptions: createScalarStore<MarqueeToolOptions>({ ...DEFAULT_MARQUEE_OPTIONS }, marqueeOptionsEqual),marqueePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, rectShapePreviewEqual),layerPixelEpoch: createScalarStore<number>(0),+ documentEpoch: createScalarStore<number>(0),ruleOfThirds: createScalarStore<boolean>(false),samInteraction: createScalarStore(null),shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 2d363432f2..087ca4421c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -53,16 +53,27 @@ export const useLayerThumbnailVersion = (};/**- * A primitive read of live engine state (document model, cached pixels), taken on every render and whenever a layer- * publishes pixels. The React Compiler memoizes a plain render-time engine call on its arguments, so it would keep a- * stale answer after a paint; route such reads through here.+ * A primitive read of live engine state (document model, cached pixels), taken on every render and whenever the+ * engine's document changes or a layer publishes pixels. The React Compiler memoizes a plain render-time engine call+ * on its arguments, so it would keep a stale answer after a paint or another layer's edit; route such reads through+ * here.*/export const useCanvasEngineRead = <T extends boolean | number | string | null>(engine: CanvasCoreStoreCapability | null,read: () => T): T => {const subscribe = useCallback(- (listener: () => void) => engine?.interaction.subscribe('layerPixelEpoch', listener) ?? (() => undefined),+ (listener: () => void) => {+ if (!engine) {+ return () => undefined;+ }+ const unsubscribePixels = engine.interaction.subscribe('layerPixelEpoch', listener);+ const unsubscribeDocument = engine.interaction.subscribe('documentEpoch', listener);+ return () => {+ unsubscribePixels();+ unsubscribeDocument();+ };+ },[engine]);return useSyncExternalStore(subscribe, read, read);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.browser.test.tsxindex e707aee047..1df4c1d639 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.browser.test.tsx@@ -18,27 +18,27 @@ await i18n.use(initReactI18next).init({resources: { en: { translation: { 'widgets.layers.control.filter': 'Filter' } } },});-/** An engine whose layer gains pixels later and announces them through the pixel epoch, as a fill does. */-const createPaintingEngine = () => {- let painted = false;- const listeners = new Set<() => void>();+/** An engine whose layer gains content later, announced through one of its interaction signals. */+const createChangingEngine = () => {+ let hasContent = false;+ const listeners = new Map<string, Set<() => void>>();const engine = {- exports: { hasExportableLayerContent: () => painted },+ exports: { hasExportableLayerContent: () => hasContent },interaction: {subscribe: (key: string, listener: () => void) => {- if (key === 'layerPixelEpoch') {- listeners.add(listener);- }- return () => listeners.delete(listener);+ const set = listeners.get(key) ?? new Set();+ set.add(listener);+ listeners.set(key, set);+ return () => set.delete(listener);},},projectId: 'project',} as unknown as LayerFilterOperationEngine;- const paint = (): void => {- painted = true;- listeners.forEach((listener) => listener());+ const gainContent = (signal: 'layerPixelEpoch' | 'documentEpoch'): void => {+ hasContent = true;+ listeners.get(signal)?.forEach((listener) => listener());};- return { engine, paint };+ return { engine, gainContent };};const noop = (): void => {};@@ -53,8 +53,11 @@ afterEach(() => {container = null;});-it('enables Filter as soon as the layer publishes pixels, without reselecting it', async () => {- const { engine, paint } = createPaintingEngine();+it.each([+ ['publishes pixels (a fill)', 'layerPixelEpoch'],+ ['gains content through a document change', 'documentEpoch'],+] as const)('enables Filter as soon as the layer %s, without reselecting it', async (_, signal) => {+ const { engine, gainContent } = createChangingEngine();const layer = createEmptyPaintLayer('Raster', 'raster');container = document.createElement('div');document.body.append(container);@@ -70,7 +73,7 @@ it('enables Filter as soon as the layer publishes pixels, without reselecting it);await expect.element(page.getByRole('button', { name: 'Filter' })).toBeDisabled();- act(() => paint());+ act(() => gainContent(signal));await expect.element(page.getByRole('button', { name: 'Filter' })).toBeEnabled();});