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.

feat(canvas): save to gallery from the canvas header

Josh Corbettc6585ece6cdd
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c812e60038..f3aeafefc2 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2547,6 +2547,7 @@
"fitBboxToLayers": "Fit frame to layers",
"fitBboxToMasks": "Fit frame to masks",
"fitToView": "Fit to view",
+ "moreSaveOptions": "More save options",
"newCanvas": "New canvas",
"newCanvasConfirm": "Clear all layers and start a fresh canvas? This cannot be undone.",
"newSession": "New session",
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
index 64dd138460..a27b2cfa4b 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
@@ -8,8 +8,9 @@ describe('firstPartyHotkeyCatalog', () => {
// no default keys — Task 46) + `app.openCommandPalette` (webv2-only, mod+k)
// + the seven top-bar redesign commands (alt+mod+enter, mod+p, an unbound
// save, and alt+1..4) + `app.openSettings` (mod+,) + `gallery.toggleStarredOnly`
- // (webv2 starred-only listing filter, unbound).
- expect(firstPartyHotkeyCatalog).toHaveLength(102);
+ // (webv2 starred-only listing filter, unbound) + the two unbound canvas
+ // gallery saves (`canvas.saveToGallery`, `canvas.saveBboxToGallery`).
+ expect(firstPartyHotkeyCatalog).toHaveLength(104);
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openCommandPalette');
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('canvas.mergeDown');
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index df65726a50..194ef3dca9 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -74,6 +74,8 @@ const implemented = new Set([
'canvas.fitBboxToMasks',
'canvas.newSession',
'canvas.nextEntity',
+ 'canvas.saveBboxToGallery',
+ 'canvas.saveToGallery',
'canvas.prevEntity',
'canvas.redo',
'canvas.setFillColorsToDefault',
@@ -249,8 +251,10 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'toggleNonRasterLayers', ['shift+h']),
hotkey('canvas', 'fitBboxToMasks', ['shift+b']),
hotkey('canvas', 'toggleBbox', ['shift+o']),
- // New canvas session: no default keys — assignable via the hotkeys settings.
+ // New canvas session and the gallery saves: no default keys — assignable via the hotkeys settings.
hotkey('canvas', 'newSession', []),
+ hotkey('canvas', 'saveToGallery', []),
+ hotkey('canvas', 'saveBboxToGallery', []),
hotkey('workflows', 'addNode', ['shift+a', 'space']),
hotkey('workflows', 'copySelection', ['mod+c']),
hotkey('workflows', 'pasteSelection', ['mod+v']),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index 8c46b89b99..fa163c2d80 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -4,10 +4,11 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
-import { Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import { Box, HStack, Icon, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
import { useModifierHeld } from '@platform/react/useModifierHeld';
import { Button, IconButton } from '@platform/ui/Button';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { Group } from '@platform/ui/Group';
import { MenuContent } from '@platform/ui/Menu';
import { Tooltip } from '@platform/ui/Tooltip';
import { getCanvasEngine } from '@workbench/canvas-operations/api';
@@ -23,6 +24,7 @@ import {
FrameIcon,
MaximizeIcon,
Redo2Icon,
+ SaveIcon,
SquareDashedBottomIcon,
Trash2Icon,
Undo2Icon,
@@ -44,12 +46,13 @@ import { CANVAS_SNAP_TO_GRID_KEY, canvasSettingsEqual, resolveCanvasSettings } f
import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';
import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';
import { useCanvasEngine } from './useCanvasEngine';
+import { useCanvasGallerySave } from './useCanvasGallerySave';
import { reportStructuralCommit } from './useStructuralCommit';
import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';
type CanvasHeaderEngine = Pick<
CanvasEngineHandle,
- 'diagnostics' | 'document' | 'history' | 'interaction' | 'layers' | 'viewport'
+ 'diagnostics' | 'document' | 'exports' | 'history' | 'interaction' | 'layers' | 'lifecycle' | 'projectId' | 'viewport'
>;
const ZOOM_OPTIONS = zoomMenuOptions();
@@ -68,12 +71,12 @@ const selectModelBase = (project: Project): string | null => {
/**
* Canvas widget header actions, in legacy toolbar order: the zoom-percent menu, a
* reset-view (fit content to view) button, fit-bbox-to-layers / fit-bbox-to-masks,
- * undo / redo, and a new-session menu. Rendered in
- * the widget frame's header slot; resolves the shared engine like the layers header
- * does, and renders nothing until it is available.
+ * undo / redo, save-to-gallery (canvas, with the bbox region in its menu), and a
+ * new-session menu. Rendered in the widget frame's header slot; resolves the
+ * shared engine like the layers header does, and renders nothing until it is
+ * available.
*
- * Excluded per product decision: the project (save/load) menu, a save-to-gallery
- * button (its command/hotkey stays), and the snapshot menu.
+ * Excluded per product decision: the project (save/load) menu and the snapshot menu.
*/
export const CanvasHeaderActions = ({ runtime }: WidgetViewProps) => {
const engine = useCanvasEngine();
@@ -93,6 +96,7 @@ const CanvasHeaderActionsInner = ({
const canUndo = useCanvasCanUndo(engine);
const canRedo = useCanvasCanRedo(engine);
const editingLocked = useCanvasDocumentEditingLocked(engine);
+ const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);
const document = useActiveProjectSelector((project) => project.canvas.document);
const modelBase = useActiveProjectSelector(selectModelBase);
const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
@@ -120,6 +124,7 @@ const CanvasHeaderActionsInner = ({
fitMasksRect,
openNewCanvas,
reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
+ saveToGallery: (region) => void saveToGallery(region),
t,
});
@@ -131,9 +136,10 @@ const CanvasHeaderActionsInner = ({
);
// Commands (hotkey-assignable; catalog ids `canvas.fitBboxToLayers` /
- // `canvas.fitBboxToMasks` / `canvas.newSession`). `useEffectEvent` reads the
- // latest fit rects / dialog opener without re-registering per document change.
- // The new-session command routes through the SAME confirm dialog as the button.
+ // `canvas.fitBboxToMasks` / `canvas.saveToGallery` / `canvas.saveBboxToGallery` /
+ // `canvas.newSession`). `useEffectEvent` reads the latest fit rects / dialog
+ // opener without re-registering per document change. The new-session command
+ // routes through the SAME confirm dialog as the button.
const executeHeaderCommand = useEffectEvent((commandId: string) =>
executeCanvasHeaderCommand(commandId, commandContext())
);
@@ -143,6 +149,8 @@ const CanvasHeaderActionsInner = ({
['canvas.fitBboxToLayers', t('widgets.canvas.controls.fitBboxToLayers'), ['shift+n']],
['canvas.fitBboxToMasks', t('widgets.canvas.controls.fitBboxToMasks'), ['shift+b']],
// No default keys — assignable through the hotkeys settings.
+ ['canvas.saveToGallery', t('widgets.canvas.contextMenu.saveCanvasToGallery'), []],
+ ['canvas.saveBboxToGallery', t('widgets.canvas.contextMenu.saveBboxToGallery'), []],
['canvas.newSession', t('widgets.canvas.controls.newSession'), []],
] as const;
const disposers = entries.flatMap(([id, title, defaultKeys]) => [
@@ -247,6 +255,48 @@ const CanvasHeaderActionsInner = ({
</IconButton>
</Tooltip>
+ <HeaderDivider />
+
+ <Menu.Root positioning={MENU_POSITIONING}>
+ <Group attached>
+ <Tooltip content={t('widgets.canvas.contextMenu.saveCanvasToGallery')}>
+ <IconButton
+ aria-label={t('widgets.canvas.contextMenu.saveCanvasToGallery')}
+ color="fg.muted"
+ disabled={editingLocked || isSaving}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void saveToGallery('canvas')}
+ >
+ {isSaving ? <Spinner size="xs" /> : <SaveIcon />}
+ </IconButton>
+ </Tooltip>
+ <Menu.Trigger asChild>
+ <IconButton
+ aria-label={t('widgets.canvas.controls.moreSaveOptions')}
+ color="fg.muted"
+ disabled={editingLocked || isSaving}
+ minW="0"
+ size="2xs"
+ variant="ghost"
+ w="5"
+ >
+ <ChevronDownIcon size={12} />
+ </IconButton>
+ </Menu.Trigger>
+ </Group>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="11rem" py="1">
+ <Menu.Item value="save-bbox" onClick={() => void saveToGallery('bbox')}>
+ <Icon as={SaveIcon} boxSize="3.5" color="fg.subtle" />
+ <Menu.ItemText fontSize="xs">{t('widgets.canvas.contextMenu.saveBboxToGallery')}</Menu.ItemText>
+ </Menu.Item>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+
<Menu.Root positioning={MENU_POSITIONING}>
<Tooltip content={t('widgets.canvas.controls.newSession')}>
<span style={{ display: 'inline-flex' }}>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
index 45df3daf80..f71fcf43f0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
@@ -48,6 +48,7 @@ const contextOf = (overrides: Partial<CanvasHeaderCommandContext> = {}): CanvasH
fitLayersRect: FIT_LAYERS,
fitMasksRect: FIT_MASKS,
openNewCanvas: vi.fn(),
+ saveToGallery: vi.fn(),
t: (key) => key,
...overrides,
});
@@ -167,6 +168,17 @@ describe('executeCanvasHeaderCommand', () => {
expect(engine.layers.commitStructural).not.toHaveBeenCalled();
});
+ it.each([
+ ['canvas.saveToGallery', 'canvas'],
+ ['canvas.saveBboxToGallery', 'bbox'],
+ ] as const)('%s saves the %s region, unless an operation owns the document', (commandId, region) => {
+ const saveToGallery = vi.fn();
+ executeCanvasHeaderCommand(commandId, contextOf({ editingLocked: true, saveToGallery }));
+ expect(saveToGallery).not.toHaveBeenCalled();
+ executeCanvasHeaderCommand(commandId, contextOf({ saveToGallery }));
+ expect(saveToGallery).toHaveBeenCalledWith(region);
+ });
+
it('ignores an unknown command id', () => {
const openNewCanvas = vi.fn();
const { engine } = createEngine();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
index 9c4ea2f2e1..86317db599 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
@@ -4,6 +4,7 @@ import type {
Rect,
StructuralCommitResult,
} from '@workbench/canvas-engine/api';
+import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';
import { createNewCanvasState } from '@workbench/canvasMigration';
@@ -41,6 +42,8 @@ export interface CanvasHeaderCommandContext extends NewCanvasContext {
/** Opens the confirm dialog. The destructive replace only runs from its confirm. */
readonly openNewCanvas: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
+ /** Composites the region and uploads it to the gallery's current board. */
+ readonly saveToGallery: (region: CanvasGallerySaveRegion) => void;
readonly t: (key: string) => string;
}
@@ -97,5 +100,9 @@ export const executeCanvasHeaderCommand = (commandId: string, ctx: CanvasHeaderC
applyFitBbox(ctx, ctx.fitMasksRect, false);
} else if (commandId === 'canvas.newSession') {
ctx.openNewCanvas();
+ } else if (commandId === 'canvas.saveToGallery' && !ctx.editingLocked) {
+ ctx.saveToGallery('canvas');
+ } else if (commandId === 'canvas.saveBboxToGallery' && !ctx.editingLocked) {
+ ctx.saveToGallery('bbox');
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
new file mode 100644
index 0000000000..9ae445366c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
@@ -0,0 +1,109 @@
+import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, createRef, type Ref, useImperativeHandle } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useCanvasGallerySave } from './useCanvasGallerySave';
+
+const mocks = vi.hoisted(() => ({
+ reportError: vi.fn(),
+ saveCanvasToGallery: vi.fn<(options: { region: CanvasGallerySaveRegion }) => Promise<unknown>>(),
+}));
+
+vi.mock('@workbench/canvas-operations/api', () => ({
+ saveCanvasToGallery: (...args: [{ region: CanvasGallerySaveRegion }]) => mocks.saveCanvasToGallery(...args),
+}));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useWorkbenchCommands: () => ({ notifications: { reportError: mocks.reportError } }),
+ useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: { id: 'project-1' } }) }),
+}));
+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));
+vi.mock('@features/gallery/queries', () => ({ invalidateGallery: vi.fn(() => Promise.resolve()) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+type Handle = ReturnType<typeof useCanvasGallerySave>;
+const engine = { projectId: 'project-1' } as unknown as Parameters<typeof useCanvasGallerySave>[0];
+
+/** Two probes stand in for the header button and the context menu, which each call the hook. */
+const Probe = ({ ref }: { ref: Ref<Handle> }) => {
+ const handle = useCanvasGallerySave(engine);
+ useImperativeHandle(ref, () => handle, [handle]);
+ return null;
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+const header = createRef<Handle>();
+const menu = createRef<Handle>();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const deferred = () => {
+ let resolve!: (value: unknown) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ accountLifecycle.activate('user-a');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <Probe ref={header} />
+ <Probe ref={menu} />
+ </QueryClientProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('useCanvasGallerySave across surfaces', () => {
+ it('runs one save per project at a time and shows it busy on every surface', async () => {
+ const inFlight = deferred();
+ mocks.saveCanvasToGallery.mockReturnValueOnce(inFlight.promise);
+
+ let first: Promise<void> | undefined;
+ await act(() => {
+ first = header.current!.save('canvas');
+ });
+ expect(header.current!.isSaving).toBe(true);
+ expect(menu.current!.isSaving).toBe(true);
+
+ await act(() => menu.current!.save('bbox'));
+ expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ inFlight.resolve({ imageName: 'saved.png', status: 'saved' });
+ await first;
+ });
+ expect(header.current!.isSaving).toBe(false);
+ expect(menu.current!.isSaving).toBe(false);
+ });
+
+ it('releases the gate after a failed save', async () => {
+ mocks.saveCanvasToGallery.mockRejectedValueOnce(new Error('upload failed'));
+ await act(() => header.current!.save('canvas'));
+ expect(mocks.reportError).toHaveBeenCalledOnce();
+ expect(menu.current!.isSaving).toBe(false);
+
+ mocks.saveCanvasToGallery.mockResolvedValueOnce({ imageName: 'saved.png', status: 'saved' });
+ await act(() => menu.current!.save('canvas'));
+ expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index 3368222cc5..a1462c6390 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -5,18 +5,24 @@ import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
+ registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
+import { createKeyedTransientStore } from '@platform/state/externalStore';
import { useQueryClient } from '@tanstack/react-query';
import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';
import { useNotify } from '@workbench/useNotify';
import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { getCanvasGallerySaveErrorAction, withMatchingCanvasProject } from './canvasGallerySaveState';
type CanvasGallerySaveEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'lifecycle' | 'projectId'>;
+/** Projects with a save in flight: the header button and the context menu share the gate and the busy state. */
+const savingProjects = createKeyedTransientStore<string, true>();
+registerAccountOwnedResource({ clear: () => savingProjects.clear(), name: 'canvas-gallery-saves' });
+
export const useCanvasGallerySave = (
engine: CanvasGallerySaveEngine | null
): { isSaving: boolean; save: (region: CanvasGallerySaveRegion) => Promise<void> } => {
@@ -25,21 +31,18 @@ export const useCanvasGallerySave = (
const queries = useWorkbenchQueries();
const { notifications } = useWorkbenchCommands();
const queryClient = useQueryClient();
- const isSavingRef = useRef(false);
- const [isSaving, setIsSaving] = useState(false);
+ const isSaving = savingProjects.useValue(engine?.projectId ?? '') === true;
const save = useCallback(
async (region: CanvasGallerySaveRegion): Promise<void> => {
- if (isSavingRef.current) {
+ const project = queries.getSnapshot().activeProject;
+ if (savingProjects.get(project.id)) {
return;
}
-
- const project = queries.getSnapshot().activeProject;
const owner = captureAccountScope();
await withMatchingCanvasProject(engine, project.id, async (matchedEngine) => {
- isSavingRef.current = true;
- setIsSaving(true);
+ savingProjects.set(project.id, true);
try {
const result = await saveCanvasToGallery({ engine: matchedEngine, project, region });
@@ -67,8 +70,7 @@ export const useCanvasGallerySave = (
getCanvasGallerySaveErrorAction(error, project.id, t('widgets.canvas.contextMenu.saveError'))
);
} finally {
- isSavingRef.current = false;
- setIsSaving(false);
+ savingProjects.delete(project.id);
}
});
},