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): harden gallery context saves

joshistoast8d34539b74dc
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
index f6f55dff0b..a8a9c320eb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
@@ -1,6 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop -- the container ref callback is intentionally re-created when `engine` changes, so a project switch detaches the old engine and attaches the new one. */
import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
-import type { CSSProperties, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent } from 'react';
+import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react';
import { Box } from '@chakra-ui/react';
import { shouldFocusCanvasSurface } from '@workbench/widgets/canvas/surfaceFocus';
@@ -49,15 +49,7 @@ const focusCanvasSurface = (event: ReactPointerEvent<HTMLDivElement>) => {
* is owned entirely by the engine via the overlay, so this component never
* re-renders on interaction.
*/
-export const CanvasSurface = ({
- engine,
- onContextMenu,
-}: {
- engine: CanvasEngine;
- /** Right-click on the surface: the widget hit-tests the layer under the cursor
- * and opens the shared layer context menu (or suppresses the browser menu). */
- onContextMenu?: (event: ReactMouseEvent<HTMLDivElement>) => void;
-}) => {
+export const CanvasSurface = ({ engine }: { engine: CanvasEngine }) => {
const screenRef = useRef<HTMLCanvasElement>(null);
const overlayRef = useRef<HTMLCanvasElement>(null);
@@ -99,7 +91,6 @@ export const CanvasSurface = ({
position="relative"
tabIndex={-1}
w="full"
- onContextMenu={onContextMenu}
onPointerDownCapture={focusCanvasSurface}
>
<canvas ref={screenRef} style={CANVAS_STYLE} />
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index ec79a8f16e..aa79aea93e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -24,7 +24,11 @@ import { useTranslation } from 'react-i18next';
import { gridSizeForModelBase } from './bboxGrid';
import { CanvasBottomControls } from './CanvasBottomControls';
import { CanvasBottomOverlay } from './CanvasBottomOverlay';
-import { resolveCanvasContextMenu, type CanvasContextMenuTarget } from './canvasContextMenu';
+import {
+ resolveCanvasContextMenu,
+ resolveCanvasContextMenuBranch,
+ type CanvasContextMenuTarget,
+} from './canvasContextMenu';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
import { getCanvasInteractionCapabilities } from './canvasInteractionLock';
import { CanvasSaveToGallerySubmenu } from './CanvasSaveToGallerySubmenu';
@@ -401,17 +405,26 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
: null,
[contextMenuTarget]
);
- const isSaveToGalleryDisabled = isSaving || isInteractionLocked;
+ const contextMenuBranch = resolveCanvasContextMenuBranch(contextMenuTarget, engine !== null);
+ const isSaveToGalleryDisabled = !engine || isSaving || isInteractionLocked;
const saveToGallerySubmenu = useMemo(
() => <CanvasSaveToGallerySubmenu disabled={isSaveToGalleryDisabled} onSave={saveToGallery} />,
[isSaveToGalleryDisabled, saveToGallery]
);
return (
- <Box aria-label={t('widgets.canvas.surface')} bg="bg.inset" h="full" overflow="hidden" position="relative" w="full">
+ <Box
+ aria-label={t('widgets.canvas.surface')}
+ bg="bg.inset"
+ h="full"
+ overflow="hidden"
+ position="relative"
+ w="full"
+ onContextMenu={handleSurfaceContextMenu}
+ >
{engine ? (
<>
- <CanvasSurface engine={engine} onContextMenu={handleSurfaceContextMenu} />
+ <CanvasSurface engine={engine} />
<ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />
<CanvasLayerContextMenu
additionalItems={saveToGallerySubmenu}
@@ -421,13 +434,13 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
target={layerContextMenuTarget}
onClose={closeContextMenu}
/>
- {contextMenuTarget && !layerContextMenuTarget ? (
- <CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>
- {saveToGallerySubmenu}
- </CanvasGlobalContextMenu>
- ) : null}
</>
) : null}
+ {contextMenuBranch === 'global' && contextMenuTarget ? (
+ <CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>
+ {saveToGallerySubmenu}
+ </CanvasGlobalContextMenu>
+ ) : null}
{/*
* Floating bottom-center chrome: the staging bar (when active) stacks
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
index a71d756b9f..a27b159dec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
-import { resolveCanvasContextMenu } from './canvasContextMenu';
+import { resolveCanvasContextMenu, resolveCanvasContextMenuBranch } from './canvasContextMenu';
const baseOptions = {
clientX: 240,
@@ -48,4 +48,14 @@ describe('resolveCanvasContextMenu', () => {
target: { layerId: null, x: 240, y: 160 },
});
});
+
+ it('opens the global menu without a hit-test when the engine is unavailable', () => {
+ const resolution = resolveCanvasContextMenu(baseOptions);
+
+ expect(resolution).toEqual({
+ preventDefault: true,
+ target: { layerId: null, x: 240, y: 160 },
+ });
+ expect(resolveCanvasContextMenuBranch(resolution.target, false)).toBe('global');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
index 435bbd7f8c..707ce0e60f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
@@ -19,6 +19,19 @@ interface CanvasContextMenuResolution {
target: CanvasContextMenuTarget | null;
}
+export type CanvasContextMenuBranch = 'global' | 'layer' | null;
+
+export const resolveCanvasContextMenuBranch = (
+ target: CanvasContextMenuTarget | null,
+ hasEngine: boolean
+): CanvasContextMenuBranch => {
+ if (!target) {
+ return null;
+ }
+
+ return target.layerId !== null && hasEngine ? 'layer' : 'global';
+};
+
export const resolveCanvasContextMenu = ({
clientX,
clientY,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts
new file mode 100644
index 0000000000..82dc1e088d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getCanvasGallerySaveErrorAction, withMatchingCanvasProject } from './canvasGallerySaveState';
+
+describe('withMatchingCanvasProject', () => {
+ it('does not run save, refresh, or error effects for a mismatched engine and project', () => {
+ const save = vi.fn();
+ const refresh = vi.fn();
+ const recordError = vi.fn();
+
+ const result = withMatchingCanvasProject({ projectId: 'engine-project' }, 'active-project', () => {
+ save();
+ refresh();
+ recordError();
+ });
+
+ expect(result).toBeUndefined();
+ expect(save).not.toHaveBeenCalled();
+ expect(refresh).not.toHaveBeenCalled();
+ expect(recordError).not.toHaveBeenCalled();
+ });
+});
+
+describe('getCanvasGallerySaveErrorAction', () => {
+ it('maps a save failure to one localized record with diagnostic context', () => {
+ expect(
+ getCanvasGallerySaveErrorAction(new Error('backend exploded'), 'project-1', "Couldn't save to gallery")
+ ).toEqual({
+ area: 'canvas-save-to-gallery',
+ context: { error: 'backend exploded' },
+ message: "Couldn't save to gallery",
+ namespace: 'canvas',
+ projectId: 'project-1',
+ type: 'recordError',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts
new file mode 100644
index 0000000000..9a2f4d0db1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts
@@ -0,0 +1,26 @@
+interface CanvasProjectIdentity {
+ readonly projectId: string;
+}
+
+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+export const getCanvasGallerySaveErrorAction = (error: unknown, projectId: string, message: string) => ({
+ area: 'canvas-save-to-gallery',
+ context: { error: toErrorMessage(error) },
+ message,
+ namespace: 'canvas' as const,
+ projectId,
+ type: 'recordError' as const,
+});
+
+export const withMatchingCanvasProject = <Engine extends CanvasProjectIdentity, Result>(
+ engine: Engine | null,
+ projectId: string,
+ run: (engine: Engine) => Result
+): Result | undefined => {
+ if (!engine || engine.projectId !== projectId) {
+ return undefined;
+ }
+
+ return run(engine);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index e67b4c4107..0054f0661d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -6,7 +6,7 @@ import { useWorkbenchStore } from '@workbench/WorkbenchContext';
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+import { getCanvasGallerySaveErrorAction, withMatchingCanvasProject } from './canvasGallerySaveState';
export const useCanvasGallerySave = (
engine: CanvasEngine | null
@@ -19,44 +19,39 @@ export const useCanvasGallerySave = (
const save = useCallback(
async (region: CanvasGallerySaveRegion): Promise<void> => {
- if (!engine || isSavingRef.current) {
+ if (isSavingRef.current) {
return;
}
- isSavingRef.current = true;
- setIsSaving(true);
const project = store.getSnapshot().activeProject;
- try {
- const result = await saveCanvasToGallery({ engine, project, region });
-
- if (result.status === 'saved') {
- store.dispatch({ projectId: project.id, type: 'touchGalleryImagesRefresh' });
- notify.success(
- t('widgets.canvas.contextMenu.saved'),
- t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })
- );
- } else if (result.status === 'empty') {
- notify.info(t('widgets.canvas.contextMenu.empty'));
- } else if (result.status === 'stale') {
- notify.info(t('widgets.canvas.contextMenu.stale'));
- } else {
- notify.info(t('widgets.canvas.contextMenu.notReady'));
+ await withMatchingCanvasProject(engine, project.id, async (matchedEngine) => {
+ isSavingRef.current = true;
+ setIsSaving(true);
+
+ try {
+ const result = await saveCanvasToGallery({ engine: matchedEngine, project, region });
+
+ if (result.status === 'saved') {
+ store.dispatch({ projectId: project.id, type: 'touchGalleryImagesRefresh' });
+ notify.success(
+ t('widgets.canvas.contextMenu.saved'),
+ t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })
+ );
+ } else if (result.status === 'empty') {
+ notify.info(t('widgets.canvas.contextMenu.empty'));
+ } else if (result.status === 'stale') {
+ notify.info(t('widgets.canvas.contextMenu.stale'));
+ } else {
+ notify.info(t('widgets.canvas.contextMenu.notReady'));
+ }
+ } catch (error: unknown) {
+ store.dispatch(getCanvasGallerySaveErrorAction(error, project.id, t('widgets.canvas.contextMenu.saveError')));
+ } finally {
+ isSavingRef.current = false;
+ setIsSaving(false);
}
- } catch (error: unknown) {
- const message = toErrorMessage(error);
- store.dispatch({
- area: 'canvas-save-to-gallery',
- message,
- namespace: 'canvas',
- projectId: project.id,
- type: 'recordError',
- });
- notify.error(t('widgets.canvas.contextMenu.saveError'), message);
- } finally {
- isSavingRef.current = false;
- setIsSaving(false);
- }
+ });
},
[engine, notify, store, t]
);