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
fix(canvas): check board access and refresh the gallery when saving a layer
Josh Corbettd279c79512cd
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex d476d3d007..c37df16db3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -19,6 +19,7 @@ import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { galleryTransfers } from '@features/gallery';import { useModelsSelector } from '@features/models';import { IconButton, MenuActionItem, MenuContent, MenuIconItem, RenameDialog, Tooltip } from '@platform/ui';+import { useQueryClient } from '@tanstack/react-query';import {canMergeSelectedRasters,getDocumentIndex,@@ -234,6 +235,7 @@ const LayerMenu = ({const projectId = useActiveProjectId();const { widgets } = useWorkbenchCommands();const notify = useNotify();+ const queryClient = useQueryClient();const base = useSelectedModelBase();const models = useModelsSelector((snapshot) => snapshot.models);const defaultControlModel = useMemo(() => resolveDefaultControlModelForBase(models, base), [base, models]);@@ -613,16 +615,25 @@ const LayerMenu = ({}const result = await saveLayerToBoard(layer.id, board.id, {+ client: queryClient,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);+ switch (result) {+ case 'saved':+ notify.success(t('widgets.layers.actions.savedToBoard', { board: board.label }));+ return;+ case 'stale':+ return;+ case 'board-view-only':+ throw new Error(t('widgets.gallery.uploadsUnavailableForViewOnlyBoard', { name: board.label }));+ case 'board-unavailable':+ throw new Error(t('widgets.gallery.uploadsUnavailableForBoard', { name: board.label }));+ default:+ throw makeStatusError(result);}},- [engine, layer.id, makeStatusError, notify, t]+ [engine, layer.id, makeStatusError, notify, queryClient, t]);const handleCopyToClipboard = useCallback(async () => {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 6d8fb295e3..f6356f8fdc 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@@ -311,25 +311,32 @@ it('toggles the real bookmark menu handler without changing previous-layer memorexpect(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 sketchesBoard: 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,+};++/** Lists boards as the Gallery panel did, then as the listing of every readable board did afterwards. */+const listBoards = (panelBoards: GalleryBoard[], destinationBoards: GalleryBoard[]) => {const listing = galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings(getProjectWidgetValues(mocks.project, 'gallery'))));- queryClient.setQueryData(listing.queryKey, [board]);+ queryClient.setQueryData(listing.queryKey, panelBoards, { updatedAt: Date.now() - 1_000 });+ queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, destinationBoards);+};++it('saves the layer to the board picked in its submenu and names that board', async () => {+ listBoards([sketchesBoard], [sketchesBoard]);mocks.upload.mockClear();mocks.commands.notifications.add.mockClear();@@ -348,3 +355,23 @@ it('saves the layer to the board picked in its submenu and names that board', assignal: expect.any(AbortSignal),});});++it('refuses a board the panel still offers once a newer listing holds it view-only, and says so', async () => {+ listBoards(+ [sketchesBoard],+ [{ ...sketchesBoard, access: { ...sketchesBoard.access!, actions: ['read'], role: 'viewer' } }]+ );+ 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(+ expect.objectContaining({ kind: 'error', message: 'You can view Sketches but not add to it' })+ );+ expect(mocks.upload).not.toHaveBeenCalled();+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.tsindex 3674014ae2..311db812e9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts@@ -1,5 +1,14 @@-import { accountLifecycle } from '@platform/state/accountLifecycle';-import { describe, expect, it, vi } from 'vitest';+import { getGallerySettings } from '@features/gallery/contracts';+import {+ canonicalizeGalleryItemsFilter,+ galleryBoardsOptions,+ galleryKeys,+ getGalleryListingBoardsQuery,+} from '@features/gallery/queries';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { QueryClient, QueryObserver } from '@tanstack/react-query';+import { afterEach, describe, expect, it, vi } from 'vitest';import { copyBlobToClipboard, copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';@@ -60,22 +69,195 @@ describe('copyLayerToClipboard', () => {});});+interface ServerBoard {+ id: string;+ actions: string[];+ archived?: boolean;+ imageCount?: number;+}++/** The board endpoints as the server answers them; every other request answers an empty total. */+const serveBoards = (initial: ServerBoard[]) => {+ let boards = initial;+ const listings: URLSearchParams[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn((input: RequestInfo | URL) => {+ const url = new URL(input instanceof Request ? input.url : String(input), 'http://invoke.test');+ if (url.pathname !== '/api/v1/boards/') {+ return Promise.resolve(new Response(JSON.stringify({ total: 0 })));+ }+ listings.push(url.searchParams);+ const includeArchived = url.searchParams.get('include_archived') === 'true';+ const body = boards+ .filter((board) => includeArchived || !board.archived)+ .map((board) => ({+ allowed_actions: board.actions,+ archived: board.archived ?? false,+ asset_count: 0,+ board_id: board.id,+ board_name: board.id,+ created_at: '2026-10-01T00:00:00Z',+ general_access: 'restricted',+ image_count: board.imageCount ?? 0,+ my_role: board.actions.includes('add_media') ? 'owner' : 'viewer',+ }));+ return Promise.resolve(new Response(JSON.stringify(body)));+ })+ );++ return {+ /** Reads of the listing of every readable board, archived included. */+ destinationReads: () => listings.filter((params) => params.get('include_archived') === 'true').length,+ listingReads: () => listings.length,+ setBoards: (next: ServerBoard[]) => {+ boards = next;+ },+ };+};++const createClient = () => new QueryClient({ defaultOptions: { queries: { gcTime: Infinity, retry: false } } });++const exportsPixels = () =>+ vi.fn(() => Promise.resolve({ blob: new Blob(['pixels'], { type: 'image/png' }), status: 'ok' as const }));++/** An item list the Gallery panel read for `boardId`, fresh for its 60-second stale time. */+const seedItemList = (client: QueryClient, boardId: string) => {+ const key = galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({ boardId, galleryView: 'images', searchTerm: '' })+ );+ client.setQueryData(key, { pageParams: [0], pages: [{ items: [], total: 0 }] });+ return () => client.getQueryState(key);+};++afterEach(() => {+ vi.unstubAllGlobals();+});+describe('saveLayerToBoard', () => {- it('uploads the baked layer to the chosen board under the account signal', async () => {+ it('uploads to a board the listing takes uploads for, then reads the gallery and its board counts again', 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 }));+ const server = serveBoards([+ { actions: ['read', 'add_media'], id: 'board-7' },+ { actions: ['read', 'add_media'], archived: true, id: 'old' },+ ]);+ const client = createClient();+ // A warm Gallery: the listing of every readable board, the panel's own listing (observed) and an item list.+ await client.fetchQuery(galleryBoardsOptions({ includeArchived: true }));+ const panel = new QueryObserver(client, galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings({}))));+ const unsubscribe = panel.subscribe(() => undefined);+ await vi.waitFor(() => expect(panel.getCurrentResult().data).toHaveLength(2));+ const itemList = seedItemList(client, 'board-7');+ const exportLayer = exportsPixels();let uploadedFile: File | null = null;const upload = vi.fn((file: File) => {uploadedFile = file;+ server.setBoards([+ { actions: ['read', 'add_media'], id: 'board-7', imageCount: 1 },+ { actions: ['read', 'add_media'], archived: true, id: 'old' },+ ]);return Promise.resolve();});- await expect(saveLayerToBoard('layer-a', 'board-7', { exportLayer, upload })).resolves.toBe('saved');+ await expect(saveLayerToBoard('layer-a', 'board-7', { client, exportLayer, upload })).resolves.toBe('saved');expect(exportLayer).toHaveBeenCalledWith('layer-a', { includeDisabled: true, 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' });+ await vi.waitFor(() =>+ expect(panel.getCurrentResult().data?.find((board) => board.id === 'board-7')?.imageCount).toBe(1)+ );+ expect(itemList()?.isInvalidated).toBe(true);+ unsubscribe();++ // An archived board chosen on purpose is a destination too.+ await expect(saveLayerToBoard('layer-a', 'old', { client, exportLayer, upload })).resolves.toBe('saved');+ expect(upload).toHaveBeenLastCalledWith(expect.any(File), 'old', { signal: owner.signal });+ });++ it('reads the listing of every readable board before deciding when none is cached yet', async () => {+ accountLifecycle.activate('layer-export-a', ':user:layer-export-a');+ const server = serveBoards([{ actions: ['read', 'add_media'], id: 'board-7' }]);+ const client = createClient();+ const readsWhenExported: number[] = [];+ const exportLayer = vi.fn(() => {+ readsWhenExported.push(server.destinationReads());+ return Promise.resolve({ blob: new Blob(['pixels'], { type: 'image/png' }), status: 'ok' as const });+ });+ const upload = vi.fn(() => Promise.resolve());++ await expect(saveLayerToBoard('layer-a', 'board-7', { client, exportLayer, upload })).resolves.toBe('saved');++ expect(readsWhenExported).toEqual([1]);+ expect(server.destinationReads()).toBe(1);+ expect(upload).toHaveBeenCalledWith(expect.any(File), 'board-7', { signal: expect.any(AbortSignal) });+ });++ it('reports a board revoked after it was listed, refreshes the gallery and stops offering the board', async () => {+ accountLifecycle.activate('layer-export-a', ':user:layer-export-a');+ const server = serveBoards([{ actions: ['read', 'add_media'], id: 'shared' }]);+ const client = createClient();+ await client.fetchQuery(galleryBoardsOptions({ includeArchived: true }));+ const itemList = seedItemList(client, 'shared');+ const exportLayer = exportsPixels();+ // Access dropped to view-only after the listing was read: the server refuses the upload.+ server.setBoards([{ actions: ['read'], id: 'shared' }]);+ const refusal = new ApiError('You cannot add to this board', 403);+ const upload = vi.fn(() => Promise.reject(refusal));++ await expect(saveLayerToBoard('layer-a', 'shared', { client, exportLayer, upload })).rejects.toBe(refusal);++ await vi.waitFor(() => expect(server.destinationReads()).toBe(2));+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));+ expect(itemList()?.isInvalidated).toBe(true);++ // The next save is judged from the listing read again: refused before anything is baked or sent.+ await expect(saveLayerToBoard('layer-a', 'shared', { client, exportLayer, upload })).resolves.toBe(+ 'board-view-only'+ );+ expect(exportLayer).toHaveBeenCalledTimes(1);+ expect(upload).toHaveBeenCalledTimes(1);+ });++ it('refuses a board the listing holds view-only or no longer holds, without baking, and reads the listing again', async () => {+ accountLifecycle.activate('layer-export-a', ':user:layer-export-a');+ const server = serveBoards([+ { actions: ['read', 'add_media'], id: 'own' },+ { actions: ['read'], id: 'viewed' },+ ]);+ const client = createClient();+ await client.fetchQuery(galleryBoardsOptions({ includeArchived: true }));+ const exportLayer = exportsPixels();+ const upload = vi.fn(() => Promise.resolve());++ await expect(saveLayerToBoard('layer-a', 'viewed', { client, exportLayer, upload })).resolves.toBe(+ 'board-view-only'+ );+ await vi.waitFor(() => expect(server.destinationReads()).toBe(2));+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));++ await expect(saveLayerToBoard('layer-a', 'deleted', { client, exportLayer, upload })).resolves.toBe(+ 'board-unavailable'+ );+ await vi.waitFor(() => expect(server.destinationReads()).toBe(3));++ expect(exportLayer).not.toHaveBeenCalled();+ expect(upload).not.toHaveBeenCalled();+ });++ it('saves to Uncategorized without consulting any board listing', async () => {+ accountLifecycle.activate('layer-export-a', ':user:layer-export-a');+ const server = serveBoards([]);+ const client = createClient();+ const upload = vi.fn(() => Promise.resolve());++ await expect(saveLayerToBoard('layer-a', 'none', { client, exportLayer: exportsPixels(), upload })).resolves.toBe(+ 'saved'+ );++ expect(upload).toHaveBeenCalledWith(expect.any(File), 'none', { signal: expect.any(AbortSignal) });+ expect(server.listingReads()).toBe(0);});it('does not upload an account A export that completes after account B activates', async () => {@@ -86,7 +268,7 @@ describe('saveLayerToBoard', () => {});const exportLayer = vi.fn(() => exportResult);const upload = vi.fn(() => Promise.resolve());- const pendingSave = saveLayerToBoard('layer-a', 'none', { exportLayer, upload });+ const pendingSave = saveLayerToBoard('layer-a', 'none', { client: createClient(), exportLayer, upload });accountLifecycle.activate('layer-export-b', ':user:layer-export-b');resolveExport({ status: 'empty' });@@ -104,7 +286,7 @@ describe('saveLayerToBoard', () => {resolveUpload = resolve;});const upload = vi.fn(() => uploadResult);- const pendingSave = saveLayerToBoard('layer-a', 'none', { exportLayer, upload });+ const pendingSave = saveLayerToBoard('layer-a', 'none', { client: createClient(), 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 e0d9a9c65c..76ed2da76a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts@@ -1,5 +1,15 @@+import type { QueryClient } from '@tanstack/react-query';import type { ExportBakedLayerBlobResult } from '@workbench/canvas-engine/api';+import { canOnBoard } from '@features/gallery/contracts';+import {+ canAddToCachedGalleryBoard,+ ensureGalleryBoardDestinations,+ getCachedGalleryBoard,+ invalidateGallery,+ invalidateGalleryBoardDestinations,+ invalidateGalleryItems,+} from '@features/gallery/queries';import {assertAccountScopeCurrent,captureAccountScope,@@ -45,6 +55,7 @@ export const copyLayerToClipboard = async (};interface SaveLayerToBoardDeps {+ client: QueryClient;exportLayer(layerId: string,options: { includeDisabled: boolean; signal: AbortSignal }@@ -52,18 +63,40 @@ interface SaveLayerToBoardDeps {upload(file: File, boardId: string, options: { signal: AbortSignal }): Promise<unknown>;}-export type SaveLayerToBoardResult = 'saved' | 'stale' | LayerAssetExportFailureStatus;+export type SaveLayerToBoardResult =+ | 'saved'+ | 'stale'+ | 'board-view-only'+ | 'board-unavailable'+ | LayerAssetExportFailureStatus;/*** 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.+ * Uncategorized). A real board is judged first from the ensured listing of every readable board, as Gallery uploads+ * are: one listed without `add_media` reports `board-view-only` and one no longer listed `board-unavailable`, before+ * anything is baked, and the listings are read again so the picker stops offering it. Once the upload settles the+ * gallery reads again; a failed one also re-reads the listings (the board may have refused it) and rethrows. A stale+ * account reports `stale` instead of leaking an abort into the next account's UI.*/export const saveLayerToBoard = async (layerId: string,boardId: string,- { exportLayer, upload }: SaveLayerToBoardDeps+ { client, exportLayer, upload }: SaveLayerToBoardDeps): Promise<SaveLayerToBoardResult> => {const owner = captureAccountScope();+ const isRealBoard = boardId !== 'none';++ if (isRealBoard) {+ await ensureGalleryBoardDestinations(client);+ if (!isAccountScopeCurrent(owner)) {+ return 'stale';+ }+ if (!canAddToCachedGalleryBoard(boardId, client)) {+ const cachedBoard = getCachedGalleryBoard(boardId, client);+ void invalidateGalleryBoardDestinations(client, owner);+ return cachedBoard && !canOnBoard(cachedBoard, 'add_media') ? 'board-view-only' : 'board-unavailable';+ }+ }try {const result = await exportLayer(layerId, { includeDisabled: true, signal: owner.signal });@@ -74,9 +107,23 @@ export const saveLayerToBoard = async (}const file = new File([result.blob], `layer-${layerId}.png`, { type: result.blob.type || 'image/png' });- await upload(file, boardId, { signal: owner.signal });+ try {+ await upload(file, boardId, { signal: owner.signal });+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ // A board that refused the upload re-reads the listings (destination read included) along with the items.+ if (isRealBoard) {+ void invalidateGalleryItems(client, owner);+ void invalidateGalleryBoardDestinations(client, owner);+ } else {+ void invalidateGallery(client, owner);+ }+ }+ throw error;+ }assertAccountScopeCurrent(owner);+ void invalidateGallery(client, owner);return 'saved';} catch (error) {if (!isAccountScopeCurrent(owner)) {