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
feat(canvas): save layers to a chosen board
Josh Corbettac1126c0f835
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdxindex ceeb399f26..adcebc2c5a 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx@@ -184,7 +184,7 @@ The gear button in the header opens the canvas settings. They are saved with the## Saving and sharing a canvas-The canvas belongs to its project and is saved with it automatically. To keep a finished image, use **Save Canvas to Gallery** or **Save BBox to Gallery**, or accept results and save individual layers with **Save layer to uploads**. To share a whole canvas, with its layers, masks and settings, export the project as an `.invk` file; see [Projects](/users-guide/projects/introduction/#exporting-and-importing).+The canvas belongs to its project and is saved with it automatically. To keep a finished image, use **Save Canvas to Gallery** or **Save BBox to Gallery**, or accept results and save individual layers to a board with **Save layer to board**. To share a whole canvas, with its layers, masks and settings, export the project as an `.invk` file; see [Projects](/users-guide/projects/introduction/#exporting-and-importing).## Copying and pastingdiff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdxindex bb27657b9b..9e2caf58c4 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx@@ -73,7 +73,7 @@ The history keeps the last 64 steps. It lasts only while the project is open inRight-click a layer, or select it and press **Shift+F10**, for its menu. Right-clicking the canvas opens the same menu for the selected layer.-<Image src={layersContext} alt="The menu of a raster layer, with Transform, Rename layer, Fit to bbox, Add adjustment, Add regenerate region, Filter, Select object, Merge down, Copy to, Convert to, Crop layer to bbox, Save layer to uploads, Disable layer, Lock layer, Color label and Delete layer." width={500} />+<Image src={layersContext} alt="The menu of a raster layer, with Transform, Rename layer, Fit to bbox, Add adjustment, Add regenerate region, Filter, Select object, Merge down, Copy to, Convert to, Crop layer to bbox, Save layer to board, Disable layer, Lock layer, Bookmark for quick switch, Color label and Delete layer." width={500} />The icons at the top **Arrange** the layer (move it to the front, forward, backward or to the back), **Duplicate layer** and **Group layers**. Below them:@@ -81,7 +81,7 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw* **Rename layer** and **Fit to bbox** (scale the layer to fit inside the generation frame).* **Merge down**.* **Copy to** — including **Copy layer to clipboard**, and copies to other layer types.- * **Crop layer to bbox** and **Save layer to uploads** (save it to the Gallery's Uploads).+ * **Crop layer to bbox** and **Save layer to board** (save it to the Gallery as an upload, in Uncategorized or a board you pick from its submenu).* **Disable layer**, **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is temporary and is not saved in the project. It can reset when the canvas is released, for example after switching away from its project, and resets on reload.* **Delete layer**.* **Raster layers:**diff --git a/docs/src/content/docs/Users Guide/assets/layers-context-menu.webp b/docs/src/content/docs/Users Guide/assets/layers-context-menu.webpindex ec96ca1fff..d7620c46df 100644Binary files a/docs/src/content/docs/Users Guide/assets/layers-context-menu.webp and b/docs/src/content/docs/Users Guide/assets/layers-context-menu.webp differdiff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 3b39a11440..9f85084f98 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -887,6 +887,7 @@"source:src/workbench/hotkeys/shortcutHints.ts","source:src/workbench/hotkeys/targetWidget.ts","source:src/workbench/iconResolver.tsx",+ "source:src/workbench/image-actions/GalleryBoardDestinationGroups.tsx","source:src/workbench/image-actions/recallParametersBridge.ts","source:src/workbench/image-actions/useFindGalleryItem.ts","source:src/workbench/invocation.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 4c1b36ed33..002ee7bca7 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1579,6 +1579,7 @@"source:src/workbench/hotkeys/shortcutHints.ts","source:src/workbench/hotkeys/targetWidget.ts","source:src/workbench/iconResolver.tsx",+ "source:src/workbench/image-actions/GalleryBoardDestinationGroups.tsx","source:src/workbench/image-actions/ImageContextMenu.tsx","source:src/workbench/image-actions/RecallActionButtons.tsx","source:src/workbench/image-actions/appendReferenceImage.ts",@@ -2688,6 +2689,7 @@"source:src/workbench/hotkeys/shortcutHints.ts","source:src/workbench/hotkeys/targetWidget.ts","source:src/workbench/iconResolver.tsx",+ "source:src/workbench/image-actions/GalleryBoardDestinationGroups.tsx","source:src/workbench/image-actions/ImageContextMenu.tsx","source:src/workbench/image-actions/RecallActionButtons.tsx","source:src/workbench/image-actions/appendReferenceImage.ts",@@ -2988,6 +2990,7 @@"source:src/workbench/widgets/layers/LayerRegionSettings.tsx","source:src/workbench/widgets/layers/LayerRow.tsx","source:src/workbench/widgets/layers/LayerRowSurface.tsx",+ "source:src/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsx","source:src/workbench/widgets/layers/LayerStackHeader.tsx","source:src/workbench/widgets/layers/LayerStackMenu.tsx","source:src/workbench/widgets/layers/LayerSurfaceHost.tsx",@@ -4009,6 +4012,7 @@"source:src/workbench/hotkeys/shortcutHints.ts","source:src/workbench/hotkeys/targetWidget.ts","source:src/workbench/iconResolver.tsx",+ "source:src/workbench/image-actions/GalleryBoardDestinationGroups.tsx","source:src/workbench/image-actions/ImageContextMenu.tsx","source:src/workbench/image-actions/RecallActionButtons.tsx","source:src/workbench/image-actions/appendReferenceImage.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex e94c6a760d..cad7f8339e 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3761,7 +3761,8 @@"rename": "Rename layer","reorder": "Reorder layer","runWorkflow": "Run workflow",- "saveLayerToAssets": "Save layer to uploads",+ "saveLayerToBoard": "Save layer to board",+ "savedToBoard": "Layer saved to {{board}}.","select": "Select {{name}}","selectObject": "Select object","toggleAutoNegative": "Toggle auto-negative",diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/GalleryBoardDestinationGroups.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/GalleryBoardDestinationGroups.tsxnew file mode 100644index 0000000000..0fc66c29ec--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/GalleryBoardDestinationGroups.tsx@@ -0,0 +1,64 @@+import type { GalleryBoard } from '@features/gallery';++import { Menu } from '@chakra-ui/react';+import { getGalleryBoardDestinationGroups, getGalleryBoardLabel } from '@features/gallery/contracts';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { useProjectLibrarySelector } from '@workbench/projects/library';+import { useActiveProjectId, useActiveProjectName } from '@workbench/WorkbenchContext';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * The stored boards a "to board" submenu offers, grouped in the panel's tiers (the open project, the Library,+ * shared, other users', other projects). Only stored boards (`kind: 'board'`, not date or Uncategorized entries) that+ * accept the caller's media (`add_media`) are listed.+ */+export const GalleryBoardDestinationGroups = ({+ boards,+ onSelect,+}: {+ boards: readonly GalleryBoard[];+ onSelect: (board: GalleryBoard) => void;+}) => {+ const { t } = useTranslation();+ const projectId = useActiveProjectId();+ const projectName = useActiveProjectName();+ const librarySummaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);+ const groups = useMemo(+ () =>+ getGalleryBoardDestinationGroups({+ boards: boards.filter((board) => board.kind === 'board'),+ projectId,+ projectName,+ projectNames: new Map(librarySummaries.map((summary) => [summary.id, summary.name])),+ t,+ }),+ [boards, librarySummaries, projectId, projectName, t]+ );++ return groups.map((group) => (+ <Menu.ItemGroup key={group.id}>+ <Menu.ItemGroupLabel>{group.label}</Menu.ItemGroupLabel>+ {group.boards.map((board) => (+ <GalleryBoardDestinationItem key={board.id} board={board} onSelect={onSelect} />+ ))}+ </Menu.ItemGroup>+ ));+};++const GalleryBoardDestinationItem = ({+ board,+ onSelect,+}: {+ board: GalleryBoard;+ onSelect: (board: GalleryBoard) => void;+}) => {+ const { t } = useTranslation();+ const handleClick = useCallback(() => onSelect(board), [board, onSelect]);++ return (+ <Menu.Item value={`board-${board.id}`} onClick={handleClick}>+ <MiddleTruncate fontSize="md" minW="0" text={getGalleryBoardLabel(board, t)} />+ </Menu.Item>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex a4c259d7c4..802e2f2ece 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -742,7 +742,7 @@ describe('ImageContextMenu change-board destinations', () => {expect(trigger).not.toBeUndefined();await hoverItem(trigger!);await settleUntil(- () => document.querySelector('[data-value="move-to-theirs"]') !== null,+ () => document.querySelector('[data-value="board-theirs"]') !== null,'the change-board submenu to list its boards');@@ -769,6 +769,6 @@ describe('ImageContextMenu change-board destinations', () => {}),])).toEqual(['widgets.gallery.boardGroups.library', 'widgets.gallery.boardGroups.otherUsers']);- expect(document.querySelector('[data-value="move-to-mine"]')).not.toBeNull();+ expect(document.querySelector('[data-value="board-mine"]')).not.toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex dc815a7f4f..de5f4931b4 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -10,16 +10,13 @@ import {legacyGeneratedImageToGalleryItem,toGalleryItemKey,} from '@features/gallery';-import { getGalleryBoardDestinationGroups, getGalleryBoardLabel } from '@features/gallery/contracts';import { galleryKeys } from '@features/gallery/queries';import { captureAccountScope } from '@platform/state/accountLifecycle';import { MenuContent, MenuIconItem } from '@platform/ui';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useQuery } from '@tanstack/react-query';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';-import { useProjectLibrarySelector } from '@workbench/projects/library';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useActiveProjectId, useActiveProjectName, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ClapperboardIcon,AsteriskIcon,@@ -55,6 +52,7 @@ import { useTranslation } from 'react-i18next';import type { ImageActions } from './useImageActions';+import { GalleryBoardDestinationGroups } from './GalleryBoardDestinationGroups';import { EMPTY_IMAGE_RECALL_CAPABILITIES, type ImageRecallCapabilities } from './imageRecall';import { EMPTY_VIDEO_RECALL_CAPABILITIES, type VideoRecallCapabilities, type VideoRecallKind } from './videoRecall';@@ -1077,21 +1075,9 @@ const ChangeBoardSubMenu = ({onMove: (boardId: string) => void;}) => {const { t } = useTranslation();- const projectId = useActiveProjectId();- const projectName = useActiveProjectName();- const librarySummaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);const handleRemoveFromBoard = useCallback(() => onMove('none'), [onMove]);- const groups = useMemo(- () =>- getGalleryBoardDestinationGroups({- boards: boards.filter((board) => board.kind === 'board' && board.id !== currentBoardId),- projectId,- projectName,- projectNames: new Map(librarySummaries.map((summary) => [summary.id, summary.name])),- t,- }),- [boards, currentBoardId, librarySummaries, projectId, projectName, t]- );+ const handleSelectBoard = useCallback((board: GalleryBoard) => onMove(board.id), [onMove]);+ const destinations = useMemo(() => boards.filter((board) => board.id !== currentBoardId), [boards, currentBoardId]);return (<ContextSubMenu icon={FolderIcon} label={t('widgets.gallery.changeBoard')} scrollArea>@@ -1103,29 +1089,11 @@ const ChangeBoardSubMenu = ({onClick={handleRemoveFromBoard}/>)}- {groups.map((group) => (- <Menu.ItemGroup key={group.id}>- <Menu.ItemGroupLabel>{group.label}</Menu.ItemGroupLabel>- {group.boards.map((board) => (- <ChangeBoardMenuItem key={board.id} board={board} onMove={onMove} />- ))}- </Menu.ItemGroup>- ))}+ <GalleryBoardDestinationGroups boards={destinations} onSelect={handleSelectBoard} /></ContextSubMenu>);};-const ChangeBoardMenuItem = ({ board, onMove }: { board: GalleryBoard; onMove: (boardId: string) => void }) => {- const { t } = useTranslation();- const handleClick = useCallback(() => onMove(board.id), [board.id, onMove]);-- return (- <Menu.Item value={`move-to-${board.id}`} onClick={handleClick}>- <MiddleTruncate fontSize="md" minW="0" text={getGalleryBoardLabel(board, t)} />- </Menu.Item>- );-};-const ContextSubMenu = ({children,icon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex e08bd8e905..d476d3d007 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -78,6 +78,7 @@ import {type LayerConfigPatchKind,type LayerContextAction,type LayerContextActionEffects,+ type LayerContextBoardChoice,type LayerContextActionId,type LayerContextActionState,type LayerType,@@ -88,7 +89,7 @@ import {getLayerContextMenuLayout,getLayerContextMenuRenderEntries,} from './layerContextMenuLayout';-import { copyLayerToClipboard, saveLayerToAssets } from './layerExportActions';+import { copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';import { canGroupSelection, groupLayers } from './layerGroupCommands';import { resolveMenuTargetForRender } from './layerMenuState';import {@@ -114,6 +115,7 @@ import {MASK_MODIFIER_DEFAULTS,} from './layerOps';import { requestLayerProperties } from './layerPropertiesRequestStore';+import { LayerSaveToBoardSubmenu } from './LayerSaveToBoardSubmenu';import { RunLayerWorkflowDialog, useLayerWorkflowAvailability } from './RunLayerWorkflowDialog';import { useSelectedModelBase } from './useSelectedModelBase';@@ -604,19 +606,24 @@ const LayerMenu = ({patchBase(getActionLabel('fit-to-bbox'), { transform });}, [bbox, documentRect, getActionLabel, layer, makeStatusError, patchBase]);- const handleSaveToAssets = useCallback(async () => {- if (!engine) {- throw makeStatusError('not-ready');- }+ const handleSaveToBoard = useCallback(+ async (board: LayerContextBoardChoice) => {+ if (!engine) {+ throw makeStatusError('not-ready');+ }- const result = await saveLayerToAssets(layer.id, {- exportLayer: engine.exports.exportBakedLayerBlob,- upload: galleryTransfers.upload,- });- if (result !== 'saved' && result !== 'stale') {- throw makeStatusError(result);- }- }, [engine, layer.id, makeStatusError]);+ const result = await saveLayerToBoard(layer.id, board.id, {+ exportLayer: engine.exports.exportBakedLayerBlob,+ upload: galleryTransfers.upload,+ });+ if (result === 'saved') {+ notify.success(t('widgets.layers.actions.savedToBoard', { board: board.label }));+ } else if (result !== 'stale') {+ throw makeStatusError(result);+ }+ },+ [engine, layer.id, makeStatusError, notify, t]+ );const handleCopyToClipboard = useCallback(async () => {if (!engine) {@@ -885,7 +892,7 @@ const LayerMenu = ({patchConfig: handleLayerConfigAction,rasterize: handleRasterize,reorder: (kind, actionId) => reorder(kind, getActionLabel(actionId)),- saveToAssets: handleSaveToAssets,+ saveToBoard: handleSaveToBoard,setColorLabel: handleSetColorLabel,toggleLock: handleToggleLock,toggleQuickSwitchBookmark: handleToggleQuickSwitchBookmark,@@ -914,7 +921,7 @@ const LayerMenu = ({handleMerge,handleOpenProperties,handleRasterize,- handleSaveToAssets,+ handleSaveToBoard,handleSetColorLabel,handleToggleLock,handleToggleQuickSwitchBookmark,@@ -929,10 +936,13 @@ const LayerMenu = ({]);- const runAction = useCallback(- (action: LayerContextAction) => {+ const runAction = useCallback<RunLayerAction>(+ (action, board) => {+ if (action.isDisabled) {+ return;+ }void Promise.resolve()- .then(() => action.handler({ ...actionState, effects }))+ .then(() => action.handler({ ...actionState, board, effects })).catch((error: unknown) => {notify.error(t('widgets.layers.actions.actionFailed'), toErrorMessage(error));});@@ -1150,6 +1160,9 @@ const SUBMENU_META: Record<LayerContextSubmenuId, { defaultLabel: string; icon:'copy-to': { defaultLabel: 'Copy to', icon: CopyIcon, labelKey: 'widgets.layers.menu.copyTo' },};+/** Runs a layer action, reporting its failure; a `picker: 'board'` action runs with the board picked for it. */+type RunLayerAction = (action: LayerContextAction, board?: LayerContextBoardChoice) => void;+const SUBMENU_POSITIONING = { placement: 'right-start' } as const;const QUICK_MENU_TOOLTIP_CONTENT_PROPS = { fontSize: 'xs' } as const;const QUICK_MENU_TOOLTIP_POSITIONING_PROPS = { placement: 'top' } as const;@@ -1162,7 +1175,7 @@ const renderLayerMenuEntries = ({}: {beforeDangerItems?: ReactNode;entries: readonly LayerContextMenuRenderEntry[];- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;t: (key: string, options?: { defaultValue: string }) => string;}) =>entries.map((entry) =>@@ -1181,7 +1194,7 @@ const LayerMenuSection = ({section,t,}: {- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;section: LayerContextMenuSection;t: (key: string, options: { defaultValue: string }) => string;}) => {@@ -1215,10 +1228,13 @@ const LayerMenuLayoutItem = ({}: {compact: boolean;item: LayerContextMenuItem;- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;t: (key: string, options: { defaultValue: string }) => string;}) => {if (item.kind === 'action') {+ if (item.action.picker === 'board') {+ return <LayerSaveToBoardSubmenu action={item.action} onSelect={runAction} />;+ }return compact ? (<LayerMenuIconActionItem action={item.action} runAction={runAction} t={t} />) : (@@ -1237,7 +1253,7 @@ const LayerMenuSubmenu = ({}: {compact: boolean;item: Extract<LayerContextMenuItem, { kind: 'submenu' }>;- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;t: (key: string, options: { defaultValue: string }) => string;}) => {const meta = SUBMENU_META[item.id];@@ -1289,7 +1305,7 @@ const LayerMenuIconActionItem = ({t,}: {action: LayerContextAction;- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;t: (key: string, options: { count?: number; defaultValue: string }) => string;}) => {const onSelect = useCallback(() => runAction(action), [action, runAction]);@@ -1312,7 +1328,7 @@ const LayerMenuActionItem = ({t,}: {action: LayerContextAction;- runAction: (action: LayerContextAction) => void;+ runAction: RunLayerAction;t: (key: string, options: { count?: number; defaultValue: string }) => string;}) => {const onSelect = useCallback(() => runAction(action), [action, runAction]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsxnew file mode 100644index 0000000000..472626a97d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsx@@ -0,0 +1,202 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { GalleryBoard } from '@features/gallery';++import { ChakraProvider, Menu, Portal } from '@chakra-ui/react';+import { getGallerySettings } from '@features/gallery/contracts';+import { galleryBoardsOptions, getGalleryListingBoardsQuery } from '@features/gallery/queries';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { SaveIcon } from 'lucide-react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import type { LayerContextAction } from './layerContextActions';++import { LayerSaveToBoardSubmenu } from './LayerSaveToBoardSubmenu';++vi.mock('@workbench/projects/library', () => ({+ useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),+}));+vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectId: () => 'project-1',+ useActiveProjectName: () => 'Project',+ // No stored gallery values: the panel's default listing.+ useActiveProjectSelector: () => ({}),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const board = (id: string, actions: NonNullable<GalleryBoard['access']>['actions']): GalleryBoard => ({+ access: { actions, adminOverride: false, generalAccess: 'restricted', role: 'owner' },+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id,+ imageCount: 1,+ isInbox: false,+ kind: 'board',+ name: `Board ${id}`,+ ownerName: 'Me',+ projectId: null,+ videoCount: 0,+});++const saveAction = (isDisabled: boolean): LayerContextAction => ({+ defaultLabel: 'Save layer to board',+ handler: vi.fn(),+ icon: SaveIcon,+ id: 'save-to-board',+ isDisabled,+ labelKey: 'widgets.layers.actions.saveLayerToBoard',+ order: 10,+ picker: 'board',+ section: 'output',+});++let root: Root | null = null;+let host: HTMLDivElement | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ act(() => root?.unmount());+ host?.remove();+ root = null;+ host = null;+});++const interact = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 50);+ });+ });++const settleUntil = async (isSettled: () => boolean, description: string, timeoutMs = 2000): Promise<void> => {+ const deadline = Date.now() + timeoutMs;+ while (!isSettled()) {+ if (Date.now() > deadline) {+ throw new Error(`Timed out after ${String(timeoutMs)}ms waiting for ${description}`);+ }+ await act(async () => {+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 10);+ });+ });+ }+};++/** zag treats a pointer move as a hover only when the position changes, so approach from a pixel away. */+const hover = async (target: HTMLElement): Promise<void> => {+ const rect = target.getBoundingClientRect();+ const clientY = rect.top + rect.height / 2;+ await interact(() => {+ for (const clientX of [rect.left + rect.width / 2 - 1, rect.left + rect.width / 2]) {+ target.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, clientX, clientY, pointerType: 'mouse' }));+ }+ });+};++const render = async (action: LayerContextAction, onSelect = vi.fn()) => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const listing = galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings({})));+ queryClient.setQueryData(listing.queryKey, [board('mine', ['read', 'add_media']), board('read-only', ['read'])]);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await interact(() => {+ root?.render(+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <Menu.Root open positioning={{ getAnchorRect: () => ({ height: 1, width: 1, x: 20, y: 20 }) }}>+ <Portal>+ <Menu.Positioner>+ <Menu.Content>+ <Menu.Item value="before">Before</Menu.Item>+ <LayerSaveToBoardSubmenu action={action} onSelect={onSelect} />+ <Menu.Item value="after">After</Menu.Item>+ </Menu.Content>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </ChakraProvider>+ </QueryClientProvider>+ );+ });++ const trigger = document.querySelector<HTMLButtonElement>('[aria-label="widgets.layers.actions.saveLayerToBoard"]');+ expect(trigger).not.toBeNull();+ return {+ listingQuery: () => queryClient.getQueryCache().find({ queryKey: listing.queryKey })!,+ onSelect,+ trigger: trigger!,+ };+};++/** Presses each key in the parent menu; returns the highlighted item's name (or value) after each press. */+const walkKeys = async (keys: readonly string[]): Promise<(string | undefined)[]> => {+ await interact(() => document.querySelector<HTMLElement>('[role="menu"]')!.focus());+ const highlighted: (string | undefined)[] = [];+ for (const key of keys) {+ await act(() => userEvent.keyboard(key));+ await interact(() => undefined);+ const item = document.querySelector<HTMLElement>('[data-highlighted]');+ highlighted.push(item?.getAttribute('aria-label') ?? item?.dataset.value);+ }+ return highlighted;+};++describe('LayerSaveToBoardSubmenu', () => {+ it('reads boards only once opened and saves to the board picked', async () => {+ const action = saveAction(false);+ const { listingQuery, onSelect, trigger } = await render(action);++ expect(listingQuery().getObserversCount()).toBe(0);++ await hover(trigger);+ await settleUntil(() => document.querySelector('[data-value="board-mine"]') !== null, 'the board list');++ expect(listingQuery().getObserversCount()).toBe(1);+ expect(document.querySelector('[data-value="board-none"]')?.textContent).toBe('widgets.gallery.uncategorized');+ // A board the caller can only read is no destination.+ expect(document.querySelector('[data-value="board-read-only"]')).toBeNull();++ await interact(() => document.querySelector<HTMLElement>('[data-value="board-mine"]')!.click());++ expect(onSelect).toHaveBeenCalledExactlyOnceWith(action, { id: 'mine', label: 'Board mine' });+ });++ it('offers no boards while the action is disabled', async () => {+ const { listingQuery, trigger } = await render(saveAction(true));++ expect(trigger.disabled).toBe(true);+ await hover(trigger);++ expect(document.querySelector('[data-value="board-none"]')).toBeNull();+ expect(listingQuery().getObserversCount()).toBe(0);+ });++ it('opens from the keyboard when enabled', async () => {+ await render(saveAction(false));++ expect(await walkKeys(['{ArrowDown}', '{ArrowDown}'])).toEqual([+ 'before',+ 'widgets.layers.actions.saveLayerToBoard',+ ]);+ await act(() => userEvent.keyboard('{ArrowRight}'));+ await settleUntil(() => document.querySelector('[data-value="board-none"]') !== null, 'the board list');+ });++ it('skips the disabled row from the keyboard, so ArrowRight cannot open it', async () => {+ const { listingQuery } = await render(saveAction(true));++ expect(await walkKeys(['{ArrowDown}', '{ArrowDown}'])).toEqual(['before', 'after']);+ await act(() => userEvent.keyboard('{ArrowRight}'));+ await interact(() => undefined);++ expect(document.querySelector('[data-value="board-none"]')).toBeNull();+ expect(listingQuery().getObserversCount()).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsxnew file mode 100644index 0000000000..d9deef2c27--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsx@@ -0,0 +1,115 @@+import type { GalleryBoard } from '@features/gallery';++import { HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';+import { getGalleryBoardLabel, getGallerySettings } from '@features/gallery/contracts';+import { galleryBoardsOptions, getGalleryListingBoardsQuery } from '@features/gallery/queries';+import { useHostGalleryBoards } from '@features/gallery/react';+import { MenuContent } from '@platform/ui/Menu';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { useQuery } from '@tanstack/react-query';+import { GalleryBoardDestinationGroups } from '@workbench/image-actions/GalleryBoardDestinationGroups';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { ChevronRightIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import type { LayerContextAction, LayerContextBoardChoice } from './layerContextActions';++const SUBMENU_POSITIONING = { placement: 'right-start' } as const;++/**+ * A `picker: 'board'` layer action as a submenu of the boards the caller can add to, Uncategorized first. The list+ * mounts only while the submenu is open, so a layer menu never reads boards it does not show.+ */+export const LayerSaveToBoardSubmenu = ({+ action,+ onSelect,+}: {+ action: LayerContextAction;+ onSelect: (action: LayerContextAction, board: LayerContextBoardChoice) => void;+}) => {+ const { t } = useTranslation();+ const label = t(action.labelKey, { count: action.labelCount, defaultValue: action.defaultLabel });+ const handleSelect = useCallback((board: LayerContextBoardChoice) => onSelect(action, board), [action, onSelect]);++ return (+ <Menu.Root lazyMount positioning={SUBMENU_POSITIONING} unmountOnExit>+ <Menu.TriggerItem asChild>+ {/* zag's trigger item has no disabled prop: `data-disabled` keeps arrow keys from highlighting it, which would+ let ArrowRight open the submenu; the native attribute stops pointer hover and click. */}+ <button+ aria-disabled={action.isDisabled || undefined}+ aria-label={label}+ data-disabled={action.isDisabled ? '' : undefined}+ disabled={action.isDisabled}+ type="button"+ >+ <HStack gap="2" minW="0" w="full">+ <Icon as={action.icon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="md">+ {label}+ </Text>+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ </HStack>+ </button>+ </Menu.TriggerItem>+ <Portal>+ <Menu.Positioner>+ <MenuContent maxH="18rem" minW="13rem" py="1">+ <ScrollArea.Root maxH="inherit" variant="hover" w="full">+ <ScrollArea.Viewport maxH="inherit" w="full">+ <ScrollArea.Content>+ <BoardChoices onSelect={handleSelect} />+ </ScrollArea.Content>+ </ScrollArea.Viewport>+ <ScrollArea.Scrollbar>+ <ScrollArea.Thumb />+ </ScrollArea.Scrollbar>+ </ScrollArea.Root>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const BoardChoices = ({ onSelect }: { onSelect: (board: LayerContextBoardChoice) => void }) => {+ const { t } = useTranslation();+ // The Gallery panel's own listing (same key, shared cache), so the boards read as the panel shows them.+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));+ const { data, isError, isPending, refetch } = useQuery(+ galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings(galleryValues)))+ );+ const boards = useHostGalleryBoards(data);+ const uncategorizedLabel = t('widgets.gallery.uncategorized');+ const handleSelectUncategorized = useCallback(+ () => onSelect({ id: 'none', label: uncategorizedLabel }),+ [onSelect, uncategorizedLabel]+ );+ const handleSelectBoard = useCallback(+ (board: GalleryBoard) => onSelect({ id: board.id, label: getGalleryBoardLabel(board, t) }),+ [onSelect, t]+ );+ const handleRetry = useCallback(() => void refetch(), [refetch]);++ return (+ <>+ <Menu.Item value="board-none" onClick={handleSelectUncategorized}>+ <MiddleTruncate fontSize="md" minW="0" text={uncategorizedLabel} />+ </Menu.Item>+ {isPending ? (+ <Menu.Item disabled value="boards-loading">+ <Text color="fg.muted" fontSize="md">+ {t('common.loading')}+ </Text>+ </Menu.Item>+ ) : isError ? (+ <Menu.Item closeOnSelect={false} value="boards-retry" onClick={handleRetry}>+ <Text fontSize="md">{t('widgets.gallery.retryLoadingBoards')}</Text>+ </Menu.Item>+ ) : null}+ <GalleryBoardDestinationGroups boards={boards} onSelect={handleSelectBoard} />+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsxindex e6cd9ddd1a..6d8fb295e3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx@@ -1,9 +1,13 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type * as GalleryModule from '@features/gallery';+import type { GalleryBoard } from '@features/gallery';import type { CanvasNodeContract } from '@workbench/canvas-engine/api';import type { Project } from '@workbench/projectContracts';import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';import { ChakraProvider } from '@chakra-ui/react';+import { getGallerySettings } from '@features/gallery/contracts';+import { galleryBoardsOptions, getGalleryListingBoardsQuery } from '@features/gallery/queries';import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';@@ -15,6 +19,7 @@ import {} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { getProjectWidgetValues } from '@workbench/widgetState';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { createInstance } from 'i18next';import { act, createRef, useImperativeHandle, useState, type Ref } from 'react';@@ -32,15 +37,22 @@ import { buildLayerStackRows } from './layerTreeRows';const PROJECT_ID = 'surface-project';const mocks = vi.hoisted(() => ({- commands: { notifications: { add: () => undefined }, widgets: { open: () => undefined } },+ commands: { notifications: { add: vi.fn() }, widgets: { open: () => undefined } },// Only a layer menu reads workflow availability, once per render, so its calls show a layer menu is mounted.layerMenuRender: vi.fn(),project: null as unknown as Project,+ upload: vi.fn(() => Promise.resolve()),}));+vi.mock('@features/gallery', async (importOriginal) => {+ const gallery = await importOriginal<typeof GalleryModule>();+ return { ...gallery, galleryTransfers: { ...gallery.galleryTransfers, upload: mocks.upload } };+});+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof WorkbenchContextModule>()),useActiveProjectId: () => PROJECT_ID,+ useActiveProjectName: () => 'Surface project',useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(mocks.project),useOptionalWorkbenchCommands: () => mocks.commands,useWorkbenchCommands: () => mocks.commands,@@ -79,7 +91,10 @@ const engine = {document: {model: () => createDocumentModel(mocks.project.canvas.document, { editRevision: 0, projectId: PROJECT_ID }),},- exports: { hasExportableLayerContent: () => true },+ exports: {+ exportBakedLayerBlob: () => Promise.resolve({ blob: new Blob(['pixels'], { type: 'image/png' }), status: 'ok' }),+ hasExportableLayerContent: () => true,+ },interaction: {get: (key: string) => (key === 'layerQuickSwitch' ? quickSwitch : false),set: (key: string, value: typeof quickSwitch) => {@@ -117,6 +132,7 @@ const Harness = ({ ref }: { ref: Ref<OpenSurface> }) => {let host: HTMLDivElement | null = null;let root: Root | null = null;+let queryClient = new QueryClient();(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;beforeEach(async () => {@@ -130,9 +146,10 @@ beforeEach(async () => {host = document.createElement('div');document.body.append(host);root = createRoot(host);+ queryClient = new QueryClient();await act(() =>root!.render(- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={queryClient}><I18nextProvider i18n={i18n}><ChakraProvider value={system}><Harness ref={openSurfaceRef} />@@ -293,3 +310,41 @@ it('toggles the real bookmark menu handler without changing previous-layer memorawait act(() => page.getByRole('menuitem', { name: /^Remove quick switch bookmark/ }).click());expect(quickSwitch).toEqual({ bookmarkedLayerId: null, previousLayerId: 'child' });});++it('saves the layer to the board picked in its submenu and names that board', async () => {+ const board: GalleryBoard = {+ access: { actions: ['read', 'add_media'], adminOverride: false, generalAccess: 'restricted', role: 'owner' },+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id: 'sketches',+ imageCount: 0,+ isInbox: false,+ kind: 'board',+ name: 'Sketches',+ ownerName: 'Me',+ projectId: null,+ videoCount: 0,+ };+ const listing = galleryBoardsOptions(+ getGalleryListingBoardsQuery(getGallerySettings(getProjectWidgetValues(mocks.project, 'gallery')))+ );+ queryClient.setQueryData(listing.queryKey, [board]);+ mocks.upload.mockClear();+ mocks.commands.notifications.add.mockClear();++ await act(() => openSurface({ anchor, id: 'layer', kind: 'menu' }));+ await act(() => page.getByRole('menuitem', { name: 'Save layer to board', exact: true }).hover());+ await act(() => page.getByRole('menuitem', { name: 'Sketches', exact: true }).click());++ await expect+ .poll(() => mocks.commands.notifications.add)+ .toHaveBeenCalledWith({+ kind: 'success',+ message: undefined,+ title: 'Layer saved to Sketches.',+ });+ expect(mocks.upload).toHaveBeenCalledExactlyOnceWith(expect.any(File), 'sketches', {+ signal: expect.any(AbortSignal),+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex cf7b31915a..0f11db2d47 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -118,7 +118,7 @@ const makeEffects = (): LayerContextActionEffects => ({rasterize: vi.fn(),reorder: vi.fn(),setColorLabel: vi.fn(),- saveToAssets: vi.fn(() => Promise.resolve()),+ saveToBoard: vi.fn(() => Promise.resolve()),toggleLock: vi.fn(),toggleQuickSwitchBookmark: vi.fn(),toggleVisibility: vi.fn(),@@ -280,6 +280,17 @@ describe('layer context action registry', () => {expect(transform).toHaveBeenCalledOnce();});+ it('saves the layer to the board chosen in its picker', async () => {+ const effects = makeEffects();+ const board = { id: 'board-7', label: 'Sketches' };+ const definition = getLayerContextActionDefinition('save-to-board');++ await definition.handler(makeRuntimeContext(rasterLayer, { board, effects }));++ expect(effects.saveToBoard).toHaveBeenCalledWith(board);+ expect(() => definition.handler(makeRuntimeContext(rasterLayer, { effects }))).toThrow();+ });+it('starts Select Object for the action layer through the registry', () => {const effects = makeEffects();const context = makeRuntimeContext(rasterLayer, { effects });@@ -470,7 +481,7 @@ describe('getLayerContextActions', () => {'add-hue','add-invert','add-regenerate-region',- 'save-to-assets',+ 'save-to-board','copy-to-clipboard','crop-to-bbox','extract-masked-area',@@ -596,7 +607,7 @@ describe('getLayerContextActions', () => {it('still allows non-destructive copy and export from a locked layer when interaction is free', () => {const actions = getLayerContextActions(makeState({ ...rasterLayer, isLocked: true }));expect(byId(actions, 'copy-to-clipboard').isDisabled).toBe(false);- expect(byId(actions, 'save-to-assets').isDisabled).toBe(false);+ expect(byId(actions, 'save-to-board').isDisabled).toBe(false);});it('disables locked-layer mutations but keeps toggle lock enabled', () => {@@ -666,10 +677,10 @@ describe('getLayerContextActions', () => {const noEngine = getLayerContextActions(makeState(rasterLayer, { hasEngine: false }));const empty = getLayerContextActions(makeState(rasterLayer, { hasSupportedContent: false }));- for (const id of ['transform', 'filter', 'save-to-assets', 'copy-to-clipboard', 'crop-to-bbox'] as const) {+ for (const id of ['transform', 'filter', 'save-to-board', 'copy-to-clipboard', 'crop-to-bbox'] as const) {expect(byId(noEngine, id).isDisabled, id).toBe(true);}- for (const id of ['save-to-assets', 'copy-to-clipboard', 'crop-to-bbox'] as const) {+ for (const id of ['save-to-board', 'copy-to-clipboard', 'crop-to-bbox'] as const) {expect(byId(empty, id).isDisabled, id).toBe(true);}});@@ -678,7 +689,7 @@ describe('getLayerContextActions', () => {const cacheOnly = createEmptyPaintLayer('Cache only', 'cache-only');const actions = getLayerContextActions(makeState(cacheOnly, { hasSupportedContent: true }));- expect(byId(actions, 'save-to-assets').isDisabled).toBe(false);+ expect(byId(actions, 'save-to-board').isDisabled).toBe(false);expect(byId(actions, 'fit-to-bbox').isDisabled).toBe(true);});@@ -697,7 +708,7 @@ describe('getLayerContextActions', () => {'add-hue','add-invert','add-regenerate-region',- 'save-to-assets',+ 'save-to-board','copy-to-clipboard','crop-to-bbox','merge-down',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex eb1aa1fbfe..0efddb1c63 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -79,7 +79,7 @@ export type LayerContextActionId =| 'rename'| 'transform'| 'fit-to-bbox'- | 'save-to-assets'+ | 'save-to-board'| 'copy-to-clipboard'| 'crop-to-bbox'| 'extract-masked-area'@@ -150,7 +150,7 @@ export interface LayerContextActionEffects {transform(): void;fitToBbox(): void;openProperties(): void;- saveToAssets(): Promise<void>;+ saveToBoard(board: LayerContextBoardChoice): Promise<void>;copyToClipboard(): Promise<void>;cropToBbox(): Promise<void>;extractMaskedArea(): Promise<void>;@@ -172,11 +172,19 @@ export interface LayerContextActionEffects {delete(): void;}+/** A gallery board picked in a `picker: 'board'` action's submenu; `id` is `'none'` for Uncategorized. */+export interface LayerContextBoardChoice {+ id: string;+ label: string;+}+export interface LayerContextActionRuntimeContext extends LayerContextActionState {effects: LayerContextActionEffects;+ /** The board a `picker: 'board'` action runs with; absent for every other action. */+ board?: LayerContextBoardChoice;}-export interface LayerContextActionDefinition {+interface LayerContextActionDefinitionBase {id: LayerContextActionId;labelKey: string;defaultLabel: string;@@ -185,7 +193,6 @@ export interface LayerContextActionDefinition {/** CSS color for the item's icon (label swatches); the theme tone otherwise. */iconColor?: string;section: LayerContextMenuSectionId;- submenu?: LayerContextSubmenuId;order: number;supportedLayerTypes: readonly LayerType[];tone?: 'danger';@@ -200,6 +207,17 @@ export interface LayerContextActionDefinition {getLabelCount?(context: LayerContextActionState): number;}+/**+ * A picker action is its own submenu, so it cannot also sit in a static one: there it would render as a plain item+ * that runs without a board.+ */+export type LayerContextActionDefinition = LayerContextActionDefinitionBase &+ (+ | { picker?: never; submenu?: LayerContextSubmenuId }+ /** Renders the action as a submenu of the account's gallery boards; the chosen board runs it. */+ | { picker: 'board'; submenu?: never }+ );+export interface LayerContextAction {id: LayerContextActionId;labelKey: string;@@ -209,6 +227,7 @@ export interface LayerContextAction {iconColor?: string;section: LayerContextMenuSectionId;submenu?: LayerContextSubmenuId;+ picker?: 'board';order: number;tone?: 'danger';hint?: string;@@ -828,14 +847,20 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinisupportedLayerTypes: ALL_LAYER_TYPES,},{- defaultLabel: 'Save layer to uploads',- handler: ({ effects }) => effects.saveToAssets(),+ defaultLabel: 'Save layer to board',+ handler: ({ board, effects }) => {+ if (!board) {+ throw new Error('Save layer to board runs with a chosen board');+ }+ return effects.saveToBoard(board);+ },icon: SaveIcon,- id: 'save-to-assets',+ id: 'save-to-board',isEnabled: hasReadablePixels,isVisible: alwaysVisible,- labelKey: 'widgets.layers.actions.saveLayerToAssets',+ labelKey: 'widgets.layers.actions.saveLayerToBoard',order: 10,+ picker: 'board',section: 'output',supportedLayerTypes: ALL_LAYER_TYPES,},@@ -1003,6 +1028,7 @@ export const getLayerContextActions = (context: LayerContextActionState): LayerClabelCount: definition.getLabelCount?.(context),labelKey: definition.getLabelKey?.(context) ?? definition.labelKey,order: definition.order,+ picker: definition.picker,section: definition.section,submenu: definition.submenu,tone: definition.tone,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 4c81e94fda..3092db9bb5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -106,7 +106,7 @@ describe('getLayerContextMenuLayout', () => {],presentation: 'list',},- { id: 'output', items: ['crop-to-bbox', 'save-to-assets'], presentation: 'list' },+ { id: 'output', items: ['crop-to-bbox', 'save-to-board'], presentation: 'list' },{id: 'state',items: [diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.tsindex 16e2f4b730..3674014ae2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts@@ -1,7 +1,7 @@import { accountLifecycle } from '@platform/state/accountLifecycle';import { describe, expect, it, vi } from 'vitest';-import { copyBlobToClipboard, copyLayerToClipboard, saveLayerToAssets } from './layerExportActions';+import { copyBlobToClipboard, copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';describe('copyBlobToClipboard', () => {it('writes a ClipboardItem using the blob MIME type', async () => {@@ -60,8 +60,8 @@ describe('copyLayerToClipboard', () => {});});-describe('saveLayerToAssets', () => {- it('threads the account signal through export and upload', async () => {+describe('saveLayerToBoard', () => {+ it('uploads the baked layer to the chosen board under the account signal', async () => {const owner = accountLifecycle.activate('layer-export-a', ':user:layer-export-a');const blob = new Blob(['pixels'], { type: 'image/png' });const exportLayer = vi.fn(() => Promise.resolve({ blob, status: 'ok' as const }));@@ -71,10 +71,10 @@ describe('saveLayerToAssets', () => {return Promise.resolve();});- await expect(saveLayerToAssets('layer-a', { exportLayer, upload })).resolves.toBe('saved');+ await expect(saveLayerToBoard('layer-a', 'board-7', { exportLayer, upload })).resolves.toBe('saved');expect(exportLayer).toHaveBeenCalledWith('layer-a', { includeDisabled: true, signal: owner.signal });- expect(upload).toHaveBeenCalledWith(expect.any(File), 'none', { signal: owner.signal });+ expect(upload).toHaveBeenCalledWith(expect.any(File), 'board-7', { signal: owner.signal });expect(uploadedFile).toMatchObject({ name: 'layer-layer-a.png', type: 'image/png' });});@@ -86,7 +86,7 @@ describe('saveLayerToAssets', () => {});const exportLayer = vi.fn(() => exportResult);const upload = vi.fn(() => Promise.resolve());- const pendingSave = saveLayerToAssets('layer-a', { exportLayer, upload });+ const pendingSave = saveLayerToBoard('layer-a', 'none', { exportLayer, upload });accountLifecycle.activate('layer-export-b', ':user:layer-export-b');resolveExport({ status: 'empty' });@@ -104,7 +104,7 @@ describe('saveLayerToAssets', () => {resolveUpload = resolve;});const upload = vi.fn(() => uploadResult);- const pendingSave = saveLayerToAssets('layer-a', { exportLayer, upload });+ const pendingSave = saveLayerToBoard('layer-a', 'none', { exportLayer, upload });await vi.waitFor(() => expect(upload).toHaveBeenCalledOnce());accountLifecycle.activate('layer-export-b', ':user:layer-export-b');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.tsindex de7316e78f..e0d9a9c65c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts@@ -44,7 +44,7 @@ export const copyLayerToClipboard = async (return 'ok';};-interface SaveLayerToAssetsDeps {+interface SaveLayerToBoardDeps {exportLayer(layerId: string,options: { includeDisabled: boolean; signal: AbortSignal }@@ -52,16 +52,17 @@ interface SaveLayerToAssetsDeps {upload(file: File, boardId: string, options: { signal: AbortSignal }): Promise<unknown>;}-export type SaveLayerToAssetsResult = 'saved' | 'stale' | LayerAssetExportFailureStatus;+export type SaveLayerToBoardResult = 'saved' | 'stale' | LayerAssetExportFailureStatus;/**- * Owns the complete local-export → gallery-upload boundary. A stale account- * reports `stale` instead of leaking an abort into the next account's UI.+ * Owns the complete local-export → gallery-upload boundary: the baked layer is uploaded to `boardId` (`'none'` for+ * Uncategorized). A stale account reports `stale` instead of leaking an abort into the next account's UI.*/-export const saveLayerToAssets = async (+export const saveLayerToBoard = async (layerId: string,- { exportLayer, upload }: SaveLayerToAssetsDeps-): Promise<SaveLayerToAssetsResult> => {+ boardId: string,+ { exportLayer, upload }: SaveLayerToBoardDeps+): Promise<SaveLayerToBoardResult> => {const owner = captureAccountScope();try {@@ -73,7 +74,7 @@ export const saveLayerToAssets = async (}const file = new File([result.blob], `layer-${layerId}.png`, { type: result.blob.type || 'image/png' });- await upload(file, 'none', { signal: owner.signal });+ await upload(file, boardId, { signal: owner.signal });assertAccountScopeCurrent(owner);return 'saved';diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 2b32173a43..dbc0653d4f 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -127,6 +127,8 @@ const EDITOR_BOOT_SHARED_MODULES = ['/workbench/hotkeys/targetWidget.ts','/workbench/widget-frame/compactWidgetCapacity.tsx','/features/gallery/ui/GalleryItemSearch.tsx',+ // The image menu (editor boot) and the lazy layer menu share the board destination list; alone it costs a request.+ '/workbench/image-actions/GalleryBoardDestinationGroups.tsx','/app/GalleryUiAdapter.tsx','/features/generation/core/prompt/ast.ts','/features/generation/core/prompt/attention.ts',@@ -279,6 +281,7 @@ const CANVAS_LAYER_SHARED_MODULES = ['/workbench/widgets/canvas/useColorSampler.ts','/workbench/widgets/canvas/useStructuralCommit.ts','/workbench/widgets/layers/LayerContextMenu.tsx',+ '/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsx','/workbench/widgets/layers/RunLayerWorkflowDialog.tsx','/workbench/widgets/layers/colorLabels.ts','/workbench/widgets/layers/layerActionSession.ts',