Skip to content

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.

fix(webv2): read live layer content when the layers UI renders

Josh Corbett2e4b2d91fa10
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
index f732a7b367..1cc4c152d4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
@@ -6,12 +6,14 @@ import { isLayerEditable } from './layerEligibility';
export type HasMergeVisibleContent = (layerId: string) => boolean;
+const isMergeVisibleRasterLeaf = (leaf: SemanticLeaf, hasContent: HasMergeVisibleContent): boolean =>
+ leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id);
+
/** Contributing raster leaves with content, top first. */
export const getMergeVisibleRasterLeaves = (
leaves: readonly SemanticLeaf[],
hasContent: HasMergeVisibleContent
-): SemanticLeaf[] =>
- leaves.filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id));
+): SemanticLeaf[] => leaves.filter((leaf) => isMergeVisibleRasterLeaf(leaf, hasContent));
/** Contributing raster layers with content, top first. */
export const getMergeVisibleRasterLayers = (
@@ -19,9 +21,19 @@ export const getMergeVisibleRasterLayers = (
hasContent: HasMergeVisibleContent
): CanvasLayerContract[] => getMergeVisibleRasterLeaves(leaves, hasContent).map((leaf) => leaf.layer);
-/** Whether the raster stack's merge-visible action has at least two contributors. */
-export const canMergeVisibleRasters = (leaves: readonly SemanticLeaf[], hasContent: HasMergeVisibleContent): boolean =>
- getMergeVisibleRasterLayers(leaves, hasContent).length >= 2;
+/** Whether the raster stack's merge-visible action has at least two contributors; stops at the second. */
+export const canMergeVisibleRasters = (
+ leaves: readonly SemanticLeaf[],
+ hasContent: HasMergeVisibleContent
+): boolean => {
+ let found = 0;
+ for (const leaf of leaves) {
+ if (isMergeVisibleRasterLeaf(leaf, hasContent) && ++found === 2) {
+ return true;
+ }
+ }
+ return false;
+};
/**
* Destructive merge-selected may only collapse one uninterrupted run of raster siblings: leaves
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index d42f167820..2d363432f2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -52,6 +52,22 @@ export const useLayerThumbnailVersion = (
return useSyncExternalStore(subscribe, getSnapshot);
};
+/**
+ * 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.
+ */
+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),
+ [engine]
+ );
+ return useSyncExternalStore(subscribe, read, read);
+};
+
/** Subscribes to one layer's thumbnail request state; an absent key is idle. */
export const useLayerThumbnailStatus = (
engine: CanvasCoreStoreCapability | null,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index afac46ad9b..388cd60cce 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -30,6 +30,7 @@ import { useExternalStoreSelector } from '@platform/state/selectors';
import { Button, Field, Select, Slider } from '@platform/ui';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';
+import { useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
import { useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -334,18 +335,22 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
const selectedModelName = modelOptions.find((model) => model.key === adapter.model)?.name;
const adapterModel = models.find((model) => model.key === adapter.model) ?? null;
- const hasContent = engine?.exports.hasExportableLayerContent(layer.id) ?? false;
- const controlLoraIndex =
+ const hasContent = useCanvasEngineRead(engine, () => engine?.exports.hasExportableLayerContent(layer.id) ?? false);
+ const controlLoraIndex = useCanvasEngineRead(engine, () =>
adapter.kind === 'control_lora' && engine
? contributingControlLayers(engine, 'control_lora').findIndex((candidate) => candidate.id === layer.id)
- : 0;
- const zImageControlIndex =
+ : 0
+ );
+ const zImageControlIndex = useCanvasEngineRead(engine, () =>
adapter.kind === 'z_image_control' && engine
? contributingControlLayers(engine, 'z_image_control').findIndex((candidate) => candidate.id === layer.id)
- : 0;
- const contributing = engine
- ? (lookupDocumentLeaf(engine.document.model()?.document, layer.id)?.contributionEnabled ?? false)
- : layer.isEnabled;
+ : 0
+ );
+ const contributing = useCanvasEngineRead(engine, () =>
+ engine
+ ? (lookupDocumentLeaf(engine.document.model()?.document, layer.id)?.contributionEnabled ?? false)
+ : layer.isEnabled
+ );
// Same reason as `kindOptions`: validation asks the capability table whether the kind is supported.
const validationReason = useExternalStoreSelector(
subscribeArchitectureCapabilities,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index daf760424b..784211988f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -37,11 +37,7 @@ import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
-import {
- useCanvasDocumentEditingLocked,
- useCanvasLayerPixelEpoch,
- useLayerThumbnailVersion,
-} from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasDocumentEditingLocked, useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
@@ -242,11 +238,11 @@ const LayerMenu = ({
const documentEditingLocked = useCanvasDocumentEditingLocked(engine);
const { selectedIds } = useLayerPanelState(projectId, document.selectedLayerId);
const interactionLocked = isCanvasInteractionLocked(canvas, queueItems) || documentEditingLocked;
- // Re-render when live, not-yet-persisted paint/mask pixels change.
- useLayerThumbnailVersion(engine, layer.id);
- const hasSupportedContent = engine
- ? engine.exports.hasExportableLayerContent(layer.id)
- : hasPureExportableLayerContent(layer, document);
+ const hasLiveContent = useCanvasEngineRead(
+ engine,
+ () => engine?.exports.hasExportableLayerContent(layer.id) ?? false
+ );
+ const hasSupportedContent = engine ? hasLiveContent : hasPureExportableLayerContent(layer, document);
const [internalDialogKind, setInternalDialogKind] = useState<LayerMenuDialogKind | null>(null);
const dialogKind = controlledDialogKind !== undefined ? controlledDialogKind : internalDialogKind;
const setDialogKind = useCallback(
@@ -280,20 +276,23 @@ const LayerMenu = ({
[commitPrepared, layer, selectedIds]
);
- const canGroup = canGroupSelection(engine?.document.model() ?? null, actionTargets({ layer, selectedIds }));
- // Un-memoized on purpose, like `canGroup`: it reads live raster content
- // (`hasExportableLayerContent`), which the content epoch re-renders for.
- useCanvasLayerPixelEpoch(engine);
- const mergeModel = engine?.document.model() ?? null;
- const mergeTargets = actionTargets({ layer, selectedIds });
- const canMerge =
- !!engine &&
- !!mergeModel &&
- mergeTargets.length > 1 &&
- canMergeSelectedRasters(mergeModel.document, mergeModel.compileLeaves(), new Set(mergeTargets), (layerId) =>
- engine.exports.hasExportableLayerContent(layerId)
+ const targets = actionTargets({ layer, selectedIds });
+ const canGroup = useCanvasEngineRead(engine, () => canGroupSelection(engine?.document.model() ?? null, targets));
+ const canMerge = useCanvasEngineRead(engine, () => {
+ const model = engine?.document.model() ?? null;
+ return (
+ !!engine &&
+ !!model &&
+ targets.length > 1 &&
+ canMergeSelectedRasters(model.document, model.compileLeaves(), new Set(targets), (layerId) =>
+ engine.exports.hasExportableLayerContent(layerId)
+ )
);
- const canDeleteSelection = !!mergeModel && mergeModel.refusalFor({ ids: mergeTargets, type: 'remove' }) === null;
+ });
+ const canDeleteSelection = useCanvasEngineRead(
+ engine,
+ () => engine?.document.model()?.refusalFor({ ids: targets, type: 'remove' }) === null
+ );
const hiddenByAncestor =
(lookupDocumentNodeState(document, layer.id)?.documentHidden ?? false) && !isNodeHidden(layer);
const actionState = useMemo<LayerContextActionState>(
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.tsx
new file mode 100644
index 0000000000..e707aee047
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.browser.test.tsx
@@ -0,0 +1,76 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, expect, it } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { LayerFilterOperationButton, type LayerFilterOperationEngine } from './LayerFilterOperationButton';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ 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>();
+ const engine = {
+ exports: { hasExportableLayerContent: () => painted },
+ interaction: {
+ subscribe: (key: string, listener: () => void) => {
+ if (key === 'layerPixelEpoch') {
+ listeners.add(listener);
+ }
+ return () => listeners.delete(listener);
+ },
+ },
+ projectId: 'project',
+ } as unknown as LayerFilterOperationEngine;
+ const paint = (): void => {
+ painted = true;
+ listeners.forEach((listener) => listener());
+ };
+ return { engine, paint };
+};
+
+const noop = (): void => {};
+
+let root: Root | null = null;
+let container: HTMLDivElement | null = null;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ container?.remove();
+ root = null;
+ container = null;
+});
+
+it('enables Filter as soon as the layer publishes pixels, without reselecting it', async () => {
+ const { engine, paint } = createPaintingEngine();
+ const layer = createEmptyPaintLayer('Raster', 'raster');
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+ act(() =>
+ root!.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <LayerFilterOperationButton engine={engine} layer={layer} onOperationStarted={noop} operations={null} />
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+ await expect.element(page.getByRole('button', { name: 'Filter' })).toBeDisabled();
+
+ act(() => paint());
+
+ await expect.element(page.getByRole('button', { name: 'Filter' })).toBeEnabled();
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx
index 2a97155b9f..d65e4efe5c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx
@@ -22,13 +22,12 @@ interface CapturedTooltipProps {
disabled?: boolean;
}
-const { captured, notifyError, thumbnailSubscription } = vi.hoisted(() => ({
+const { captured, notifyError } = vi.hoisted(() => ({
captured: {
button: null as CapturedButtonProps | null,
tooltip: null as CapturedTooltipProps | null,
},
notifyError: vi.fn(),
- thumbnailSubscription: vi.fn(),
}));
vi.mock('@platform/ui', async (importOriginal) => {
@@ -49,9 +48,6 @@ vi.mock('@platform/ui', async (importOriginal) => {
vi.mock('@workbench/useNotify', () => ({
useNotify: () => ({ error: notifyError, info: vi.fn(), success: vi.fn() }),
}));
-vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({
- useLayerThumbnailVersion: thumbnailSubscription,
-}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
@@ -66,6 +62,7 @@ const createEngine = (
const startFilterOperation = vi.fn(launch);
const engine = {
exports: { hasExportableLayerContent },
+ interaction: { subscribe: () => () => undefined },
operations: { startFilterOperation },
} as unknown as LayerFilterOperationEngine;
@@ -103,7 +100,6 @@ beforeEach(() => {
captured.button = null;
captured.tooltip = null;
notifyError.mockClear();
- thumbnailSubscription.mockClear();
});
describe('LayerFilterOperationButton eligibility', () => {
@@ -143,7 +139,7 @@ describe('LayerFilterOperationButton eligibility', () => {
it.each([
['raster', createEmptyPaintLayer('Raster', 'raster')],
['control', createControlLayer('Control', 'control')],
- ] as const)('enables a filterable %s layer and subscribes to its thumbnail', (_type, layer) => {
+ ] as const)('enables a filterable %s layer', (_type, layer) => {
const { engine } = createEngine(true);
const { button, tooltip } = renderButton(engine, layer);
@@ -151,8 +147,6 @@ describe('LayerFilterOperationButton eligibility', () => {
expect(button.disabled).toBe(false);
expect(tooltip.disabled).toBe(true);
expect(tooltip.content).toBe('');
- expect(thumbnailSubscription).toHaveBeenCalledOnce();
- expect(thumbnailSubscription).toHaveBeenCalledWith(engine, layer.id);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx
index f9cf6b661b..6062d05c1e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx
@@ -5,7 +5,7 @@ import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import { Box } from '@chakra-ui/react';
import { Button, Tooltip } from '@platform/ui';
import { useNotify } from '@workbench/useNotify';
-import { useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,11 +33,14 @@ export const LayerFilterOperationButton = ({
}: LayerFilterOperationButtonProps) => {
const { t } = useTranslation();
const notify = useNotify();
- useLayerThumbnailVersion(engine, layer.id);
+ const hasExportableContent = useCanvasEngineRead(
+ engine,
+ () => engine?.exports.hasExportableLayerContent(layer.id) ?? false
+ );
const disabledReason = getLayerFilterLaunchDisabledReason({
hasEngine: engine !== null,
- hasExportableContent: engine?.exports.hasExportableLayerContent(layer.id) ?? false,
+ hasExportableContent,
isEnabled: layer.isEnabled,
isLocked: layer.isLocked,
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
index 3043bf1d3c..b9a7e9e9e7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
@@ -4,6 +4,7 @@ import type { LucideIcon } from 'lucide-react';
import { toaster } from '@platform/ui';
import { canMergeVisibleRasters, compileDocumentNodes, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectName } from '@workbench/WorkbenchContext';
import { EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
@@ -55,11 +56,14 @@ export const useLayerStackActions = (
nodes: own,
};
}, [axis, stack, stacks]);
- const canMerge =
- !editingLocked &&
- !!engine &&
- stack === 'raster' &&
- canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent);
+ const canMerge = useCanvasEngineRead(
+ engine,
+ () =>
+ !editingLocked &&
+ !!engine &&
+ stack === 'raster' &&
+ canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent)
+ );
const canExport = !!engine && exportable;
return useMemo(() => {