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(canvas): close canvas operation edit races

joshistoast2e7e927f1278
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 58fe81bd9b..d245fefc94 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -1405,6 +1405,49 @@ describe('createCanvasEngine', () => {
engine.dispose();
});
+ it('cropLayerToBbox aborts when an operation starts during its deferred export', async () => {
+ const pending = createDeferred<Blob>();
+ const document = { ...makeDoc(), layers: [rasterLayer('operation'), rasterLayer('a')] };
+ const { projectId, store } = createReducerBackedStore(document);
+ const bitmapStore = createSpyBitmapStore();
+ const resolver = vi.fn((imageName: string) => (imageName === 'a' ? pending.promise : Promise.resolve(new Blob())));
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore,
+ imageResolver: resolver,
+ projectId,
+ store,
+ });
+ const operationExport = await engine.exportLayerPixels('operation');
+ if (operationExport.status !== 'ok') {
+ throw new Error('expected an operation guard');
+ }
+ (store.dispatch as Mock).mockClear();
+ bitmapStore.markLayerDirty.mockClear();
+
+ const crop = engine.cropLayerToBbox('a');
+ await vi.waitFor(() => expect(resolver).toHaveBeenCalledWith('a', expect.any(AbortSignal)));
+ const cleanupPreview = vi.fn();
+ engine.canvasOperations.start({
+ cleanupPreview,
+ guard: operationExport.guard,
+ identity: { kind: 'filter', layerId: 'operation', projectId },
+ });
+ pending.resolve(new Blob());
+
+ await expect(crop).resolves.toEqual({ status: 'busy' });
+ expect(engine.getDocument()).toEqual(document);
+ expect(store.dispatch).not.toHaveBeenCalled();
+ expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(engine.stores.canUndo.get()).toBe(false);
+ expect(cleanupPreview).not.toHaveBeenCalled();
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'filter', layerId: 'operation' },
+ status: 'active',
+ });
+ engine.dispose();
+ });
+
it('cropLayerToBbox reports busy during an open gesture', async () => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
@@ -6754,6 +6797,29 @@ describe('commitRasterFilterResult', () => {
harness.engine.dispose();
});
+ it('does not publish when an operation starts during durable-image decode', async () => {
+ const harness = await createPendingGuardHarness();
+ const cleanupPreview = vi.fn();
+ harness.engine.canvasOperations.start({
+ cleanupPreview,
+ guard: harness.guard,
+ identity: { kind: 'select-object', layerId: harness.layer.id, projectId: 'p1' },
+ });
+
+ harness.decoded.resolve(new Blob());
+
+ await expect(harness.pending).resolves.toEqual({ status: 'busy' });
+ expect(harness.engine.getDocument()).toEqual(harness.document);
+ expect(harness.store.dispatch).not.toHaveBeenCalled();
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(cleanupPreview).not.toHaveBeenCalled();
+ expect(harness.engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'select-object' },
+ status: 'active',
+ });
+ harness.engine.dispose();
+ });
+
it('returns missing without mutation when the source is deleted', async () => {
const harness = await createPendingGuardHarness();
harness.setDocument({ ...harness.document, layers: [] });
@@ -7734,6 +7800,48 @@ describe('commitGeneratedImageResult', () => {
harness.engine.dispose();
});
+ it('does not publish when an operation starts during generated-image decode', async () => {
+ const harness = await createPendingGuardHarness();
+ const cleanupPreview = vi.fn();
+ harness.engine.canvasOperations.start({
+ cleanupPreview,
+ guard: harness.exported.guard,
+ identity: { kind: 'filter', layerId: harness.source.id, projectId: 'p1' },
+ });
+
+ harness.decoded.resolve(new Blob());
+
+ await expect(harness.pending).resolves.toEqual({ status: 'busy' });
+ expect(harness.engine.getDocument()).toEqual(harness.document);
+ expect(harness.store.dispatch).not.toHaveBeenCalled();
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(cleanupPreview).not.toHaveBeenCalled();
+ expect(harness.engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'filter' },
+ status: 'active',
+ });
+ harness.engine.dispose();
+ });
+
+ it('does not publish when an operation starts and ends during generated-image decode', async () => {
+ const harness = await createPendingGuardHarness();
+ const operation = harness.engine.canvasOperations.start({
+ cleanupPreview: vi.fn(),
+ guard: harness.exported.guard,
+ identity: { kind: 'filter', layerId: harness.source.id, projectId: 'p1' },
+ });
+ operation?.cancel();
+
+ harness.decoded.resolve(new Blob());
+
+ await expect(harness.pending).resolves.toEqual({ status: 'busy' });
+ expect(harness.engine.getDocument()).toEqual(harness.document);
+ expect(harness.store.dispatch).not.toHaveBeenCalled();
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });
+ harness.engine.dispose();
+ });
+
it('returns aborted without resolving the generated image when already cancelled', async () => {
const source = workflowRaster();
const resolver = vi.fn(() => Promise.resolve(new Blob()));
@@ -9379,6 +9487,42 @@ describe('guarded filter previews', () => {
}
);
+ it('does not clear history while document editing is locked', async () => {
+ const layer = guardableLayer('L');
+ const document = { ...emptyDoc(), layers: [layer] };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ expect((await engine.exportLayerPixels(layer.id)).status).toBe('ok');
+ engine.commitStructural(
+ 'Rename',
+ { id: layer.id, patch: { name: 'Renamed' }, type: 'updateCanvasLayer' },
+ { id: layer.id, patch: { name: layer.name }, type: 'updateCanvasLayer' }
+ );
+ const guard = engine.captureLayerExportGuard(layer.id);
+ if (!guard) {
+ throw new Error('expected an operation guard');
+ }
+ const operation = engine.canvasOperations.start({
+ cleanupPreview: vi.fn(),
+ guard,
+ identity: { kind: 'filter', layerId: layer.id, projectId },
+ });
+
+ engine.clearHistory();
+
+ expect(engine.stores.canUndo.get()).toBe(true);
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({ identity: { kind: 'filter' }, status: 'active' });
+ operation?.cancel();
+ engine.clearHistory();
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.dispose();
+ });
+
it('invalidates the owned filter session when its guarded source changes', async () => {
const layer = guardableLayer('L');
const document = { ...emptyDoc(), layers: [layer] };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index a27c4a24e1..5e12dfbfe1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1558,12 +1558,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
canvasOperations = createCanvasOperationController({ isGuardCurrent: isLayerExportGuardCurrent });
const documentEditOwner = Symbol('canvas-operation-document-edit-owner');
+ type DocumentEditPermit = { epoch: number; owner?: symbol };
+ let documentEditEpoch = 0;
+ let documentEditingLocked = false;
const syncDocumentEditingLock = (): void => {
- stores.documentEditingLocked.set(canvasOperations.getSnapshot().status === 'active');
+ const nextLocked = canvasOperations.getSnapshot().status === 'active';
+ if (nextLocked !== documentEditingLocked) {
+ documentEditingLocked = nextLocked;
+ documentEditEpoch += 1;
+ }
+ stores.documentEditingLocked.set(nextLocked);
};
const unsubscribeDocumentEditingLock = canvasOperations.subscribe(syncDocumentEditingLock);
const canEditDocument = (owner?: symbol): boolean =>
owner === documentEditOwner || !stores.documentEditingLocked.get();
+ const captureDocumentEditPermit = (owner?: symbol): DocumentEditPermit | null =>
+ canEditDocument(owner) ? { epoch: documentEditEpoch, owner } : null;
+ const isDocumentEditPermitCurrent = (permit: DocumentEditPermit): boolean =>
+ permit.owner === documentEditOwner || (!stores.documentEditingLocked.get() && permit.epoch === documentEditEpoch);
const ensureLayerCaches = (doc: CanvasDocumentContractV2): void => {
for (const layer of doc.layers) {
@@ -1736,7 +1748,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const cropLayerToBbox = async (layerId: string): Promise<CropLayerResult> => {
- if (!canEditDocument() || pipeline.isGestureActive()) {
+ const permit = captureDocumentEditPermit();
+ if (!permit || pipeline.isGestureActive()) {
return { status: 'busy' };
}
endNudgeBurst();
@@ -1755,6 +1768,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
try {
const exported = await exportBakedLayerPixels(layerId, { includeDisabled: true });
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
if (exported.status !== 'ok') {
switch (exported.status) {
case 'missing':
@@ -1772,7 +1788,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (!liveDocument || !liveLayer) {
return { status: 'missing' };
}
- if (pipeline.isGestureActive()) {
+ if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {
return { status: 'busy' };
}
if (liveLayer.isLocked) {
@@ -1848,6 +1864,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const afterPixels = { pixels: cropped, rect: cropRect };
const preparedAfter = prepareGeneratedPaintCache(layerId, afterPixels.rect, afterPixels.pixels);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
publishSnapshot(after, preparedAfter);
history.push({
bytes:
@@ -1866,7 +1885,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const copyLayerToRaster = async (layerId: string): Promise<string | null> => {
- if (!canEditDocument()) {
+ const permit = captureDocumentEditPermit();
+ if (!permit) {
return null;
}
if (pipeline.isGestureActive()) {
@@ -1879,10 +1899,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return null;
}
const baked = await exportBakedLayerPixels(layerId, { includeDisabled: true });
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return null;
+ }
if (baked.status !== 'ok') {
return null;
}
- if (pipeline.isGestureActive() || !isLayerExportGuardCurrent(baked.guard) || baked.guard.layer !== sourceLayer) {
+ if (
+ !isDocumentEditPermitCurrent(permit) ||
+ pipeline.isGestureActive() ||
+ !isLayerExportGuardCurrent(baked.guard) ||
+ baked.guard.layer !== sourceLayer
+ ) {
return null;
}
const liveDocument = mirror.getDocument();
@@ -1923,6 +1951,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
);
installGeneratedPaintCache(prepared);
};
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return null;
+ }
apply();
history.push({
bytes: baked.rect.width * baked.rect.height * 4 + 256,
@@ -3860,7 +3891,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
signal?: AbortSignal,
owner?: symbol
): Promise<ReplaceSelectionFromImageResult> => {
- if (!canEditDocument(owner)) {
+ const permit = captureDocumentEditPermit(owner);
+ if (!permit) {
return { status: 'busy' };
}
if (signal?.aborted) {
@@ -3868,10 +3900,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
try {
const blob = await imageResolver(image.imageName, signal);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
if (signal?.aborted) {
return { status: 'aborted' };
}
const bitmap = await backend.createImageBitmap(blob);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ bitmap.close();
+ return { status: 'busy' };
+ }
if (signal?.aborted) {
bitmap.close();
return { status: 'aborted' };
@@ -3902,7 +3941,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {
return { status: 'unsupported' };
}
- if (pipeline.isGestureActive()) {
+ if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {
return { status: 'busy' };
}
if (!isLayerExportGuardCurrent(guard)) {
@@ -3912,6 +3951,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return { status: 'aborted' };
}
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
selection.replaceMask({ rect: { ...rect }, surface: pixels });
return { status: 'selected' };
} catch (error) {
@@ -4018,7 +4060,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
options: CommitRasterFilterOptions,
owner?: symbol
): Promise<CommitRasterFilterResult> => {
- if (!canEditDocument(owner)) {
+ const permit = captureDocumentEditPermit(owner);
+ if (!permit) {
return { status: 'busy' };
}
if (options.signal?.aborted) {
@@ -4026,10 +4069,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
try {
const blob = await imageResolver(options.image.imageName, options.signal);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
return { status: 'aborted' };
}
const bitmap = await backend.createImageBitmap(blob);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ bitmap.close();
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
bitmap.close();
return { status: 'aborted' };
@@ -4057,7 +4107,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {
return { status: 'unsupported' };
}
- if (pipeline.isGestureActive()) {
+ if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {
return { status: 'busy' };
}
if (!isLayerExportGuardCurrent(options.guard)) {
@@ -4067,6 +4117,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return { status: 'aborted' };
}
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
endNudgeBurst();
const image = structuredClone(options.image);
const rect = { ...options.rect };
@@ -4229,7 +4282,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
options: CommitGeneratedImageOptions,
owner?: symbol
): Promise<CommitGeneratedImageResult> => {
- if (!canEditDocument(owner)) {
+ const permit = captureDocumentEditPermit(owner);
+ if (!permit) {
return { status: 'busy' };
}
if (options.signal?.aborted) {
@@ -4242,6 +4296,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;
}
| { result: CommitGeneratedImageResult } => {
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { result: { status: 'busy' } };
+ }
const document = mirror.getDocument();
const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);
if (!document || !liveLayer) {
@@ -4264,11 +4321,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
try {
const blob = await imageResolver(options.image.imageName, options.signal);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
return { status: 'aborted' };
}
const bitmap = await backend.createImageBitmap(blob);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ bitmap.close();
+ return { status: 'busy' };
+ }
if (options.signal?.aborted) {
bitmap.close();
return { status: 'aborted' };
@@ -4462,7 +4526,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
upperLayerId: string,
operation: BooleanRasterOperation
): Promise<BooleanRasterResult> => {
- if (!canEditDocument() || pipeline.isGestureActive()) {
+ const permit = captureDocumentEditPermit();
+ if (!permit || pipeline.isGestureActive()) {
return 'busy';
}
endNudgeBurst();
@@ -4490,6 +4555,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
exportBakedLayerPixels(upper.id),
exportBakedLayerPixels(below.id),
]);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return 'busy';
+ }
if (upperPixels.status !== 'ok' || belowPixels.status !== 'ok') {
if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {
return 'not-ready';
@@ -4504,7 +4572,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
return 'empty';
}
- if (pipeline.isGestureActive()) {
+ if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {
return 'busy';
}
if (
@@ -4595,6 +4663,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
installGeneratedPaintCache(prepared);
};
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return 'busy';
+ }
apply();
history.push({
bytes: resultRect.width * resultRect.height * 4 + 256,
@@ -4631,7 +4702,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const extractMaskedArea = async (maskLayerId: string): Promise<ExtractMaskedAreaResult> => {
- if (!canEditDocument() || pipeline.isGestureActive()) {
+ const permit = captureDocumentEditPermit();
+ if (!permit || pipeline.isGestureActive()) {
return { status: 'busy' };
}
endNudgeBurst();
@@ -4668,6 +4740,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
exportBakedLayerPixels(maskLayerId, { includeDisabled: true }),
Promise.all(contributors.map((layer) => rasterizeLayerPixels(layer.id))),
]);
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
if (maskPixels.status !== 'ok') {
return { status: maskPixels.status === 'not-ready' ? 'not-ready' : 'empty' };
}
@@ -4676,7 +4751,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
status: contributorPixels.some((pixels) => pixels.status === 'not-ready') ? 'not-ready' : 'empty',
};
}
- if (pipeline.isGestureActive()) {
+ if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {
return { status: 'busy' };
}
if (maskPixels.guard.layer !== maskLayer || !isLayerExportGuardCurrent(maskPixels.guard)) {
@@ -4770,6 +4845,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
installGeneratedPaintCache(prepared);
};
+ if (!isDocumentEditPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
apply();
history.push({
bytes: resultRect.width * resultRect.height * 4 + 256,
@@ -6097,6 +6175,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const clearHistory = (): void => {
+ if (!canEditDocument()) {
+ return;
+ }
// `history.clear` notifies subscribers, so `syncHistoryStores` refreshes
// canUndo/canRedo — the header buttons disable in lockstep.
endNudgeBurst();
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsx
index 6a342bce80..f014609bd6 100644
--- a/invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsx
@@ -11,30 +11,41 @@ const TOGGLE_DOT_CHECKED_HOVER_STYLES = { bg: 'accent.emphasized', borderColor:
export interface ToggleDotProps extends Omit<BoxProps, 'aria-label' | 'as' | 'children' | 'onChange' | 'onClick'> {
checked: boolean;
+ disabled?: boolean;
label: string;
tooltip?: ReactNode;
onCheckedChange: (checked: boolean) => void;
}
/** Small pressable dot for compact enabled/disabled state toggles. */
-export const ToggleDot = ({ checked, label, onCheckedChange, tooltip = label, ...rest }: ToggleDotProps) => {
+export const ToggleDot = ({
+ checked,
+ disabled = false,
+ label,
+ onCheckedChange,
+ tooltip = label,
+ ...rest
+}: ToggleDotProps) => {
const handleClick = useCallback(() => onCheckedChange(!checked), [checked, onCheckedChange]);
+ const nativeDisabled = disabled ? { disabled: true } : {};
const dot = (
<Box
as="button"
+ {...nativeDisabled}
+ aria-disabled={disabled || undefined}
aria-label={label}
aria-pressed={checked}
bg={checked ? 'accent.solid' : 'transparent'}
borderColor={checked ? 'accent.solid' : 'border.emphasized'}
borderWidth="1px"
- cursor="pointer"
+ cursor={disabled ? 'not-allowed' : 'pointer'}
flexShrink="0"
h="3"
rounded="full"
transition="background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)"
w="3"
_hover={checked ? TOGGLE_DOT_CHECKED_HOVER_STYLES : TOGGLE_DOT_HOVER_STYLES}
- onClick={handleClick}
+ onClick={disabled ? undefined : handleClick}
{...rest}
/>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index 17df03f051..10f0e024b8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -276,7 +276,7 @@ const CanvasHeaderActionsInner = ({
</Portal>
</Menu.Root>
- <CanvasSettingsMenu engine={engine} />
+ <CanvasSettingsMenu editingLocked={editingLocked} engine={engine} />
<ConfirmDialog
body={t('widgets.canvas.controls.newCanvasConfirm')}
@@ -299,7 +299,7 @@ const HeaderDivider = () => <Box bg="border.subtle" flexShrink={0} h="4" mx="1"
* actions (matching legacy `CanvasSettingsPopover`). `closeOnSelect={false}` keeps
* it open while toggling. Settings persist per-project and never enter undo history.
*/
-const CanvasSettingsMenu = ({ engine }: { engine: CanvasEngine }) => {
+const CanvasSettingsMenu = ({ editingLocked, engine }: { editingLocked: boolean; engine: CanvasEngine }) => {
const { t } = useTranslation();
const dispatch = useWorkbenchDispatch();
const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
@@ -355,7 +355,7 @@ const CanvasSettingsMenu = ({ engine }: { engine: CanvasEngine }) => {
<Icon as={BugIcon} boxSize="3.5" color="fg.subtle" />
<Menu.ItemText fontSize="xs">{t('widgets.canvas.settings.logDebugInfo')}</Menu.ItemText>
</Menu.Item>
- <Menu.Item value="debug-clear-history" onClick={() => engine.clearHistory()}>
+ <Menu.Item disabled={editingLocked} value="debug-clear-history" onClick={() => engine.clearHistory()}>
<Icon as={Trash2Icon} boxSize="3.5" color="fg.subtle" />
<Menu.ItemText fontSize="xs">{t('widgets.canvas.settings.clearHistory')}</Menu.ItemText>
</Menu.Item>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
index b175a80df5..2b02c49b30 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
@@ -154,6 +154,7 @@ export const LayerGroupSection = ({
<LayerListItem
key={layer.id}
dispatch={dispatch}
+ editingLocked={editingLocked}
engine={engine}
index={globalIndexById.get(layer.id) ?? 0}
isSelected={layer.id === selectedLayerId}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.ts
new file mode 100644
index 0000000000..d3a63a7f57
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { getLayerListItemInteractionState } from './LayerListItem';
+
+describe('getLayerListItemInteractionState', () => {
+ it('keeps selection available while disabling document edits and sorting during an operation', () => {
+ expect(getLayerListItemInteractionState(true)).toEqual({
+ canRename: false,
+ canSelect: true,
+ canToggleLock: false,
+ canToggleVisibility: false,
+ sortableDisabled: true,
+ });
+ });
+
+ it('enables ordinary row editing and sorting when document editing is unlocked', () => {
+ expect(getLayerListItemInteractionState(false)).toEqual({
+ canRename: true,
+ canSelect: true,
+ canToggleLock: true,
+ canToggleVisibility: true,
+ sortableDisabled: false,
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
index 37f0a6fbd4..1cc6931682 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
@@ -27,6 +27,7 @@ const layerBadgeKey = (layer: CanvasLayerContract): string => {
interface LayerListItemProps {
dispatch: Dispatch<WorkbenchAction>;
+ editingLocked: boolean;
engine: CanvasEngine | null;
index: number;
isSelected: boolean;
@@ -34,6 +35,14 @@ interface LayerListItemProps {
layers: readonly CanvasLayerContract[];
}
+export const getLayerListItemInteractionState = (editingLocked: boolean) => ({
+ canRename: !editingLocked,
+ canSelect: true,
+ canToggleLock: !editingLocked,
+ canToggleVisibility: !editingLocked,
+ sortableDisabled: editingLocked,
+});
+
/**
* One layer row: thumbnail, name (double-click to rename), type badge,
* visibility + lock toggles, a properties popover (blend mode + the layer's
@@ -42,9 +51,21 @@ interface LayerListItemProps {
* constraint so clicks, double-click rename, and the row buttons still work;
* the selected layer's opacity (and mask fill swatch) lives in the panel header.
*/
-export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, layers }: LayerListItemProps) => {
+export const LayerListItem = ({
+ dispatch,
+ editingLocked,
+ engine,
+ index,
+ isSelected,
+ layer,
+ layers,
+}: LayerListItemProps) => {
const { t } = useTranslation();
- const { isDragging, listeners, setNodeRef, transform, transition } = useSortable({ id: layer.id });
+ const interaction = getLayerListItemInteractionState(editingLocked);
+ const { isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ disabled: interaction.sortableDisabled,
+ id: layer.id,
+ });
const [isEditing, setIsEditing] = useState(false);
const [draftName, setDraftName] = useState(layer.name);
const [contextMenuTarget, setContextMenuTarget] = useState<CanvasLayerContextMenuTarget | null>(null);
@@ -61,10 +82,10 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
);
const handleSelect = useCallback(() => {
- if (!isSelected) {
+ if (interaction.canSelect && !isSelected) {
dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });
}
- }, [dispatch, isSelected, layer.id]);
+ }, [dispatch, interaction.canSelect, isSelected, layer.id]);
const patchBase = useCallback(
(label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {
@@ -137,7 +158,7 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
return (
<Box ref={setNodeRef} style={dndStyle}>
<Row
- {...listeners}
+ {...(interaction.sortableDisabled ? {} : listeners)}
active={isSelected ? 'muted' : undefined}
cursor={isDragging ? 'grabbing' : 'default'}
display="flex"
@@ -153,6 +174,7 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
<Input
autoFocus
aria-label={t('widgets.layers.actions.rename')}
+ disabled={!interaction.canRename}
size="2xs"
value={draftName}
onBlur={commitName}
@@ -161,7 +183,13 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
onPointerDown={stopPropagation}
/>
) : (
- <Text fontSize="2xs" fontWeight="700" truncate onDoubleClick={startEditing}>
+ <Text
+ aria-disabled={!interaction.canRename}
+ fontSize="2xs"
+ fontWeight="700"
+ truncate
+ onDoubleClick={interaction.canRename ? startEditing : undefined}
+ >
{layer.name}
</Text>
)}
@@ -172,6 +200,8 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
<Box flexShrink="0" onClick={stopPropagation} onPointerDown={stopPropagation}>
<ToggleDot
checked={layer.isEnabled}
+ cursor={interaction.canToggleVisibility ? 'pointer' : 'not-allowed'}
+ disabled={!interaction.canToggleVisibility}
label={t('widgets.layers.actions.toggleVisibility')}
onCheckedChange={handleToggleVisible}
/>
@@ -179,6 +209,7 @@ export const LayerListItem = ({ dispatch, engine, index, isSelected, layer, laye
<IconButton
aria-label={t('widgets.layers.actions.toggleLock')}
color={layer.isLocked ? 'fg' : 'fg.subtle'}
+ disabled={!interaction.canToggleLock}
size="2xs"
variant="ghost"
onClick={handleToggleLock}