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(webv2): bind the gallery to server-owned project boards
joshistoast4d4446fdbdc4
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b32e2ba1de..9e09d14cc3 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2604,6 +2604,7 @@"downloadReady": "Download ready","downloadSelection": "Download selection","dropMediaToUploadToBoard": "Drop images or videos to upload to {{name}}",+ "exportProjectFromBoard": "Export project (.invk)","generationProgress": "Generation progress","generationProgressPercent": "Generation {{percentage}}%","hideArchivedBoards": "Hide archived boards",diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 3e73a6e54c..9ac49cabbe 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';import { GalleryUiProvider } from '@features/gallery/react';import { useActiveProgressTarget } from '@features/queue/react';+import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';import { getProjectWidgetValues } from '@workbench/widgetState';import {useActiveProjectId,@@ -36,12 +37,14 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const liveFollowEnabled = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);const liveProgressTarget = useActiveProgressTarget();const { account, gallery, notifications, widgets } = useWorkbenchCommands();+ const exportProject = useExportLibraryProject();const adapter = useMemo<GalleryUiAdapter>(() => ({account: {enableLiveFollow: () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),},antialiasProgressImages,+ exportProject,gallery,galleryValues,generateValues,@@ -58,6 +61,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })[account,antialiasProgressImages,+ exportProject,gallery,galleryValues,generateValues,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.tsindex cb78cb2910..3a730dec23 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts@@ -11,6 +11,7 @@ const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({imageCount: 50,kind: 'board',name: 'dogs',+ projectId: null,videoCount: 4,...overrides,});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsindex 07b2da0f33..c0856c6b70 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -32,6 +32,16 @@ export interface GalleryBoard {/** ISO creation timestamp; absent for uncategorized and date virtual boards. */createdAt?: string | null;ownerName?: string | null;+ /**+ * The project that owns this board, or `null` for an ordinary one.+ *+ * A project's board is part of that project: it takes its name from it, is+ * deleted with it, and the generic board routes refuse to rename, archive or+ * delete it. The UI hides those actions for *any* project-owned board, not just+ * the open project's — the server is authoritative either way, so a stale+ * client is refused rather than obeyed.+ */+ projectId: string | null;}export interface GalleryImage extends GeneratedImageContract {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 829c43f73a..6a220b3ffe 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -50,6 +50,11 @@ interface BackendBoardDTO {created_at?: string | null;/** Board owner's display name; populated only for admins on multi-user backends. */owner_username?: string | null;+ /**+ * The project that owns this board. The backend's board DTO excludes nulls, so+ * an ordinary board omits the key entirely rather than sending `null`.+ */+ project_id?: string | null;}/**@@ -211,6 +216,7 @@ const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({kind: 'board',name: board.board_name,ownerName: board.owner_username ?? null,+ projectId: board.project_id ?? null,videoCount: board.video_count ?? 0,});@@ -381,6 +387,8 @@ export const listGalleryBoards = async ({// Synthesized, not stored: `kind` is the durable fact and the UI resolves// the label from it, so no untranslatable name crosses the transport.name: '',+ // A virtual board is nobody's project board.+ projectId: null,videoCount: uncategorizedVideoCount,},...boards.filter((board) => includeArchived || !board.archived).map(mapBoard),@@ -415,6 +423,8 @@ export const listGalleryDateBoards = async (signal?: AbortSignal): Promise<GalleimageCount: board.image_count,kind: 'date',name: board.board_name,+ // A virtual board is nobody's project board.+ projectId: null,videoCount: board.video_count ?? 0,}));};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsxindex a83e9ff039..a202eb07c4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx@@ -42,6 +42,7 @@ const board = {imageCount: 2,kind: 'board',name: 'Board 1',+ projectId: null,videoCount: 1,} as const;const target = { board, x: 20, y: 20 };diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex be8f5efd1f..02005ea126 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -5,7 +5,7 @@ import { Dialog, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-import { Button } from '@platform/ui/Button';import { MenuContent } from '@platform/ui/Menu';import { ArchiveIcon, DownloadIcon, PencilIcon, Trash2Icon, type LucideIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useGalleryWidget } from './GalleryWidgetContext';@@ -20,20 +20,17 @@ export interface GalleryBoardMenuTarget {* Cursor-anchored actions menu for a single board row (download, rename,* archive, delete) so boards can be managed without selecting them first.* Opened from the board dropdown via right-click or the row's hover actions- * button; the dropdown stays open underneath (see onActiveChange).+ * button; the dropdown stays open underneath.*/export const GalleryBoardMenu = ({target,- onActiveChange,onClose,}: {target: GalleryBoardMenuTarget | null;- /** Reports whether the menu or one of its dialogs is showing, so the host dropdown can stay open. */- onActiveChange?: (isActive: boolean) => void;onClose: () => void;}) => {const { t } = useTranslation();- const { actions, gallery } = useGalleryWidget();+ const { actions } = useGalleryWidget();const [renameTarget, setRenameTarget] = useState<GalleryBoard | null>(null);const [deleteTarget, setDeleteTarget] = useState<GalleryBoard | null>(null);const [renameValue, setRenameValue] = useState('');@@ -42,14 +39,10 @@ export const GalleryBoardMenu = ({targetRef.current = target;const board = target?.board ?? null;- // Project boards can be downloaded but never renamed, archived, or deleted.- const isManagedBoard = board !== null && board.kind === 'board' && board.id !== gallery.projectBoardId;- const isActive = target !== null || renameTarget !== null || deleteTarget !== null;-- useEffect(() => {- onActiveChange?.(isActive);- }, [isActive, onActiveChange]);-+ // A project's board can be downloaded but never renamed, archived, or deleted: those follow+ // the project. This covers every project's board, not just the open one — the server refuses+ // all of them, so offering the action anywhere would only produce a 409.+ const isManagedBoard = board !== null && board.kind === 'board' && board.projectId === null;const positioning = useMemo(() => ({getAnchorRect: () => {@@ -140,6 +133,7 @@ export const GalleryBoardMenu = ({<Menu.Positioner>{board && (<MenuContent minW="12rem">+ {board.projectId !== null && <BoardExportProjectMenuItem board={board} />}<BoardDownloadMenuItem board={board} />{isManagedBoard && (<>@@ -232,6 +226,31 @@ export const GalleryBoardMenu = ({);};+/**+ * A project's board sits inside a project, so its menu offers both: the whole project as an+ * `.invk`, and the board's media on its own. The media-only download is the existing action and+ * keeps its video-omission warning; this one carries the document too.+ */+const BoardExportProjectMenuItem = ({ board }: { board: GalleryBoard }) => {+ const { t } = useTranslation();+ const { actions } = useGalleryWidget();+ const projectId = board.projectId;+ const handleClick = useCallback(() => {+ if (projectId !== null) {+ actions.exportProject(projectId, board.name);+ }+ }, [actions, board.name, projectId]);++ return (+ <BoardMenuItem+ icon={DownloadIcon}+ label={t('widgets.gallery.exportProjectFromBoard')}+ value="export-project"+ onClick={handleClick}+ />+ );+};+const BoardDownloadMenuItem = ({ board }: { board: GalleryBoard }) => {const { t } = useTranslation();const { actions } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsxindex 7ebce54ead..8052b81272 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx@@ -19,7 +19,6 @@ import { getBoardCounts } from './galleryStateView';export const GalleryBoardRow = ({board,isMenuOpen,- isProjectBoard,isSelected,loadedItemBoardIds,onOpenMenu,@@ -28,7 +27,6 @@ export const GalleryBoardRow = ({board: GalleryBoard;/** Its own menu is showing, so the trigger must not fade out from under it. */isMenuOpen?: boolean;- isProjectBoard: boolean;isSelected: boolean;loadedItemBoardIds: ReadonlyMap<GalleryItemKey, string>;/** Omitted for date rows, which have no board actions. */@@ -143,7 +141,7 @@ export const GalleryBoardRow = ({onContextMenu={onOpenMenu ? handleContextMenu : undefined}onSelect={handleSelect}>- {isProjectBoard ? (+ {board.projectId !== null ? (<Badge colorPalette={isSelected ? undefined : 'accent'} flexShrink={0} size="xs" variant="subtle">{t('common.project')}</Badge>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsxindex 7fb7f4135a..36b70ae0a9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx@@ -54,6 +54,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'assetCount: 3,imageCount: 50,kind: 'board',+ projectId: null,videoCount: 0,...overrides,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsxindex bf0b63960f..409e59398c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx@@ -165,7 +165,6 @@ export const GalleryBoardsPanel = () => {key={board.id}board={board}isMenuOpen={boardMenuTarget?.board.id === board.id}- isProjectBoard={board.id === gallery.projectBoardId}isSelected={board.id === gallery.selectedBoardId}loadedItemBoardIds={loadedItemBoardIds}onOpenMenu={openBoardMenu}@@ -194,7 +193,6 @@ export const GalleryBoardsPanel = () => {key={board.id}board={board}isMenuOpen={boardMenuTarget?.board.id === board.id}- isProjectBoard={false}isSelected={board.id === gallery.selectedBoardId}loadedItemBoardIds={loadedItemBoardIds}onSelectBoard={handleSelectBoard}@@ -215,7 +213,6 @@ export const GalleryBoardsPanel = () => {key={board.id}board={board}isMenuOpen={boardMenuTarget?.board.id === board.id}- isProjectBoard={false}isSelected={board.id === gallery.selectedBoardId}loadedItemBoardIds={loadedItemBoardIds}onOpenMenu={openBoardMenu}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex 9a2ccdd2bb..7f12832262 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -174,6 +174,7 @@ const board = {imageCount: 3,kind: 'board',name: 'Board A',+ projectId: null,videoCount: 1,} as const;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsxindex 8e8cd9e0bf..f21e6cff52 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx@@ -39,6 +39,7 @@ const board: GalleryBoard = {imageCount: 50,kind: 'board',name: 'dogs',+ projectId: null,videoCount: 0,};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsxindex 678b43c3ce..db84fbf585 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx@@ -46,6 +46,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'assetCount: 0,imageCount: 0,kind: 'board',+ projectId: null,videoCount: 0,...overrides,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 4faaca4b66..17d0685d1d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -96,6 +96,11 @@ export interface GalleryUiAdapter {notifications: GalleryNotificationsPort;projectId: string;projectName: string;+ /**+ * Export a project as an `.invk`, reporting progress itself. Keyed by project rather than+ * board because a board menu can offer this for any project's board, not only the open one.+ */+ exportProject(projectId: string, projectName: string): void;queueItems: QueueItem[];liveFollowEnabled: boolean;liveProgressTarget: GalleryLiveTarget | null;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex a620bc517b..358f8e4061 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -19,13 +19,16 @@ export interface GalleryActions {createBoard: (boardName: string) => Promise<void>;deleteBoard: (boardId: string, includeImages: boolean) => Promise<void>;downloadBoard: (boardId: string) => Promise<void>;+ /** Export the project that owns this board as a complete `.invk` archive. */+ exportProject: (projectId: string, projectName: string) => void;loadMore: () => void;refresh: () => void;renameBoard: (boardId: string, boardName: string) => Promise<void>;selectBoard: (boardId: string) => void;selectItem: (item: GalleryItem) => void;selectItemRange: (items: GalleryItemRef[], primaryItem: GalleryItem) => void;- selectProjectBoard: () => Promise<void>;+ /** Select the project's own board. It always exists, so this never creates one. */+ selectProjectBoard: () => void;setCompareItem: (image: GalleryImageItem | null) => void;setSearchTerm: (searchTerm: string) => void;setView: (galleryView: GalleryView) => void;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex f0e6fc954a..721f569c2f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -134,7 +134,6 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggetCurrentGalleryLocation,loadMore,projectBoardId: getGalleryProjectBoardId(galleryValues),- projectName,selectedBoardId,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.tsindex 8c0b3ad730..22f4dba423 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts@@ -9,6 +9,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'assetCount: 0,imageCount: 0,kind: 'board',+ projectId: null,videoCount: 0,...overrides,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.tsindex cfa414335a..02272bad03 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts@@ -11,6 +11,7 @@ const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({imageCount: 50,kind: 'board',name: 'dogs',+ projectId: null,videoCount: 4,...overrides,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 995df40b3d..63cb5da1b4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -22,9 +22,19 @@ const boards: GalleryBoard[] = [imageCount: 1,kind: 'uncategorized',name: '',+ projectId: null,+ videoCount: 0,+ },+ {+ archived: false,+ assetCount: 0,+ id: 'board-1',+ imageCount: 2,+ kind: 'board',+ name: 'Board 1',+ projectId: null,videoCount: 0,},- { archived: false, assetCount: 0, id: 'board-1', imageCount: 2, kind: 'board', name: 'Board 1', videoCount: 0 },];const createImage = (imageName: string): GeneratedImageContract => ({@@ -116,6 +126,32 @@ describe('gallery state view', () => {expect(getGalleryStateView(values, boards, [], false).selectedBoardId).toBe('none');});+ /**+ * A project arriving from another install — or one whose pre-migration board was rejected as+ * ambiguous — names a destination that does not exist here. Its own board is a better answer+ * than Uncategorized, which would quietly scatter the project's output.+ */+ it('falls back to the project board before uncategorized', () => {+ const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];+ const values = { projectBoardId: 'project-board', selectedBoardId: 'missing-board' };++ expect(getGallerySelectedBoardId(values, projectBoards)).toBe('project-board');+ expect(getGalleryStateView(values, projectBoards, [], false).selectedBoardId).toBe('project-board');+ });++ it('keeps a still-resolvable selection rather than reverting to the project board', () => {+ const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];+ const values = { projectBoardId: 'project-board', selectedBoardId: 'board-1' };++ expect(getGallerySelectedBoardId(values, projectBoards)).toBe('board-1');+ });++ it('falls back to uncategorized when the project board is gone too', () => {+ const values = { projectBoardId: 'deleted-board', selectedBoardId: 'missing-board' };++ expect(getGallerySelectedBoardId(values, boards)).toBe('none');+ });+it('does not render local fallback images while backend images are loading', () => {const values = { recentImages: [createImage('local-fallback.png')], selectedBoardId: 'none' };const gallery = getGalleryStateView(values, boards, null, true);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 3cdd27ab92..3e99f56221 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -28,6 +28,7 @@ const UNCATEGORIZED_BOARD: GalleryBoard = {imageCount: 0,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,};@@ -225,6 +226,17 @@ export const getGalleryView = (values: Record<string, unknown>): GalleryView =>export const getGallerySearchTerm = (values: Record<string, unknown>): string =>typeof values.searchTerm === 'string' ? values.searchTerm : '';+/**+ * Where new results land, resolved against the boards this install actually has.+ *+ * A saved selection survives whenever it still resolves — it is a deliberate choice, and a project+ * opened where its destination still exists should keep using it. When it does not resolve the+ * project's own board is the better answer than Uncategorized: a project arriving from another+ * install, or one whose pre-migration board was rejected as ambiguous, names a board id that means+ * nothing here, and dropping it to Uncategorized would quietly scatter that project's output.+ *+ * An empty board list means "still loading", not "no such board", so nothing is resolved yet.+ */export const getGallerySelectedBoardId = (values: Record<string, unknown>, backendBoards: GalleryBoard[]): string => {const selectedBoardId = typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none';@@ -232,6 +244,12 @@ export const getGallerySelectedBoardId = (values: Record<string, unknown>, backereturn selectedBoardId;}+ const projectBoardId = getGalleryProjectBoardId(values);++ if (projectBoardId !== null && backendBoards.some((board) => board.id === projectBoardId)) {+ return projectBoardId;+ }+return 'none';};@@ -372,6 +390,7 @@ export const getGalleryStateView = ({...UNCATEGORIZED_BOARD,imageCount: items.filter((item) => item.kind === 'image' && item.category === 'general').length,+ projectId: null,videoCount: items.filter((item) => item.kind === 'video').length,},];diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 8e9c2b5a74..737cc32881 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -120,6 +120,7 @@ const Probe = ({imageCount: 2,kind: 'board',name: 'Board 1',+ projectId: null,videoCount: 1,},{@@ -129,12 +130,12 @@ const Probe = ({imageCount: 0,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,},],loadMore: vi.fn(),projectBoardId: null,- projectName: 'Project',selectedBoardId,getCurrentGalleryLocation,});@@ -152,6 +153,7 @@ const adapter: GalleryUiAdapter = {ImageContextMenu: NoopContextMenu,account: { enableLiveFollow: noop },antialiasProgressImages: false,+ exportProject: vi.fn(),gallery: {reconcileDeletedBoardOutcome,selectBoard: noop,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex 95d721369e..56fcbea6c0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -31,17 +31,15 @@ export const useGalleryActions = ({getCurrentGalleryLocation,loadMore,projectBoardId,- projectName,selectedBoardId,}: {boards: GalleryBoard[];getCurrentGalleryLocation: () => { galleryView: GalleryView; selectedBoardId: string };loadMore: () => void;projectBoardId: string | null;- projectName: string;selectedBoardId: string;}): GalleryActions => {- const { gallery, notifications } = useGalleryUi();+ const { exportProject, gallery, notifications } = useGalleryUi();const queryClient = useQueryClient();const { t } = useTranslation();const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });@@ -171,6 +169,7 @@ export const useGalleryActions = ({recordError(error);}},+ exportProject,loadMore,refresh,renameBoard: async (boardId, boardName) => {@@ -193,32 +192,15 @@ export const useGalleryActions = ({selectBoard: gallery.selectBoard,selectItem: gallery.selectItem,selectItemRange: (items, primaryItem) => gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem),- selectProjectBoard: async () => {- const owner = captureAccountScope();-- if (projectBoardId && boards.some((board) => board.id === projectBoardId)) {+ /**+ * The project's board always exists — the server creates it with the project and+ * hydration writes its id into the document — so selecting it is just a selection.+ * There is deliberately no create-on-demand branch: a board this client made would+ * not be the project's, and the server would refuse to let a project adopt it later.+ */+ selectProjectBoard: () => {+ if (projectBoardId) {gallery.selectBoard(projectBoardId);- return;- }-- if (boards.length === 0) {- return;- }-- try {- const board = await createGalleryBoard(projectName, owner.signal);-- assertAccountScopeCurrent(owner);- gallery.setProjectBoard(board.id);- gallery.selectBoard(board.id);- recordSuccess(t('widgets.gallery.projectBoardCreated', { name: board.name }));- refresh();- } catch (error: unknown) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- recordError(error);}},setCompareItem: gallery.setCompareItem,@@ -230,11 +212,11 @@ export const useGalleryActions = ({};}, [boards,+ exportProject,gallery,loadMore,notifications,projectBoardId,- projectName,queryClient,selectedBoardId,t,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 9f04c0322b..04d8a803b0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -77,6 +77,7 @@ const adapter: GalleryUiAdapter = {ImageContextMenu: () => null,account: { enableLiveFollow: noop },antialiasProgressImages: false,+ exportProject: vi.fn(),gallery: {reconcileDeletedBoardOutcome: noop,selectBoard: noop,@@ -130,6 +131,7 @@ const Probe = ({imageCount: 2,kind: 'board',name: 'Board 1',+ projectId: null,videoCount: 1,},{@@ -139,6 +141,7 @@ const Probe = ({imageCount: 0,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,},],diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex e7904a2d20..4c47607710 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -161,6 +161,7 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<IimageCount: 0,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,},],diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.tsindex a740d5861c..87b30d22d6 100644--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts@@ -44,6 +44,7 @@ const uncategorized: GalleryBoard = {imageCount: 1,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,};const galleryT = ((key: string) => {diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.tsindex 19e31f3c19..a84ccb1993 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts@@ -36,7 +36,9 @@ const snapshot = (state: WorkbenchState, savedAt = '2026-07-17T00:00:00.000Z'):const saveResult = (state: WorkbenchState, savedAt?: string): WorkbenchSaveResult => ({conflicts: [],+ deletedProjectForks: [],hasPendingChanges: false,+ projectBoardAssignments: [],snapshot: snapshot(state, savedAt),});@@ -74,7 +76,12 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {listener();}};+ const boardAssignments: { boardId: string; projectId: string }[] = [];const port: PersistenceAggregatePort = {+ assignProjectBoard: (assignment) => {+ boardAssignments.push(assignment);+ events.push('assignProjectBoard');+ },getPersistedRevision: () => revision,getState: () => state,hydrate: (nextState) => {@@ -97,6 +104,15 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {events.push('conflict');emit();},+ reconcileDeletedProject: (fork) => {+ state = {+ ...state,+ projects: state.projects.map((project) => (project.id === fork.projectId ? fork.recoveredProject : project)),+ };+ revision += 1;+ events.push('deleted-fork');+ emit();+ },reportLoadError: (error) => events.push(`load-error:${error}`),saveFailed: (error) => events.push(`save-failed:${error}`),saveStarted: () => events.push('save-started'),@@ -113,6 +129,7 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {};return {+ boardAssignments,connect() {state = { ...state, backendConnection: { status: 'connected' } };emit();@@ -346,7 +363,9 @@ describe('Workbench persistence runtime', () => {serverProject: { ...original, name: 'Server' },},],+ deletedProjectForks: [],hasPendingChanges: false,+ projectBoardAssignments: [],snapshot: snapshot(aggregate.state),});clock.runAll();diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.tsindex b80914e623..c24986ae85 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts@@ -4,11 +4,15 @@ import type { WorkbenchState } from '@workbench/projectContracts';import type { WorkbenchLoadOptions, WorkbenchSaveResult } from './projects/syncedPersistence';export interface PersistenceAggregatePort {+ /** Point a project at the board the server minted for it. */+ assignProjectBoard(assignment: WorkbenchSaveResult['projectBoardAssignments'][number]): void;getPersistedRevision(): number;getState(): WorkbenchState;hydrate(state: WorkbenchState): void;notifyProjectNotFound(): void;reconcileConflict(conflict: WorkbenchSaveResult['conflicts'][number]): void;+ /** Replace a project deleted elsewhere with the fork carrying its unsaved edits. */+ reconcileDeletedProject(fork: WorkbenchSaveResult['deletedProjectForks'][number]): void;reportLoadError(error: string): void;saveFailed(error: string): void;saveStarted(): void;@@ -99,6 +103,14 @@ export const createWorkbenchPersistenceRuntime = ({for (const conflict of result.conflicts) {aggregate.reconcileConflict(conflict);}++ for (const fork of result.deletedProjectForks) {+ aggregate.reconcileDeletedProject(fork);+ }++ for (const assignment of result.projectBoardAssignments) {+ aggregate.assignProjectBoard(assignment);+ }};const isStaleSave = (revision: number, saveGeneration: number, requireCurrentRevision: boolean): boolean =>diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex d360b21df6..3303bbcf78 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -1,5 +1,5 @@import { mapWithConcurrency } from '@platform/core/concurrency';-import { collectLiveAssetRefs, selectCoverImageName, stripGallerySelection } from '@workbench/projects/projectAssets';+import { collectLiveAssetRefs, selectCoverImageName, stripInstallationState } from '@workbench/projects/projectAssets';import type { InvkArchiveEntry } from './archive';import type { FetchedThumbnail } from './assetTransport';@@ -68,7 +68,7 @@ export const planInvkExport = (input: {// list: not bundling a reference does not stop it travelling, it only stops// it arriving with pixels. The planner is where "what belongs in a project// file" is decided, so it is where the answer is applied.- const projectDocument = stripGallerySelection(input.projectDocument);+ const projectDocument = stripInstallationState(input.projectDocument);const refs = collectLiveAssetRefs(projectDocument);return {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex 02b52a925a..c12450adae 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName, stripGallerySelection } from './projectAssets';+import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName, stripInstallationState } from './projectAssets';/*** The walker's contract, stated as documents rather than as paths: what an@@ -208,9 +208,9 @@ describe('collectLiveAssetRefs', () => {* broken, and invisible to the restore pass that would otherwise report it as* dangling.*/-describe('stripGallerySelection', () => {+describe('stripInstallationState', () => {it('drops every selection key at any depth', () => {- const stripped = stripGallerySelection({+ const stripped = stripInstallationState({widgetInstances: {'gallery-1': {state: {@@ -239,11 +239,11 @@ describe('stripGallerySelection', () => {it('leaves a document with no selection identical', () => {const document = { canvas: { document: { layers: [imageLayer('l1', 'a.png')] } }, id: 'p1' };- expect(stripGallerySelection(document)).toBe(document);+ expect(stripInstallationState(document)).toBe(document);});it('keeps the surrounding widget state intact', () => {- const stripped = stripGallerySelection({+ const stripped = stripInstallationState({widgetInstances: {'gallery-1': { state: { values: { boardId: 'b1', selectedImageName: 'image:x.png' } }, typeId: 'gallery' },},@@ -253,6 +253,39 @@ describe('stripGallerySelection', () => {widgetInstances: { 'gallery-1': { state: { values: { boardId: 'b1' } }, typeId: 'gallery' } },});});++ /**+ * A board id means nothing on the machine a project arrives at, and the one+ * naming the project's own board is a cache the server overwrites anyway.+ */+ it('drops the gallery board ids from both the current and legacy widget shapes', () => {+ const stripped = stripInstallationState({+ widgetInstances: {+ 'gallery-1': {+ state: { values: { galleryView: 'images', projectBoardId: 'board-1', selectedBoardId: 'board-2' } },+ typeId: 'gallery',+ },+ },+ widgetStates: { gallery: { values: { projectBoardId: 'board-1', selectedBoardId: 'board-2' } } },+ });++ expect(JSON.stringify(stripped)).not.toContain('board-1');+ expect(JSON.stringify(stripped)).not.toContain('board-2');+ // Everything else the widget holds survives.+ expect(JSON.stringify(stripped)).toContain('galleryView');+ });++ /**+ * Only the gallery widget's own two keys are installation state. A board named+ * by a workflow node is an authored input and has to survive the round trip.+ */+ it('keeps board references that mean something to the document', () => {+ const document = {+ workflow: { nodes: [{ inputs: { board: { value: { board_id: 'board-3' } } }, type: 'save_image' }] },+ };++ expect(stripInstallationState(document)).toBe(document);+ });});describe('remapAssetRefs', () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 9325e9bd40..968e6f301e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -91,6 +91,25 @@ export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set(['selectedImageNames',]);+/**+ * Board ids the gallery widget holds: which board this project owns, and which+ * one new results are routed to. Both are *installation* state, not project+ * state — a board id means nothing on the machine the project arrives at.+ *+ * `projectBoardId` in particular is a cache, not a fact. The server owns the+ * project-to-board relationship, and hydration overwrites this from the project+ * record. Exporting it would carry a stale pointer to a board the receiving+ * install has never had, and importing it would fight the authoritative value+ * the create response is about to supply.+ *+ * Board ids elsewhere in the document — a workflow node's board input, say — are+ * semantically meaningful and are deliberately NOT stripped. That is why this+ * set names only the two keys the gallery widget owns.+ */+export const GALLERY_INSTALLATION_KEYS: ReadonlySet<string> = new Set(['projectBoardId', 'selectedBoardId']);++const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([...GALLERY_SELECTION_KEYS, ...GALLERY_INSTALLATION_KEYS]);+export interface ProjectAssetRefs {images: Set<string>;videos: Set<string>;@@ -174,7 +193,7 @@ const stripNode = (node: unknown): unknown => {const next: Record<string, unknown> = {};for (const [key, value] of Object.entries(node)) {- if (GALLERY_SELECTION_KEYS.has(key)) {+ if (INSTALLATION_STATE_KEYS.has(key)) {hasChanged = true;continue;}@@ -189,16 +208,21 @@ const stripNode = (node: unknown): unknown => {};/**- * Drop the gallery's selection keys at every depth, so an exported project- * opens with nothing selected rather than with pointers into the exporting- * install's gallery.+ * Drop everything that describes *this install* rather than the project — the+ * gallery's selection and its board ids — at every depth, so an exported project+ * opens with nothing selected, on the board the receiving server assigns it.** Every reader of these values already tolerates their absence — selection is- * parsed with `typeof`/`Array.isArray` guards and falls back to nothing — so- * removing the key is the same as clearing it, without inventing a shape.- * Subtrees with nothing to drop keep their identity.+ * parsed with `typeof`/`Array.isArray` guards and falls back to nothing, and the+ * board ids are re-supplied from the project record — so removing the key is the+ * same as clearing it, without inventing a shape. Subtrees with nothing to drop+ * keep their identity.+ *+ * Stripping by key at any depth rather than by walking into `widgetInstances` is+ * what makes this cover the legacy `widgetStates.gallery` shape for free, and it+ * is safe because these keys occur nowhere else in a project document.*/-export const stripGallerySelection = (projectDocument: Record<string, unknown>): Record<string, unknown> =>+export const stripInstallationState = (projectDocument: Record<string, unknown>): Record<string, unknown> =>stripNode(projectDocument) as Record<string, unknown>;export interface ProjectAssetMappings {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.tsindex 1404481495..c9c5cbeb9a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts@@ -73,6 +73,82 @@ export const normalizeLegacyProjectDocument = (data: Record<string, unknown>): R};};+const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const patchGalleryValues = (+ values: Record<string, unknown>,+ boardId: string,+ selectBoard: boolean+): Record<string, unknown> => ({+ ...values,+ projectBoardId: boardId,+ ...(selectBoard ? { selectedBoardId: boardId } : {}),+});++/**+ * Write the server's board id into a project document's gallery state.+ *+ * The server owns the project-to-board relationship; `projectBoardId` in the document is only a+ * cache of it. Every path that learns the authoritative id — hydrating a record, creating a+ * project, importing one, duplicating one, forking a conflicted one — comes through here, so there+ * is one place that decides what "the project's board" means in a document.+ *+ * `selectBoard` distinguishes the two cases. A project the user is meeting for the first time+ * should also be *pointed* at its board; one being re-hydrated should keep whatever destination+ * the user last chose, which `getGallerySelectedBoardId` resolves separately.+ *+ * Both widget shapes are patched — the current `widgetInstances` map and the `widgetStates.gallery`+ * one older builds wrote — and a document with neither is returned untouched rather than having a+ * shape invented for it.+ */+export const applyAuthoritativeProjectBoard = (+ projectDocument: Record<string, unknown>,+ boardId: string,+ options: { selectBoard: boolean }+): Record<string, unknown> => {+ let hasChanged = false;+ const next: Record<string, unknown> = { ...projectDocument };++ const instances = projectDocument.widgetInstances;+ if (isRecord(instances)) {+ const nextInstances: Record<string, unknown> = {};++ for (const [instanceId, instance] of Object.entries(instances)) {+ const state = isRecord(instance) ? instance.state : null;++ if (!isRecord(instance) || instance.typeId !== 'gallery' || !isRecord(state)) {+ nextInstances[instanceId] = instance;+ continue;+ }++ const values = isRecord(state.values) ? state.values : {};++ nextInstances[instanceId] = {+ ...instance,+ state: { ...state, values: patchGalleryValues(values, boardId, options.selectBoard) },+ };+ hasChanged = true;+ }++ next.widgetInstances = nextInstances;+ }++ const states = projectDocument.widgetStates;+ if (isRecord(states) && isRecord(states.gallery)) {+ const gallery = states.gallery;+ const values = isRecord(gallery.values) ? gallery.values : {};++ next.widgetStates = {+ ...states,+ gallery: { ...gallery, values: patchGalleryValues(values, boardId, options.selectBoard) },+ };+ hasChanged = true;+ }++ return hasChanged ? next : projectDocument;+};+/*** The minimum a document must carry to be a project at all. A document that* fails this can never rehydrate, so callers that only need to reject junkdiff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 41e32859f8..4c0716e2c7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -3,6 +3,7 @@ import type { Project } from '@workbench/projectContracts';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it } from 'vitest';+import { applyAuthoritativeProjectBoard } from './projectDocument';import { createRecoveredDocument, deserializeProjectDocument, serializeProjectDocument } from './syncedPersistence';const getProject = (overrides: Partial<Project> = {}): Project => {@@ -214,3 +215,72 @@ describe('reconcileProjectConflict', () => {expect(next.activeProjectId).toBe(second.id);});});++/**+ * SQLite owns which board belongs to which project; the document only caches it. This is the one+ * place that writes that cache, so every path — hydration, create, import, duplicate, fork —+ * agrees on what "the project's board" means.+ */+describe('applyAuthoritativeProjectBoard', () => {+ const galleryDocument = (values: Record<string, unknown>): Record<string, unknown> => ({+ widgetInstances: {+ 'canvas-1': { state: { values: { projectBoardId: 'not-the-gallery' } }, typeId: 'canvas' },+ 'gallery-1': { state: { values }, typeId: 'gallery' },+ },+ });++ const galleryValues = (document: Record<string, unknown>): Record<string, unknown> =>+ (+ (document.widgetInstances as Record<string, { state: { values: Record<string, unknown> } }>)['gallery-1'] as {+ state: { values: Record<string, unknown> };+ }+ ).state.values;++ it('replaces the project board and leaves a chosen destination alone', () => {+ const patched = applyAuthoritativeProjectBoard(+ galleryDocument({ galleryView: 'assets', projectBoardId: 'stale', selectedBoardId: 'chosen' }),+ 'authoritative',+ { selectBoard: false }+ );++ expect(galleryValues(patched)).toEqual({+ galleryView: 'assets',+ projectBoardId: 'authoritative',+ selectedBoardId: 'chosen',+ });+ });++ it('also points a first-seen project at its board', () => {+ const patched = applyAuthoritativeProjectBoard(galleryDocument({ selectedBoardId: 'chosen' }), 'authoritative', {+ selectBoard: true,+ });++ expect(galleryValues(patched).selectedBoardId).toBe('authoritative');+ });++ it('only touches the gallery widget', () => {+ const patched = applyAuthoritativeProjectBoard(galleryDocument({}), 'authoritative', { selectBoard: true });+ const instances = patched.widgetInstances as Record<string, { state: { values: Record<string, unknown> } }>;++ expect(instances['canvas-1']!.state.values.projectBoardId).toBe('not-the-gallery');+ });++ it('patches the legacy widget-states shape too', () => {+ const patched = applyAuthoritativeProjectBoard(+ { widgetStates: { gallery: { values: { projectBoardId: 'stale' } } } },+ 'authoritative',+ { selectBoard: true }+ ) as { widgetStates: { gallery: { values: Record<string, unknown> } } };++ expect(patched.widgetStates.gallery.values).toEqual({+ projectBoardId: 'authoritative',+ selectedBoardId: 'authoritative',+ });+ });++ it('invents no shape for a document with no gallery', () => {+ const document = { id: 'p1', name: 'No gallery' };++ expect(applyAuthoritativeProjectBoard(document, 'authoritative', { selectBoard: true })).toBe(document);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.tsindex 8dd3b9af7a..b05ec24b87 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts@@ -18,6 +18,8 @@ import type * as persistenceModule from './syncedPersistence';const api = vi.hoisted(() => {interface MockRecord {project_id: string;+ /** Every project owns one, and the server is the only thing that decides which. */+ board_id: string;name: string;revision: number;created_at: string;@@ -31,6 +33,7 @@ const api = vi.hoisted(() => {const conflictError = (): Error => Object.assign(new Error('conflict'), { __status: 409 });const notFoundError = (): Error => Object.assign(new Error('not found'), { __status: 404 });const toSummary = (record: MockRecord) => ({+ board_id: record.board_id,created_at: record.created_at,name: record.name,project_id: record.project_id,@@ -46,6 +49,7 @@ const api = vi.hoisted(() => {const id = data.id as string;records.set(id, {+ board_id: `board-for-${id}`,created_at: '2026-06-10 08:00:00.000',data: structuredClone(data),name: data.name as string,@@ -54,26 +58,29 @@ const api = vi.hoisted(() => {updated_at: '2026-06-10 08:00:00.000',});},- createProject: vi.fn((request: { project_id?: string; name: string; data: Record<string, unknown> }) => {- const id = request.project_id ?? `generated-${records.size}`;+ createProject: vi.fn(+ (request: { project_id?: string; board_id?: string; name: string; data: Record<string, unknown> }) => {+ const id = request.project_id ?? `generated-${records.size}`;- if (records.has(id)) {- return Promise.reject(conflictError());- }+ if (records.has(id)) {+ return Promise.reject(conflictError());+ }- const record: MockRecord = {- created_at: '2026-06-10 09:00:00.000',- data: structuredClone(request.data),- name: request.name,- project_id: id,- revision: 1,- updated_at: '2026-06-10 09:00:00.000',- };+ const record: MockRecord = {+ board_id: request.board_id ?? `board-for-${id}`,+ created_at: '2026-06-10 09:00:00.000',+ data: structuredClone(request.data),+ name: request.name,+ project_id: id,+ revision: 1,+ updated_at: '2026-06-10 09:00:00.000',+ };- records.set(id, record);+ records.set(id, record);- return Promise.resolve(clone(record));- }),+ return Promise.resolve(clone(record));+ }+ ),deleteClientStateValue: vi.fn((key: string) => {clientState.delete(key);@@ -632,3 +639,69 @@ describe('hydrateProjectFromServer', () => {expect(await service.hydrateProjectFromServer('nope')).toBeNull();});});++/**+ * The document's `projectBoardId` is a cache of a relationship SQLite owns. Every path that learns+ * the real answer has to write it down, or the project points at a board that means nothing here.+ */+describe('authoritative project boards', () => {+ const galleryBoardIds = (project: Project): { projectBoardId?: unknown; selectedBoardId?: unknown } => {+ const instance = Object.values(project.widgetInstances).find((entry) => entry.typeId === 'gallery');++ return (instance?.state.values ?? {}) as { projectBoardId?: unknown; selectedBoardId?: unknown };+ };++ it('reports the board the server minted for a project it created', async () => {+ const draft = createDraftProject([]);++ const result = await service.saveWorkbench(stateWithProjects([draft]));++ expect(result.projectBoardAssignments).toEqual([{ boardId: `board-for-${draft.id}`, projectId: draft.id }]);+ // Drained, so the next save does not re-apply it.+ expect((await service.saveWorkbench(stateWithProjects([draft]))).projectBoardAssignments).toEqual([]);+ });++ it('overwrites a stale board id when hydrating a record', async () => {+ const draft = createDraftProject([]);+ const document = persistence.serializeProjectDocument(draft) as Record<string, unknown>;+ const instances = document.widgetInstances as Record<string, { state: { values: Record<string, unknown> } }>;+ const galleryId = Object.keys(instances).find(+ (key) => (instances[key] as unknown as { typeId: string }).typeId === 'gallery'+ )!;++ // A board id written by some other install, naming a board that does not exist here.+ instances[galleryId]!.state.values.projectBoardId = 'board-from-another-machine';+ instances[galleryId]!.state.values.selectedBoardId = 'deliberate-destination';+ api.__seed(document);++ const hydrated = await service.hydrateProjectFromServer(draft.id);++ expect(galleryBoardIds(hydrated!).projectBoardId).toBe(`board-for-${draft.id}`);+ // The chosen destination is the user's, not ours; resolving it is the gallery's job.+ expect(galleryBoardIds(hydrated!).selectedBoardId).toBe('deliberate-destination');+ });++ it('forks rather than resurrects a project deleted on another device', async () => {+ const project = seedServerProject('Deleted elsewhere');+ const opened = await service.hydrateProjectFromServer(project.id);+ const edited = { ...opened!, name: 'Edited locally' };++ // Deleted on the other device, after this one had already synced.+ api.__records.delete(project.id);++ const result = await service.saveWorkbench(stateWithProjects([edited]));++ // The deletion stands...+ expect(api.__records.has(project.id)).toBe(false);+ // ...and the work survives under a fresh id, with a board of its own.+ expect(result.deletedProjectForks).toHaveLength(1);+ const [fork] = result.deletedProjectForks;+ expect(fork!.projectId).toBe(project.id);+ expect(fork!.recoveredProject.id).not.toBe(project.id);+ expect(fork!.recoveredProject.name).toBe('Edited locally (recovered)');+ expect(api.__records.get(fork!.recoveredProject.id)).toBeDefined();+ expect(result.projectBoardAssignments).toEqual([+ { boardId: `board-for-${fork!.recoveredProject.id}`, projectId: fork!.recoveredProject.id },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 01187d12a9..ebc379f66b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -25,7 +25,12 @@ import {import { recordProjectCover } from './covers';import { seedProjectLibrary, upsertProjectSummary } from './library';import { selectCoverImageName } from './projectAssets';-import { isProjectDocumentShape, normalizeLegacyProjectDocument, serializeProjectDocument } from './projectDocument';+import {+ applyAuthoritativeProjectBoard,+ isProjectDocumentShape,+ normalizeLegacyProjectDocument,+ serializeProjectDocument,+} from './projectDocument';import { fetchSessionBlob, serializeSessionBlob, SESSION_STATE_KEY } from './session';import { reportProjectSync, type ProjectSyncInfo } from './syncStore';@@ -69,11 +74,35 @@ export interface ProjectConflictResolution {recoveredProject: Project;}+/** Local edits rescued from a project that was deleted on another device. */+export interface ProjectDeletionFork {+ projectId: string;+ /** The fork carrying the local edits, under a fresh id and its own board. */+ recoveredProject: Project;+}++/** A board the server assigned to a project this save created. */+export interface ProjectBoardAssignment {+ boardId: string;+ projectId: string;+}+export interface WorkbenchSaveResult {snapshot: HydratedWorkbenchSnapshot;conflicts: ProjectConflictResolution[];/** True when changes are cached locally but could not reach the backend. */hasPendingChanges: boolean;+ /**+ * Boards the server minted for projects created during this save. A draft is created by+ * persistence rather than by the editor, so the create response is the only place its board id+ * exists — discarding it would leave the project pointing at no board until the next reload.+ */+ projectBoardAssignments: ProjectBoardAssignment[];+ /**+ * Projects deleted elsewhere whose unsaved local edits were forked rather than re-created. The+ * deletion stands; the work does not.+ */+ deletedProjectForks: ProjectDeletionFork[];}export interface WorkbenchLoadOptions {@@ -91,6 +120,8 @@ interface SyncedPersistenceState {lastPushedAccount: string | null;/** Immutable owner captured when this synchronization lifetime was constructed. */owner: AccountScope;+ /** Boards learned from create responses, drained by the next save. */+ pendingBoardAssignments: ProjectBoardAssignment[];projectDocumentJsonCache: WeakMap<Project, { document: Record<string, unknown>; json: string }>;/** Server-known projects, keyed by project id. */syncEntries: Map<string, SyncEntry>;@@ -102,6 +133,7 @@ const createSyncedPersistenceState = (owner: AccountScope): SyncedPersistenceStalocalPersistence: createLocalStorageWorkbenchPersistence(owner.storageSuffix),lastPushedAccount: null,owner,+ pendingBoardAssignments: [],projectDocumentJsonCache: new WeakMap(),syncEntries: new Map(),});@@ -139,6 +171,18 @@ const getSerializedProjectDocument = (return serialized;};+/**+ * Rehydrate a *server record*, which knows the project's real board.+ *+ * The document's own `projectBoardId` is a cache and can be stale — written by another install, or+ * replaced by the migration when the board it named turned out to be ambiguous. Overwriting it+ * here means every path that reads a project from the server agrees on one answer, and the next+ * autosave writes the correction back. The saved destination is left alone: it is a deliberate+ * choice, and `getGallerySelectedBoardId` resolves it against the boards that actually exist.+ */+const deserializeProjectRecord = (record: ProjectRecordDTO): Project | null =>+ deserializeProjectDocument(applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: false }));+/*** Rehydrate a document into a live project. This is the half of the codec that* needs the aggregate reducer, so it stays here rather than in@@ -214,6 +258,7 @@ const pushNewProject = async (syncState: SyncedPersistenceState, project: ProjecassertOwner(syncState);syncState.syncEntries.set(project.id, { pushedDoc: JSON.stringify(document), revision: created.revision });+ syncState.pendingBoardAssignments.push({ boardId: created.board_id, projectId: project.id });return true;} catch (error) {@@ -230,6 +275,7 @@ const pushNewProject = async (syncState: SyncedPersistenceState, project: ProjecpushedDoc: JSON.stringify(existing.data),revision: existing.revision,});+ syncState.pendingBoardAssignments.push({ boardId: existing.board_id, projectId: project.id });return true;} catch {@@ -314,7 +360,7 @@ const recoverConflictingProject = async (return { kind: 'retry' };}- const serverProject = deserializeProjectDocument(server.data);+ const serverProject = deserializeProjectRecord(server);if (!serverProject) {return { kind: 'failed' };@@ -346,10 +392,53 @@ const recoverConflictingProject = async (}};+/**+ * Rescue the local edits of a project the server no longer has.+ *+ * Deliberately a *fork*, not a re-create. Pushing the original id back would resurrect a project+ * the user deleted — on every device, and here as a project whose board went with the deletion.+ * The fork gets a fresh id, and with it a fresh board from the create response.+ */+const forkDeletedProject = async (+ syncState: SyncedPersistenceState,+ project: Project,+ document: Record<string, unknown>+): Promise<ProjectDeletionFork | null> => {+ assertOwner(syncState);++ const { recoveredDocument, recoveredId, recoveredName } = createRecoveredDocument(project, document);+ const recoveredProject = deserializeProjectDocument(recoveredDocument);++ if (!recoveredProject) {+ return null;+ }++ try {+ const created = await apiCreateProject(+ { data: recoveredDocument, name: recoveredName, project_id: recoveredId },+ syncState.owner.signal+ );++ assertOwner(syncState);+ syncState.syncEntries.set(recoveredId, {+ pushedDoc: JSON.stringify(recoveredDocument),+ revision: created.revision,+ });+ syncState.pendingBoardAssignments.push({ boardId: created.board_id, projectId: recoveredId });++ return { projectId: project.id, recoveredProject };+ } catch {+ assertOwner(syncState);++ return null;+ }+};+const pushProject = async (syncState: SyncedPersistenceState,project: Project,- conflicts: ProjectConflictResolution[]+ conflicts: ProjectConflictResolution[],+ deletedProjectForks: ProjectDeletionFork[]): Promise<string> => {assertOwner(syncState);const { document, json: documentJson } = getSerializedProjectDocument(syncState, project);@@ -415,13 +504,19 @@ const pushProject = async (syncState.hasPending = true;}} else if (isProjectNotFoundError(error)) {- // Deleted on another device while we held local edits: recreate rather- // than drop the user's work.+ // Deleted on another device while we held local edits. Re-creating under the same id would+ // undo that deletion — the project would reappear on every device, and on this one it would+ // be a project whose board the deletion already took. Fork instead: the deletion stands, and+ // the local work survives as a recovered project with its own id and its own board.syncState.syncEntries.delete(project.id);- if (!(await pushNewProject(syncState, project))) {- assertOwner(syncState);+ const fork = await forkDeletedProject(syncState, project, document);++ assertOwner(syncState);+ if (fork === null) {syncState.hasPending = true;+ } else {+ deletedProjectForks.push(fork);}} else {syncState.hasPending = true;@@ -524,7 +619,7 @@ const loadFromBackend = async (continue;}- const project = deserializeProjectDocument(record.data);+ const project = deserializeProjectRecord(record);if (project) {serverProjects.push(project);@@ -690,7 +785,7 @@ export const createSyncedWorkbenchPersistence = (const adoptProjectRecord = (record: ProjectRecordDTO): Project | null => {assertOwner(syncState);- const project = deserializeProjectDocument(record.data);+ const project = deserializeProjectRecord(record);if (!project) {return null;@@ -721,9 +816,12 @@ export const createSyncedWorkbenchPersistence = (},flushProjectToServer(project): Promise<void> {return enqueueMutation(async () => {+ // A flush is a targeted push, not a save: its outcomes are surfaced by the next save,+ // which is what carries them to the store.const conflicts: ProjectConflictResolution[] = [];+ const deletedProjectForks: ProjectDeletionFork[] = [];- await pushProject(syncState, project, conflicts);+ await pushProject(syncState, project, conflicts, deletedProjectForks);assertOwner(syncState);persistSyncMap(syncState);});@@ -873,6 +971,7 @@ export const createSyncedWorkbenchPersistence = (syncState.hasPending = false;const conflicts: ProjectConflictResolution[] = [];+ const deletedProjectForks: ProjectDeletionFork[] = [];const projectSyncInfos: Record<string, ProjectSyncInfo> = {};await pushSessionState(syncState, state);@@ -881,7 +980,7 @@ export const createSyncedWorkbenchPersistence = (for (const project of state.projects) {assertOwner(syncState);const lastAckedDoc = syncState.syncEntries.get(project.id)?.pushedDoc ?? null;- const documentJson = await pushProject(syncState, project, conflicts);+ const documentJson = await pushProject(syncState, project, conflicts, deletedProjectForks);assertOwner(syncState);const entry = syncState.syncEntries.get(project.id);@@ -901,7 +1000,16 @@ export const createSyncedWorkbenchPersistence = (persistSyncMap(syncState);reportProjectSync({ hasPendingChanges: syncState.hasPending, projects: projectSyncInfos });- return { conflicts, hasPendingChanges: syncState.hasPending, snapshot };+ // Drained rather than read: each assignment is applied to the store exactly once.+ const projectBoardAssignments = syncState.pendingBoardAssignments.splice(0);++ return {+ conflicts,+ deletedProjectForks,+ hasPendingChanges: syncState.hasPending,+ projectBoardAssignments,+ snapshot,+ };});},unmarkProjectDeleted(projectId): void {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 00c8fc410c..979d808360 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -126,6 +126,7 @@ const fallbackBoards: GalleryBoard[] = [imageCount: 0,kind: 'uncategorized',name: '',+ projectId: null,videoCount: 0,},];diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 22c33ac29b..cd2381e067 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -322,6 +322,7 @@ type WorkbenchReducerAction =| { type: 'redoProjectChange' }| { type: 'hydrateWorkbench'; state: WorkbenchState }| { type: 'reconcileProjectConflict'; projectId: string; serverProject: Project; recoveredProject: Project }+ | { type: 'reconcileDeletedProject'; projectId: string; recoveredProject: Project }| { type: 'autosaveStarted' }| { type: 'autosaveSucceeded'; savedAt: string }| { type: 'autosaveFailed'; error: string }@@ -3645,6 +3646,30 @@ export const __workbenchReducerInternal = (}));}+ case 'reconcileDeletedProject': {+ // The project was deleted on another device while this one held unsaved edits. Unlike a+ // revision conflict there is no server version to adopt — the deletion is the server's+ // answer. Re-creating the id would undo it everywhere, so the local edits continue under a+ // fresh identity and the original simply goes.+ const recoveredProject = normalizeWorkbenchProject(action.recoveredProject);+ const hasOriginal = state.projects.some((project) => project.id === action.projectId);+ const projects = hasOriginal+ ? state.projects.map((project) => (project.id === action.projectId ? recoveredProject : project))+ : [...state.projects, recoveredProject];++ return addNotification(+ {+ ...state,+ activeProjectId: state.activeProjectId === action.projectId ? recoveredProject.id : state.activeProjectId,+ projects,+ },+ createNotification({+ kind: 'info',+ message: `That project was deleted elsewhere. Your unsaved edits continue in "${recoveredProject.name}".`,+ title: 'Project recovered',+ })+ );+ }case 'autosaveStarted': {return { ...state, autosave: { status: 'saving' } };}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 23eccefbdd..a42a7fac71 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -411,9 +411,19 @@ const createPersistenceAdapter = (dispatch: WorkbenchDispatch, getState: () => Wconst command = createCommandFactory(dispatch);return {+ /**+ * A project created by persistence learns its board from the create response. Both writes+ * belong together: the id records which board is the project's, and selecting it is what+ * makes the project's own output land there rather than in Uncategorized.+ */+ assignProjectBoard: ({ boardId, projectId }: { boardId: string; projectId: string }) => {+ dispatch({ boardId, projectId, type: 'setGalleryProjectBoardId' });+ dispatch({ boardId, projectId, type: 'selectGalleryBoard' });+ },getState,hydrate: command('hydrateWorkbench', (state: WorkbenchState) => ({ state })),reconcileConflict: command('reconcileProjectConflict'),+ reconcileDeletedProject: command('reconcileDeletedProject'),saveFailed: command('autosaveFailed', (error: string) => ({ error })),saveStarted: command('autosaveStarted'),saveSucceeded: command('autosaveSucceeded', (savedAt: string) => ({ savedAt })),