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(gallery): drag boards between projects and settle project board changes
Josh Corbett3a350f562672
diff --git a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdxindex 5bf24568bf..b5743b790f 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx@@ -25,7 +25,7 @@ Hover over a board and click its **⋮** button, or right-click it, to open its* **Auto-add to this board** — makes this the board that receives new results, marked **Auto**, whichever board is selected. On the auto-add board, the item is **Stop auto-adding here**, which goes back to sending results to the selected board. Not offered for date boards or archived boards. See [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes).* **Download Board** — downloads the board (see [below](#downloading-a-board)).* **Rename board** — opens a dialog to change the name.-* **Move to…** — moves the board to the **Library**, into the open project, or into one of your other projects. A board in a project is private to you.+* **Move to…** — moves the board to the **Library**, into the open project, or into one of your other projects. A board in a project is private to you. You can also drag the board onto another group: the open project's, the **Library**, or one of the projects under **Other projects**. When the board's new project is hidden because **Other projects' boards** is off: if it was the selected board, the Gallery selects **Uncategorized**; if it was the auto-add board, results follow the selected board again.* **Archive Board** / **Unarchive Board** — see [below](#archiving-a-board).* **Delete Board** — see [below](#deleting-a-board).diff --git a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdxindex 7f7e277c67..8f509325cc 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx@@ -23,7 +23,7 @@ The **Gallery** holds every image and video you generate or upload. It is organiThe Gallery has three parts:* **The header** shows the selected board after *Gallery /*. Click the board name to hide or show the board list. The gear button opens the [Gallery settings](/users-guide/gallery/gallery-reference/#gallery-settings).-* **The board list** has a search field (**Search or create boards**), a **Filter & sort boards** button, and the boards themselves, grouped under the open project's name, **Library** and, when turned on, **Other projects**, **By Date** and **Archived**. Each group can be collapsed; the project and Library groups show how many boards you have made in them, and **Other projects** how many projects it lists.+* **The board list** has a search field (**Search or create boards**), a **Filter & sort boards** button, and the boards themselves, grouped under the open project's name, **Library** and, when turned on, **Other projects**, **By Date** and **Archived**. Each group can be collapsed; the project group shows how many boards it has, its Inbox included, the **Library** how many it has besides **Uncategorized**, and **Other projects** how many projects it lists.* **The media area** shows the contents of the selected board, on two tabs:* **Media** — images and videos generated in InvokeAI.* **Uploads** — images, videos and audio you have uploaded.diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxindex 515a8650ce..2c4e8d5df5 100644--- a/docs/src/content/docs/development/Front End/project-files.mdx+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -119,13 +119,13 @@ The skip is by key on purpose, because the members got there differently. `selecImport deliberately orders its work as **read → mint identity → validate and canonicalize → stage boards → restore → remap → create → place the other boards**. It first reads the archive without mutating the server, then assigns the imported project a fresh id and name. The candidate is rehydrated through the Workbench reducer and serialized back to its canonical document before any asset is restored. Only then are missing assets restored, their server-assigned names remapped throughout that canonical document, and the new project created. A malformed document therefore cannot leave restored orphan assets behind, and an import can never overwrite the project whose id was recorded in the archive.-**Creating the project is the commit point.** When an archive carries `board.json`, the restore first creates an unclaimed private *staging board* per board, in the archive's order so creation order survives — the inbox's named after the project, the others after themselves — and uploads onto them, then passes the inbox's id to `POST /projects`, which claims and renames it in the same transaction that writes the remapped document. The other staged boards are moved into the project with `PATCH /boards/{id}` once it exists, archived as the source had them. That placement is reported, never fatal: a project with most of its boards beats none, and a staged board that could not move is still in the Library with everything on it, which is what the import's toast says. Every staging board joins the rollback ledger the moment it exists, so a restore abandoned between two creates leaves nothing behind. Creating the project first would mean posting the old names and then updating with the remapped ones — making the update the commit point, where a failure leaves a real project full of references to media that never arrived. An archive without `board.json`, like a legacy JSON document, has no board to stage, so the server simply creates an empty one, exactly as it does for a project made from scratch.+**Creating the project is the commit point.** When an archive carries `board.json`, the restore first creates an unclaimed private *staging board* per board, in the archive's order so creation order survives — the inbox's named after the project, the others after themselves — and uploads onto them, then passes the inbox's id to `POST /projects`, which claims and renames it in the same transaction that writes the remapped document. The other staged boards are moved into the project with `PATCH /boards/{id}` once it exists, archived as the source had them. That placement is reported, never fatal: a project with most of its boards beats none, and a staged board that could not move is still in the Library with everything on it, which is what the import's toast says. The moves report their own progress, board by board, and the board lists are refreshed once the last one settles: the refresh that follows the create can read the boards while they are still in the Library. Every staging board joins the rollback ledger the moment it exists, so a restore abandoned between two creates leaves nothing behind. Creating the project first would mean posting the old names and then updating with the remapped ones — making the update the commit point, where a failure leaves a real project full of references to media that never arrived. An archive without `board.json`, like a legacy JSON document, has no board to stage, so the server simply creates an empty one, exactly as it does for a project made from scratch.The legacy JSON path follows the same fresh-identity validation and canonicalization boundary, then creates the project directly. A JSON envelope carries no bundled media, so it performs no existence checks, uploads, restoration or remapping.### Board media always gets a fresh identity-`board_images` has `PRIMARY KEY (image_name)`: an image sits on exactly one board. A restore that saw its own name already on the destination and reused it would not be restoring the project's board — it would be *moving* somebody else's image onto it, and deleting either project's board would then take that image from both. So every board item is uploaded (or, when duplicating, copied) unconditionally, with no existence check, and the document is rewritten to the new name. Its archived category and starring are restored: the category on upload, the starring through the same `POST /images/star` the gallery uses, so import and duplication share one starring path.+`board_images` has `PRIMARY KEY (image_name)`: an image sits on exactly one board. A restore that saw its own name already on the destination and reused it would not be restoring the project's board — it would be *moving* somebody else's image onto it, and deleting either project's board would then take that image from both. So every board item is uploaded (or, when duplicating, copied) unconditionally, with no existence check, and the document is rewritten to the new name. Uploads share one pool of 5 across all the boards, so an archive of many small boards restores as quickly as one with a single large board; duplication copies board by board, each board in one batched request. Its archived category and starring are restored: the category on upload, the starring through the same `POST /images/star` the gallery uses, so import and duplication share one starring path.Document references outside the board keep the v2 behaviour: an identity the destination already has satisfies them, so nothing is uploaded twice. That is what makes re-importing your own export nearly free.@@ -145,7 +145,7 @@ An open project is flushed to the server before it is read, and a failed flush a### Rollback-Restoration records the authoritative server names returned by every successful upload or copy, as it goes rather than at the end, so a restore that is cancelled part way through is still cleanable. If project creation then rejects while the importing account scope is still current, import checks the client-chosen project id and sends those names to the image and video batch-delete routes only when the server confirms that id is absent with `404`. A found project or an inconclusive lookup is an ambiguous create, so cleanup is skipped rather than deleting assets that the project may already reference. Cleanup is best-effort and never replaces the primary create error. It is also skipped after a create has returned and after a cross-account rotation: issuing destructive deletes with a new account's credentials would be unsafe. That safety boundary means a rotation after upload can still leave private-category media behind when the old account can no longer authorize cleanup.+Restoration records the authoritative server names returned by every successful upload or copy, as it goes rather than at the end, so a restore that is cancelled part way through is still cleanable. If project creation then rejects while the importing account scope is still current, import checks the client-chosen project id and sends those names to the image and video batch-delete routes only when the server confirms that id is absent with `404`. When neither the create nor its retry gets an answer, one more read settles the outcome only if it finds this create's project, which is then treated as created so its other boards are still moved in; a `404` there may predate the commit and proves nothing. A found project or an inconclusive lookup is an ambiguous create, so cleanup is skipped rather than deleting assets that the project may already reference. Cleanup is best-effort and never replaces the primary create error. It is also skipped after a create has returned and after a cross-account rotation: issuing destructive deletes with a new account's credentials would be unsafe. That safety boundary means a rotation after upload can still leave private-category media behind when the old account can no longer authorize cleanup.Each staging board is deleted last, and with `include_images=false`, so anything that wandered onto it while the import ran — a generation that finished in the meantime — survives as Uncategorized rather than being collected by a cleanup that never meant it.diff --git a/invokeai/app/services/intermediates/intermediates_records_default.py b/invokeai/app/services/intermediates/intermediates_records_default.pyindex cc82c86979..64fd802729 100644--- a/invokeai/app/services/intermediates/intermediates_records_default.py+++ b/invokeai/app/services/intermediates/intermediates_records_default.py@@ -306,7 +306,7 @@ class IntermediatesRecords:return self._queries.run(summarize, read_only=True)def get_projects(self, user_id: Optional[str]) -> dict[tuple[str, str], tuple[str, Optional[str]]]:- """Maps (owner, project) to (name, cover image): the newest durable image on the project's board."""+ """Maps (owner, project) to (name, cover image): the newest durable image on any of the project's boards."""return {(owner, project_id): (name, cover)for owner, project_id, name, cover in self._queries.intermediates.projects(user_id)diff --git a/invokeai/app/services/shared/database/queries/intermediates.py b/invokeai/app/services/shared/database/queries/intermediates.pyindex 304a77639e..9b30013958 100644--- a/invokeai/app/services/shared/database/queries/intermediates.py+++ b/invokeai/app/services/shared/database/queries/intermediates.py@@ -52,7 +52,7 @@ from invokeai.app.services.shared.database.dialect import ()from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, read, writefrom invokeai.app.services.shared.database.queries.session_queue import ACTIVE_QUEUE_STATUSES-from invokeai.app.services.shared.database.schema.boards import board_images+from invokeai.app.services.shared.database.schema.boards import board_images, boardsfrom invokeai.app.services.shared.database.schema.images import imagesfrom invokeai.app.services.shared.database.schema.intermediates import (intermediates_browser_holds,@@ -475,11 +475,30 @@ def _mark_unmeasurable(dialect_name: str) -> Any:return insert_ignore(dialect_name, intermediates_unmeasurable)+_PROJECT_BOARD = boards.alias("project_board")+++def _newest_durable_on_project_board(column: ColumnElement[Any]) -> Any:+ """A column of the newest durable image on one project board, walked newest first through its board's index."""+ return (+ select(column)+ .join(images, images.c.image_name == board_images.c.image_name)+ .where(board_images.c.board_id == _PROJECT_BOARD.c.board_id, images.c.is_intermediate == false())+ .order_by(board_images.c.created_at.desc(), board_images.c.image_name.desc())+ .limit(fixed_limit(1))+ .scalar_subquery()+ )+++# The newest across all of the project's boards, its inbox among them: results can land on every one. Each board's+# newest comes from its own index range, so the cost follows the number of boards rather than the images on them._COVER = (- select(board_images.c.image_name)- .join(images, images.c.image_name == board_images.c.image_name)- .where(board_images.c.board_id == _P.board_id, images.c.is_intermediate == false())- .order_by(board_images.c.created_at.desc(), board_images.c.image_name.desc())+ select(_newest_durable_on_project_board(board_images.c.image_name))+ .where(_PROJECT_BOARD.c.user_id == _P.user_id, _PROJECT_BOARD.c.project_id == _P.project_id)+ .order_by(+ _newest_durable_on_project_board(board_images.c.created_at).desc(),+ _newest_durable_on_project_board(board_images.c.image_name).desc(),+ ).limit(fixed_limit(1)).scalar_subquery())@@ -737,7 +756,7 @@ class IntermediateQueries(QueryModule):@readdef projects(self, conn: Connection, user_id: Optional[str]) -> list[tuple[str, str, str, Optional[str]]]:"""(owner, project, name, cover) of the account's projects (None: everyone's); the cover is the newest image- on the project's board that is not an intermediate."""+ on any of the project's boards that is not an intermediate."""statement = _OWNERS_PROJECTS if user_id is not None else _PROJECTSreturn [(str(r[0]), str(r[1]), str(r[2]), r[3]) for r in conn.execute(statement, {"user_id": user_id}).all()]diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 9fd561d336..8cafb14954 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -498,6 +498,7 @@"updateClient": "This project now requires a newer version of Invoke. Your local changes remain saved in this browser.","supersededElsewhere": "This project was changed on another device. Your local edits continue in the recovered copy — use that one instead.","packing": "Packing the archive…",+ "placingBoardsProgress": "Moving {{completed}} of {{total}} boards into the project…","restoringProgress": "Restoring {{completed}} of {{total}} assets…","tooLarge": "This project file is too large to open.","tooLargeToWrite": "This project is too large to package into a project file.",diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 8d15678f75..0cd0ab9b0b 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -427,6 +427,29 @@ interface BoardCacheRollbackEntry {const isGalleryBoardsData = (value: unknown): value is GalleryBoard[] =>Array.isArray(value) && value.every((board) => typeof board === 'object' && board !== null && 'id' in board);+/** The boards of a project that the account's cached board lists hold, archived ones included where a list has them. */+export const getGalleryProjectBoardsFromCaches = (client: QueryClient, projectId: string): GalleryBoard[] => {+ const boards = new Map<string, GalleryBoard>();++ for (const query of client+ .getQueryCache()+ .findAll({ queryKey: galleryKeys.boardsForAccount(captureAccountScope()) })) {+ const data = query.state.data;++ if (!isGalleryBoardsData(data)) {+ continue;+ }++ for (const board of data) {+ if (board.projectId === projectId && !boards.has(board.id)) {+ boards.set(board.id, board);+ }+ }+ }++ return [...boards.values()];+};+/*** Patches one board across every cached board list and returns a rollback* that restores the prior lists — skipping any list something else hasdiff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex e04a64bb6d..f1f177d4f0 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -31,6 +31,7 @@ export type {export type { GalleryLocatorRequest } from './core/selection';export {getGalleryItemBoardIdsFromCaches,+ getGalleryProjectBoardsFromCaches,getGalleryItemStarredFromCaches,invalidateGallery,invalidateGalleryItems,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsxindex c5e2299080..a016520850 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx@@ -1,12 +1,17 @@import { useDndMonitor, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';import { useCallback, useRef } from 'react';-import { forwardGalleryBoardDrop, isGalleryItemDragData, resolveGallerySemanticSearchDrop } from './galleryDnd';+import {+ forwardGalleryBoardDrop,+ isGalleryItemDragData,+ resolveGalleryBoardMove,+ resolveGallerySemanticSearchDrop,+} from './galleryDnd';import { useGalleryWidget } from './GalleryWidgetContext';-/** Forward board drops and temporarily expose collapsed board targets during item drags. */+/** Forward item and board drops, and temporarily expose collapsed board targets during item drags. */export const GalleryBoardDragMonitor = () => {- const { actions, gallery, itemActions } = useGalleryWidget();+ const { actions, gallery, itemActions, region } = useGalleryWidget();const dragOpenedPanelRef = useRef(false);const restoreDisclosure = useCallback(() => {@@ -32,6 +37,13 @@ export const GalleryBoardDragMonitor = () => {const handleDragEnd = useCallback((event: DragEndEvent) => {+ const boardMove = resolveGalleryBoardMove(event.active.data.current, event.over?.data.current, region);++ if (boardMove) {+ void actions.moveBoard(boardMove.boardId, boardMove.projectId, boardMove.label);+ return;+ }+const semanticDrop = resolveGallerySemanticSearchDrop(event.active.data.current, event.over?.id);if (semanticDrop) {@@ -48,7 +60,7 @@ export const GalleryBoardDragMonitor = () => {});restoreDisclosure();},- [actions, gallery.items, itemActions, restoreDisclosure]+ [actions, gallery.items, itemActions, region, restoreDisclosure]);useDndMonitor({diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex 5847a7c917..8b2ab661ad 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -20,6 +20,7 @@ import {import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { isManagedGalleryBoard } from './galleryBoardGroups';import { useGalleryWidget } from './GalleryWidgetContext';export interface GalleryBoardMenuTarget {@@ -47,10 +48,7 @@ export const GalleryBoardMenu = ({targetRef.current = target;const board = target?.board ?? null;- // An inbox is renamed, archived and deleted through its project; every other real board is the user's to manage.- // The active project's own inbox is also checked by id, because a draft project's inbox can predate the listing.- const isManagedBoard =- board !== null && board.kind === 'board' && !board.isInbox && board.id !== gallery.projectBoardId;+ const isManagedBoard = board !== null && isManagedGalleryBoard(board, gallery.projectBoardId);const positioning = useMemo(() => ({getAnchorRect: () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsxindex c9de0d26fb..be18b231a3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx@@ -1,8 +1,9 @@import type { GalleryItemKey } from '@features/gallery/core/items';import type { GalleryBoard } from '@features/gallery/core/types';-import { Badge, Box } from '@chakra-ui/react';-import { useDndContext, useDroppable } from '@dnd-kit/core';+import { Badge, Box, HStack } from '@chakra-ui/react';+import { useDndContext, useDraggable, useDroppable } from '@dnd-kit/core';+import { CSS } from '@dnd-kit/utilities';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { toGalleryItemKey } from '@features/gallery/core/items';import { IconButton } from '@platform/ui/Button';@@ -10,12 +11,15 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Tooltip } from '@platform/ui/Tooltip';import { MoreVerticalIcon } from 'lucide-react';import { useCallback, useMemo, type MouseEvent, type PointerEvent } from 'react';+import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { BoardCover } from './GalleryBoardCover';import { GalleryBoardRowShell } from './GalleryBoardRowShell';import {acceptsGalleryItemMoves,+ getGalleryBoardDragData,+ getGalleryBoardDragId,getGalleryBoardDropData,getGalleryBoardDropId,isGalleryItemDragData,@@ -25,6 +29,7 @@ import { getBoardCounts } from './galleryStateView';export const GalleryBoardRow = ({accessibleName,board,+ dragScope,isAutoAddTarget = false,isMenuOpen,isSelected,@@ -35,6 +40,11 @@ export const GalleryBoardRow = ({/** What assistive tech calls the row when its visible label alone is ambiguous, such as another project's Inbox. */accessibleName?: string;board: GalleryBoard;+ /**+ * The gallery the row is in, given only where the row can be dragged to another tier: never where the board is+ * managed through its project, and never outside the workbench's drag context.+ */+ dragScope?: string;/** Results without a board of their own land here (the gallery is not following its selection). */isAutoAddTarget?: boolean;/** Its own menu is showing, so the trigger must not fade out from under it. */@@ -56,11 +66,40 @@ export const GalleryBoardRow = ({isGalleryItemDragData(dragData) &&dragData.items.some((ref) => loadedItemBoardIds.get(toGalleryItemKey(ref)) !== board.id);- const { isOver, setNodeRef } = useDroppable({+ const { isOver, setNodeRef: setDropNodeRef } = useDroppable({data: getGalleryBoardDropData(board.id, board.kind),disabled: !canDropItems,id: getGalleryBoardDropId(board.id),});+ const {+ isDragging,+ listeners,+ setNodeRef: setDragNodeRef,+ transform,+ } = useDraggable({+ data: getGalleryBoardDragData(board, dragScope ?? ''),+ disabled: dragScope === undefined,+ id: getGalleryBoardDragId(board.id, dragScope ?? ''),+ });+ const setNodeRef = useCallback(+ (node: HTMLDivElement | null) => {+ setDropNodeRef(node);+ setDragNodeRef(node);+ },+ [setDragNodeRef, setDropNodeRef]+ );+ // Pointer drags only: Enter and Space select the row, and the board menu's Move is the keyboard's way to move it.+ const pointerDragListeners = useMemo(() => {+ if (!listeners) {+ return undefined;+ }++ const { onKeyDown: _keyboardDrag, ...pointer } = listeners;++ return pointer;+ }, [listeners]);+ // Drawn above everything, from where the row was when the drag began: the list's scroll area would clip the row.+ const dragOrigin = isDragging ? (active?.rect.current.initial ?? null) : null;const counts = getBoardCounts(board);const mediaCount = Math.max(0, counts.imageCount + counts.videoCount - counts.assetVideoCount);@@ -77,11 +116,15 @@ export const GalleryBoardRow = ({return;}+ // Not stopped: the touch drag sensor listens for this on the window, to drop a hold the menu interrupts.event.preventDefault();- event.stopPropagation();- onOpenMenu(board, event.clientX, event.clientY);++ // A touch long-press that started a drag means to move the board, not to open its menu under the finger.+ if (!isDragging) {+ onOpenMenu(board, event.clientX, event.clientY);+ }},- [board, onOpenMenu]+ [board, isDragging, onOpenMenu]);const handleActionsClick = useCallback(@@ -130,6 +173,8 @@ export const GalleryBoardRow = ({transition="opacity var(--wb-motion-duration-medium) ease"variant="ghost"onClick={handleActionsClick}+ // Pressing the menu button must not start dragging the row it sits on.+ onMouseDown={stopPropagation}onPointerDown={stopPropagation}onPointerUp={stopPropagation}>@@ -139,10 +184,26 @@ export const GalleryBoardRow = ({[handleActionsClick, isMenuOpen, onOpenMenu, spokenLabel, stopPropagation, t]);+ const dragPreviewStyle = useMemo(+ () =>+ dragOrigin+ ? ({+ height: `${String(dragOrigin.height)}px`,+ left: `${String(dragOrigin.left)}px`,+ top: `${String(dragOrigin.top)}px`,+ // Translate only, as for a dragged item: the full transform would scale it to what it hovers.+ transform: CSS.Translate.toString(transform),+ width: `${String(dragOrigin.width)}px`,+ } as const)+ : null,+ [dragOrigin, transform]+ );+return (<Box// Use outlines to avoid reflow during drag highlighting; the active row gets an inset ring.bg={isOver ? 'accent.muted' : undefined}+ opacity={isDragging ? 0.4 : undefined}outline={isOver ? '2px solid' : canDropItems ? '1px dashed' : undefined}outlineColor={canDropItems ? 'accent.solid' : undefined}// Inset keeps the ring inside the row; the selected row's opaque accent@@ -157,6 +218,7 @@ export const GalleryBoardRow = ({actions={actions}ariaLabel={accessibleName}cover={cover}+ dragListeners={pointerDragListeners}isDropTarget={canDropItems}isSelected={isSelected}label={boardLabel}@@ -177,6 +239,26 @@ export const GalleryBoardRow = ({</Badge></Tooltip></GalleryBoardRowShell>+ {dragPreviewStyle+ ? createPortal(+ <HStack+ aria-hidden="true"+ bg="bg.panel"+ boxShadow="lg"+ gap="2"+ pointerEvents="none"+ position="fixed"+ px="1"+ rounded="sm"+ style={dragPreviewStyle}+ zIndex="1500"+ >+ {cover}+ <MiddleTruncate fontWeight="500" minW="0" text={boardLabel} />+ </HStack>,+ document.body+ )+ : null}</Box>);};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsxindex 43d6eea521..50ced612c7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx@@ -1,3 +1,5 @@+import type { DraggableSyntheticListeners } from '@dnd-kit/core';+import { HStack, Stack, type SystemStyleObject } from '@chakra-ui/react';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Row } from '@platform/ui/Row';@@ -21,6 +23,9 @@ const SELECTED_CONTAINER_CSS: SystemStyleObject = {color: 'accent.contrast',} as const;+/** A row that can be dragged: touch scrolls the list until a hold arms the drag, which the row shows by losing colour. */+const DRAGGABLE_CSS: SystemStyleObject = { '&[data-drag-armed=true]': { filter: 'saturate(0)' }, touchAction: 'pan-y' };+/** Suppress hover fill during compatible drags so it cannot obscure the row's drop tint. */const DROP_TARGET_CONTAINER_CSS: SystemStyleObject = {...ROW_CONTAINER_CSS,@@ -36,6 +41,7 @@ export const GalleryBoardRowShell = ({ariaLabel,children,cover,+ dragListeners,isDropTarget = false,isSelected = false,label,@@ -51,6 +57,8 @@ export const GalleryBoardRowShell = ({/** Trailing metadata rendered inside the row button (dates, counts, badges). */children?: ReactNode;cover: ReactNode;+ /** Lets the whole row, not only its button, be picked up and dragged. */+ dragListeners?: DraggableSyntheticListeners;/** A compatible drag is in flight and this row could receive it. */isDropTarget?: boolean;isSelected?: boolean;@@ -61,13 +69,15 @@ export const GalleryBoardRowShell = ({onContextMenu?: (event: MouseEvent) => void;onSelect: () => void;}) => {- const containerCss = useMemo(- () => (isSelected ? SELECTED_CONTAINER_CSS : isDropTarget ? DROP_TARGET_CONTAINER_CSS : ROW_CONTAINER_CSS),- [isDropTarget, isSelected]- );+ const isDraggable = dragListeners !== undefined;+ const containerCss = useMemo(() => {+ const css = isSelected ? SELECTED_CONTAINER_CSS : isDropTarget ? DROP_TARGET_CONTAINER_CSS : ROW_CONTAINER_CSS;++ return isDraggable ? { ...css, ...DRAGGABLE_CSS } : css;+ }, [isDraggable, isDropTarget, isSelected]);return (- <HStack ref={ref} css={containerCss} gap="0" pe="1" w="full">+ <HStack ref={ref} css={containerCss} gap="0" pe="1" w="full" {...dragListeners}><Row active="none" asChild css={ROW_BUTTON_CSS} flex="1" gap="2" minH="7" minW="0" px="1" py="1"><buttonaria-current={isSelected ? 'true' : undefined}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 ef1ea04805..22ac74d6e2 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@@ -2,17 +2,20 @@import type { GalleryBoard } from '@features/gallery/core/types';import { ChakraProvider } from '@chakra-ui/react';-import { DndContext } from '@dnd-kit/core';+import { DndContext, KeyboardSensor, MouseSensor, pointerWithin, useSensor, useSensors } from '@dnd-kit/core';import { DEFAULT_GALLERY_SETTINGS, type GallerySettings } from '@features/gallery/core/settings';import { system } from '@theme/system';-import { act } from 'react';+import { act, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';import type { GalleryStateView } from './galleryStateView';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';+import { GalleryBoardDragMonitor } from './GalleryBoardDragMonitor';import { GalleryBoardsPanel } from './GalleryBoardsPanel';+import { GalleryDragScope } from './galleryDnd';import { GalleryWidgetContext } from './GalleryWidgetContext';vi.mock('react-i18next', () => ({@@ -41,6 +44,7 @@ vi.mock('react-i18next', () => ({const actions = {createBoard: vi.fn(() => Promise.resolve(true)),+ moveBoard: vi.fn(() => Promise.resolve()),selectBoard: vi.fn(),updateSettings: vi.fn(),};@@ -100,7 +104,24 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const renderPanel = async (gallery: GalleryStateView = createGallery()) => {+/** The workbench's drag context: the shell's mouse activation, pointer collisions, and the gallery's drop monitor. */+const WorkbenchDrag = ({ children }: { children: ReactNode }) => {+ const sensors = useSensors(+ useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),+ useSensor(KeyboardSensor)+ );++ return (+ <DndContext collisionDetection={pointerWithin} sensors={sensors}>+ <GalleryDragScope value>+ {children}+ <GalleryBoardDragMonitor />+ </GalleryDragScope>+ </DndContext>+ );+};++const renderPanel = async (gallery: GalleryStateView = createGallery(), { withDrag = false } = {}) => {const contextValue = {actions,boardsState: { error: null, isRetrying: false, retry: () => Promise.resolve(), status: 'ready' },@@ -109,15 +130,22 @@ const renderPanel = async (gallery: GalleryStateView = createGallery()) => {projectId: 'p1',projectName: 'Mahogany House',projectNames: new Map([['p2', 'Harbor Tower']]),+ region: 'left',} as unknown as GalleryWidgetContextValue;await act(() =>root?.render(<ChakraProvider value={system}><GalleryWidgetContext value={contextValue}>- <DndContext>- <GalleryBoardsPanel />- </DndContext>+ {withDrag ? (+ <WorkbenchDrag>+ <GalleryBoardsPanel />+ </WorkbenchDrag>+ ) : (+ <DndContext>+ <GalleryBoardsPanel />+ </DndContext>+ )}</GalleryWidgetContext></ChakraProvider>)@@ -343,14 +371,96 @@ describe('GalleryBoardsPanel', () => {expect((await getCreateDialog()).querySelector('h2')?.textContent).toBe('Create board in Mahogany House');});- it('counts the boards made in each tier, not its fixed row', async () => {+ it('counts the boards in each tier, the inbox included, but not Uncategorized', async () => {await renderPanel();const counts = Array.from(host?.querySelectorAll<HTMLElement>('[data-scope="collapsible"][data-part="trigger"]') ?? []).map((trigger) => trigger.textContent);- expect(counts.slice(0, 2)).toEqual(['Mahogany House1', 'Library2']);+ expect(counts.slice(0, 2)).toEqual(['Mahogany House2', 'Library2']);+ });++ describe('dragging a board', () => {+ const row = (label: string) =>+ getBoardRows().find((button) => button.textContent?.startsWith(label))!.parentElement as HTMLElement;+ const heading = (label: string) =>+ [...(host?.querySelectorAll<HTMLElement>('[data-part="trigger"], [role="heading"]') ?? [])].find((element) =>+ element.textContent?.startsWith(label)+ )!;+ const settle = () =>+ new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 30);+ });+ /**+ * A pointer that travels, as a hand does: the tiers start taking boards once the drag has begun, and are measured+ * on the moves after it. Outside act, as in the shell: dnd-kit settles the drop in effects act would hold back.+ */+ const drag = async (source: HTMLElement, target: HTMLElement) => {+ const center = (element: HTMLElement) => {+ const rect = element.getBoundingClientRect();++ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };+ };+ const from = center(source);+ const to = center(target);+ const mouse = (type: string, at: { x: number; y: number }, element: EventTarget = document) =>+ element.dispatchEvent(new MouseEvent(type, { bubbles: true, button: 0, clientX: at.x, clientY: at.y }));++ mouse('mousedown', from, source);+ for (const progress of [0.25, 0.5, 0.75, 1, 1]) {+ mouse('mousemove', { x: from.x + (to.x - from.x) * progress, y: from.y + (to.y - from.y) * progress });+ await settle();+ }+ mouse('mouseup', to);+ await settle();+ };++ it('moves it to the project or Library it is dropped on, anywhere on that tier', async () => {+ await renderPanel(createGallery({ showOtherProjectBoards: true }), { withDrag: true });++ await drag(row('dogs'), heading('Harbor Tower'));+ expect(actions.moveBoard).toHaveBeenLastCalledWith('dogs', 'p2', 'Harbor Tower');++ await drag(row('Stripes'), row('Façades'));+ expect(actions.moveBoard).toHaveBeenLastCalledWith('theirs-member', 'p1', 'Mahogany House');++ await drag(row('Façades'), heading('Library'));+ expect(actions.moveBoard).toHaveBeenLastCalledWith('mine-member', null, 'Library');+ expect(actions.moveBoard).toHaveBeenCalledTimes(3);+ });++ it('moves nothing dropped on its own tier, and never drags an inbox, which moves with its project', async () => {+ await renderPanel(createGallery({ showOtherProjectBoards: true }), { withDrag: true });++ await drag(row('dogs'), row('Cats'));+ await drag(row('Inbox'), heading('Library'));+ // Pressing the row's menu button and moving away is no drag either.+ await drag(row('Façades').querySelector<HTMLElement>('.board-row-actions')!, heading('Library'));++ expect(actions.moveBoard).not.toHaveBeenCalled();+ });++ it('takes a drop on a collapsed tier, by its heading', async () => {+ await renderPanel(createGallery({ collapsedBoardSections: ['library'] }), { withDrag: true });++ await drag(row('Façades'), heading('Library'));++ expect(actions.moveBoard).toHaveBeenCalledExactlyOnceWith('mine-member', null, 'Library');+ });++ it('selects a draggable board from the keyboard rather than starting a drag', async () => {+ await renderPanel(createGallery(), { withDrag: true });+ const button = getBoardRows().find((candidate) => candidate.textContent?.startsWith('Façades'))!;++ button.focus();+ await userEvent.keyboard('{Enter}');+ await userEvent.keyboard(' ');++ expect(actions.selectBoard).toHaveBeenCalledTimes(2);+ expect(actions.selectBoard).toHaveBeenLastCalledWith('mine-member');+ expect(actions.moveBoard).not.toHaveBeenCalled();+ });});it('names another project inbox for assistive tech while the visible row says Inbox', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsxindex 754b95f196..28d3df3c4e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx@@ -2,26 +2,30 @@ import type { GalleryItemKey } from '@features/gallery/core/items';import type { GalleryBoardSectionId } from '@features/gallery/core/settings';import type { GalleryBoard } from '@features/gallery/core/types';-import { HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';-import { getGalleryProjectGroupLabel } from '@features/gallery/core/boardLabels';+import { Box, HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';+import { useDndContext, useDroppable } from '@dnd-kit/core';import { toGalleryItemKey } from '@features/gallery/core/items';import { usePreservedScrollOffset } from '@platform/react/usePreservedScrollOffset';import { IconButton } from '@platform/ui/Button';import { RenameDialog } from '@platform/ui/RenameDialog';import { Tooltip } from '@platform/ui/Tooltip';import { PlusIcon } from 'lucide-react';-import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';+import { Fragment, use, useCallback, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import type { GalleryBoardProjectGroup } from './galleryBoardGroups';-import { BoardCoverIcon } from './GalleryBoardCover';import { GalleryBoardFilters } from './GalleryBoardFilters';-import { getGalleryBoardGroups } from './galleryBoardGroups';+import { getGalleryBoardGroups, isManagedGalleryBoard } from './galleryBoardGroups';import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenu';import { GalleryBoardRow } from './GalleryBoardRow';import { GalleryBoardRowShell } from './GalleryBoardRowShell';import { GalleryBoardSection } from './GalleryBoardSection';+import {+ acceptsGalleryBoardMove,+ GalleryDragScope,+ getGalleryBoardTierDropData,+ getGalleryBoardTierDropId,+} from './galleryDnd';import { focusVisibleOperable, GalleryLoadNotice } from './GalleryLoadError';import { useGalleryWidget } from './GalleryWidgetContext';@@ -33,7 +37,9 @@ type CreateTier = 'library' | 'project';export const GalleryBoardsPanel = () => {const { t } = useTranslation();- const { actions, boardsState, gallery, projectId, projectName, projectNames } = useGalleryWidget();+ const { actions, boardsState, gallery, projectId, projectName, projectNames, region } = useGalleryWidget();+ // Boards move between tiers by dragging only inside the workbench's drag context; elsewhere, by their menu.+ const canDragBoards = use(GalleryDragScope);const [searchTerm, setSearchTerm] = useState('');// The tier whose "+" asked for a name; the dialog it opens creates there.const [createDialogTier, setCreateDialogTier] = useState<CreateTier | null>(null);@@ -52,6 +58,7 @@ export const GalleryBoardsPanel = () => {boards: gallery.boards,projectBoardId: gallery.projectBoardId,projectId,+ projectNames,searchTerm,showArchived: showArchivedBoards,showDates: showDateBoards,@@ -62,6 +69,7 @@ export const GalleryBoardsPanel = () => {gallery.boards,gallery.projectBoardId,projectId,+ projectNames,searchTerm,showArchivedBoards,showDateBoards,@@ -168,6 +176,7 @@ export const GalleryBoardsPanel = () => {key={board.id}accessibleName={accessibleName}board={board}+ dragScope={canDragBoards && isManagedGalleryBoard(board, gallery.projectBoardId) ? region : undefined}isAutoAddTarget={board.id === gallery.settings.autoAddBoardId}isMenuOpen={boardMenuTarget?.board.id === board.id}isSelected={board.id === gallery.selectedBoardId}@@ -186,6 +195,15 @@ export const GalleryBoardsPanel = () => {onSelect={tier === 'project' ? createProjectBoardFromSearch : createLibraryBoardFromSearch}/>) : null;+ // A dragged board moves to whichever tier it is dropped on.+ const renderDropTier = (tierProjectId: string | null, label: string, content: ReactNode) =>+ canDragBoards ? (+ <GalleryBoardTierDropZone dropScope={region} label={label} projectId={tierProjectId}>+ {content}+ </GalleryBoardTierDropZone>+ ) : (+ content+ );// One line, shown while a tier holds only its fixed row, so the two tiers explain themselves once.const renderHint = (text: string) =>trimmedSearchTerm ? null : (@@ -193,14 +211,11 @@ export const GalleryBoardsPanel = () => {{text}</Text>);- const otherProjectLabel = (group: GalleryBoardProjectGroup) =>- getGalleryProjectGroupLabel(group.projectId, group.boards, projectNames, t);-const projectBoards = isBoardListUnavailable ? [] : groups.projectBoards;const libraryBoards = isBoardListUnavailable ? [] : groups.libraryBoards;- // Each tier counts the boards made in it; its fixed row (Inbox, Uncategorized) is not one.- const countCreated = (boards: GalleryBoard[]) =>- boards.filter((board) => board.kind === 'board' && !board.isInbox).length;+ // Each tier counts its boards, the project's inbox among them; Uncategorized is where media on no board shows, not+ // a board.+ const countBoards = (boards: GalleryBoard[]) => boards.filter((board) => board.kind === 'board').length;return (<Stack flex="1" gap="1" minH="0" minW="0">@@ -208,47 +223,57 @@ export const GalleryBoardsPanel = () => {<ScrollArea.Root flex="1" minH="0" variant="hover" w="full"><ScrollArea.Viewport ref={boardsViewportRef} h="full" w="full"><ScrollArea.Content {...SCROLL_CONTENT_PROPS}>- <GalleryBoardSection- action={addProjectBoardAction}- count={countCreated(projectBoards)}- isOpen={isSectionOpen('project')}- label={projectName}- sectionId="project"- onToggle={handleToggleSection}- >- {boardsState.status === 'error' || boardsState.status === 'stale-error' ? (- <GalleryLoadNotice- message={t(- isBoardListUnavailable ? 'widgets.gallery.boardsLoadFailed' : 'widgets.gallery.boardsRefreshFailed'- )}- pe="1"- ps="2"- read={boardsState}- retryLabel={t('widgets.gallery.retryLoadingBoards')}- onFocusLost={focusBoardList}- />- ) : null}- {projectBoards.map((board) => renderRow(board))}- {renderCreateRow('project')}- {isBoardListSettled && projectBoards.every((board) => board.isInbox)- ? renderHint(t('widgets.gallery.projectBoardsHint'))- : null}- </GalleryBoardSection>+ {renderDropTier(+ projectId,+ projectName,+ <GalleryBoardSection+ action={addProjectBoardAction}+ count={countBoards(projectBoards)}+ isOpen={isSectionOpen('project')}+ label={projectName}+ sectionId="project"+ onToggle={handleToggleSection}+ >+ {boardsState.status === 'error' || boardsState.status === 'stale-error' ? (+ <GalleryLoadNotice+ message={t(+ isBoardListUnavailable+ ? 'widgets.gallery.boardsLoadFailed'+ : 'widgets.gallery.boardsRefreshFailed'+ )}+ pe="1"+ ps="2"+ read={boardsState}+ retryLabel={t('widgets.gallery.retryLoadingBoards')}+ onFocusLost={focusBoardList}+ />+ ) : null}+ {projectBoards.map((board) => renderRow(board))}+ {renderCreateRow('project')}+ {isBoardListSettled && projectBoards.every((board) => board.isInbox)+ ? renderHint(t('widgets.gallery.projectBoardsHint'))+ : null}+ </GalleryBoardSection>+ )}- <GalleryBoardSection- action={addLibraryBoardAction}- count={countCreated(libraryBoards)}- isOpen={isSectionOpen('library')}- label={t('widgets.gallery.boardGroups.library')}- sectionId="library"- onToggle={handleToggleSection}- >- {libraryBoards.map((board) => renderRow(board))}- {renderCreateRow('library')}- {isBoardListSettled && libraryBoards.every((board) => board.kind === 'uncategorized')- ? renderHint(t('widgets.gallery.libraryBoardsHint'))- : null}- </GalleryBoardSection>+ {renderDropTier(+ null,+ t('widgets.gallery.boardGroups.library'),+ <GalleryBoardSection+ action={addLibraryBoardAction}+ count={countBoards(libraryBoards)}+ isOpen={isSectionOpen('library')}+ label={t('widgets.gallery.boardGroups.library')}+ sectionId="library"+ onToggle={handleToggleSection}+ >+ {libraryBoards.map((board) => renderRow(board))}+ {renderCreateRow('library')}+ {isBoardListSettled && libraryBoards.every((board) => board.kind === 'uncategorized')+ ? renderHint(t('widgets.gallery.libraryBoardsHint'))+ : null}+ </GalleryBoardSection>+ )}{!isBoardListUnavailable && groups.otherProjects.length > 0 ? (<GalleryBoardSection@@ -259,28 +284,34 @@ export const GalleryBoardsPanel = () => {onToggle={handleToggleSection}>{groups.otherProjects.map((group) => (- <Stack key={group.projectId} gap="0.5">- <Text- color="fg.muted"- fontSize="xs"- fontWeight="600"- pe="2"- ps="2"- pt="1"- role="heading"- aria-level={4}- truncate- >- {otherProjectLabel(group)}- </Text>- {group.boards.map((board) =>- // Every other project's inbox is called "Inbox"; assistive tech needs the project in the name.- renderRow(- board,- board.isInbox ? t('widgets.gallery.inboxOf', { project: otherProjectLabel(group) }) : undefined- )+ <Fragment key={group.projectId}>+ {renderDropTier(+ group.projectId,+ group.label,+ <Stack gap="0.5">+ <Text+ color="fg.muted"+ fontSize="xs"+ fontWeight="600"+ pe="2"+ ps="2"+ pt="1"+ role="heading"+ aria-level={4}+ truncate+ >+ {group.label}+ </Text>+ {group.boards.map((board) =>+ // Every other project's inbox is called "Inbox"; assistive tech needs the project in the name.+ renderRow(+ board,+ board.isInbox ? t('widgets.gallery.inboxOf', { project: group.label }) : undefined+ )+ )}+ </Stack>)}- </Stack>+ </Fragment>))}</GalleryBoardSection>) : null}@@ -345,6 +376,48 @@ export const GalleryBoardsPanel = () => {);};+/**+ * A project's boards, or the Library's, as the place a dragged board lands: anywhere on them, heading and rows alike,+ * so a collapsed section still takes one. It marks itself only while one of this gallery's boards from elsewhere is+ * being dragged.+ */+const GalleryBoardTierDropZone = ({+ children,+ dropScope,+ label,+ projectId,+}: {+ children: ReactNode;+ /** The gallery it is in; another gallery's dragged boards neither land on it nor see it highlighted. */+ dropScope: string;+ /** What the move's notice calls the destination. */+ label: string;+ projectId: string | null;+}) => {+ const { active } = useDndContext();+ const canDrop = acceptsGalleryBoardMove(active?.data.current, projectId, dropScope);+ const { isOver, setNodeRef } = useDroppable({+ data: getGalleryBoardTierDropData(projectId, label, dropScope),+ disabled: !canDrop,+ id: getGalleryBoardTierDropId(projectId, dropScope),+ });++ return (+ <Box+ ref={setNodeRef}+ // Outlines, as on a row taking items, so the highlight cannot reflow the list under the pointer.+ bg={canDrop && isOver ? 'accent.muted' : undefined}+ outline={canDrop ? (isOver ? '2px solid' : '1px dashed') : undefined}+ outlineColor={canDrop ? 'accent.solid' : undefined}+ outlineOffset="-2px"+ rounded="sm"+ transition="background var(--wb-motion-duration-fast) ease"+ >+ {children}+ </Box>+ );+};+const AddBoardButton = ({ label, onClick }: { label: string; onClick: () => void }): ReactNode => (<Tooltip content={label}><IconButton aria-haspopup="dialog" aria-label={label} color="fg.muted" size="sm" variant="ghost" onClick={onClick}>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsxindex 68226db338..9b19883e17 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx@@ -1,7 +1,7 @@import { useDndContext } from '@dnd-kit/core';import { useEffect } from 'react';-import { isGalleryItemDragData } from './galleryDnd';+import { isGalleryBoardDragData, isGalleryItemDragData } from './galleryDnd';/*** Mount once inside DndContext. The body marker enables global drag cursors that override element-specific button@@ -9,7 +9,7 @@ import { isGalleryItemDragData } from './galleryDnd';*/export const GalleryDragCursor = () => {const { active } = useDndContext();- const isGalleryDrag = isGalleryItemDragData(active?.data.current);+ const isGalleryDrag = isGalleryItemDragData(active?.data.current) || isGalleryBoardDragData(active?.data.current);useEffect(() => {if (!isGalleryDrag) {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex 94f2339835..66ed2d6ff4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -166,7 +166,11 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg[data.filter, queryClient, starredStrip.items]);const itemActionContextRef = useRef<GalleryItemActionContext | null>(null);- const galleryLocationRef = useRef({ galleryView, selectedBoardId });+ const galleryLocationRef = useRef({+ autoAddBoardId: gallery.settings.autoAddBoardId,+ galleryView,+ selectedBoardId,+ });// In-flight deletion must read the latest rendered filter and selection without an effect-sized stale window.// eslint-disable-next-line react/refs@@ -179,7 +183,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg};// Capture upload destination at launch; judge completion visibility against the latest rendered board and view.// eslint-disable-next-line react/refs- galleryLocationRef.current = { galleryView, selectedBoardId };+ galleryLocationRef.current = { autoAddBoardId: gallery.settings.autoAddBoardId, galleryView, selectedBoardId };const getItemActionContext = useCallback(() => itemActionContextRef.current, []);const getCurrentGalleryLocation = useCallback(() => galleryLocationRef.current, []);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.tsindex 248ad7890b..4dcfb1e16f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts@@ -37,6 +37,7 @@ const groupsOf = (overrides: Partial<Parameters<typeof getGalleryBoardGroups>[0]boards: ALL,projectBoardId: 'mine',projectId: 'project-1',+ projectNames: new Map(),searchTerm: '',showArchived: true,showDates: true,@@ -77,6 +78,18 @@ describe('getGalleryBoardGroups', () => {expect(groupsOf({ showOtherProjects: false }).otherProjects).toEqual([]);});+ it('names and orders other projects by their live names, whatever their inboxes were listed as', () => {+ // The listing still has Zebra's inbox under its old name; the project was renamed to "Aardvark" since.+ const projectNames = new Map([['project-z', 'Aardvark study']]);++ expect(groupsOf({ projectNames }).otherProjects.map((group) => [group.projectId, group.label])).toEqual([+ ['project-z', 'Aardvark study'],+ ['project-a', 'Apple ads'],+ ]);+ // A search that hides the inbox keeps the group's name and place.+ expect(groupsOf({ searchTerm: 'stripes' }).otherProjects.map((group) => group.label)).toEqual(['Zebra study']);+ });+it('keeps other projects archived boards out of the archived section while they are hidden', () => {const otherArchived = createBoard({ archived: true, id: 'their-old', name: 'Theirs', projectId: 'project-z' });diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.tsindex b8031c2669..bb92654c96 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts@@ -1,10 +1,17 @@import type { GalleryBoard } from '@features/gallery/core/types';-import { getGalleryBoardLabel, inboxFirst, type GalleryBoardTranslate } from '@features/gallery/core/boardLabels';+import {+ getGalleryBoardLabel,+ getGalleryProjectGroupLabel,+ inboxFirst,+ type GalleryBoardTranslate,+} from '@features/gallery/core/boardLabels';/** One other project's boards: its inbox first, named after the project, then the rest. */export interface GalleryBoardProjectGroup {boards: GalleryBoard[];+ /** The project's name as its heading shows it, which is also the order the groups take. */+ label: string;projectId: string;}@@ -18,12 +25,19 @@ export interface GalleryBoardGroups {hasAnyMatch: boolean;/** Uncategorized first, then the boards in no project. */libraryBoards: GalleryBoard[];- /** Other projects in name order; empty unless other projects are shown. */+ /** Other projects in label order; empty unless other projects are shown. */otherProjects: GalleryBoardProjectGroup[];/** The open project's inbox first, then its other boards. */projectBoards: GalleryBoard[];}+/**+ * A board its owner renames, moves, archives and deletes directly. An inbox is managed through its project; the open+ * project's is also known by id, because a draft project's inbox can predate the listing.+ */+export const isManagedGalleryBoard = (board: GalleryBoard, projectBoardId: string | null): boolean =>+ board.kind === 'board' && !board.isInbox && board.id !== projectBoardId;+/*** Apply visibility filters while grouping; GET /boards/ cannot filter by project and returns the complete list.* Membership is the board's own `projectId`; `projectBoardId` also claims the open project's inbox, which a draft@@ -33,6 +47,7 @@ export const getGalleryBoardGroups = ({boards,projectBoardId,projectId,+ projectNames,searchTerm,showArchived,showDates,@@ -43,6 +58,8 @@ export const getGalleryBoardGroups = ({projectBoardId: string | null;/** The open project; null where there is none, in which case every project is "other". */projectId: string | null;+ /** The account's project names by id, which name other projects ahead of the names their inboxes were listed with. */+ projectNames: ReadonlyMap<string, string>;searchTerm: string;showArchived: boolean;showDates: boolean;@@ -80,11 +97,20 @@ export const getGalleryBoardGroups = ({}}for (const [otherProjectId, projectGroupBoards] of byProject) {- otherProjects.push({ boards: inboxFirst(projectGroupBoards), projectId: otherProjectId });+ otherProjects.push({+ boards: inboxFirst(projectGroupBoards),+ // Labelled from every board, not the ones the search kept: a search that hides the inbox must not cost the+ // group the name its inbox would give it.+ label: getGalleryProjectGroupLabel(+ otherProjectId,+ boards.filter((board) => board.projectId === otherProjectId),+ projectNames,+ t+ ),+ projectId: otherProjectId,+ });}- // The inbox carries the project's name, so projects sort by it where one is listed.- const nameOf = (group: GalleryBoardProjectGroup) => group.boards.find((board) => board.isInbox)?.name ?? '';- otherProjects.sort((left, right) => nameOf(left).localeCompare(nameOf(right)));+ otherProjects.sort((left, right) => left.label.localeCompare(right.label));}const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.tsindex 1182c2dfcb..20790dce30 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts@@ -5,13 +5,16 @@ import { describe, expect, it, vi } from 'vitest';import {forwardGalleryBoardDrop,GALLERY_SEMANTIC_SEARCH_DROP_ID,+ getGalleryBoardDragData,getGalleryBoardDropData,+ getGalleryBoardTierDropData,getGalleryItemDragData,getGalleryItemDragId,isGalleryBoardDropData,isGalleryImageDragData,isGalleryItemDragData,resolveGalleryBoardDrop,+ resolveGalleryBoardMove,resolveGallerySemanticSearchDrop,} from './galleryDnd';@@ -237,3 +240,26 @@ describe('resolveGallerySemanticSearchDrop', () => {expect(resolveGallerySemanticSearchDrop({ kind: 'other' }, GALLERY_SEMANTIC_SEARCH_DROP_ID)).toBe(null);});});++describe('resolveGalleryBoardMove', () => {+ const dogs = getGalleryBoardDragData({ id: 'dogs', projectId: null }, 'left');++ it('moves a board dropped on another tier of the gallery it was picked up in', () => {+ expect(resolveGalleryBoardMove(dogs, getGalleryBoardTierDropData('p2', 'Harbor Tower', 'left'), 'left')).toEqual({+ boardId: 'dogs',+ label: 'Harbor Tower',+ projectId: 'p2',+ });+ expect(resolveGalleryBoardMove(dogs, getGalleryBoardTierDropData(null, 'Library', 'left'), 'left')).toBeNull();+ });++ // Every mounted gallery hears every drop; only the one the drag began and ended in acts on it.+ it('leaves a drop to the gallery it belongs to', () => {+ const tier = getGalleryBoardTierDropData('p2', 'Harbor Tower', 'left');++ expect(resolveGalleryBoardMove(dogs, tier, 'right')).toBeNull();+ expect(+ resolveGalleryBoardMove(dogs, getGalleryBoardTierDropData('p2', 'Harbor Tower', 'right'), 'right')+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex cf9cf8bd34..af1ba41f10 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -1,5 +1,5 @@import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/core/items';-import type { GalleryBoardKind } from '@features/gallery/core/types';+import type { GalleryBoard, GalleryBoardKind } from '@features/gallery/core/types';import { useDndContext, useDroppable, type UseDroppableArguments } from '@dnd-kit/core';import { toGalleryItemKey } from '@features/gallery/core/items';@@ -50,6 +50,81 @@ export const GalleryDragScope = createContext(false);export const getGalleryBoardDropId = (boardId: string): string => `gallery-board:${boardId}`;+/**+ * A board row on its way to another project or the Library. Each gallery resolves only its own boards' drags onto its+ * own tiers: the shell's one drag context reports every drop to every mounted gallery.+ */+export interface GalleryBoardDragData {+ boardId: string;+ kind: 'gallery-board-drag';+ /** Where it is now; null is the Library. */+ projectId: string | null;+ /** The gallery it was picked up in. */+ scope: string;+}++/** A project's boards, or the Library's (null): dropping a board anywhere on them moves it there. */+export interface GalleryBoardTierDropData {+ kind: 'gallery-board-tier';+ label: string;+ projectId: string | null;+ scope: string;+}++export interface GalleryBoardMove {+ boardId: string;+ label: string;+ projectId: string | null;+}++export const getGalleryBoardDragId = (boardId: string, scope: string): string =>+ `gallery-board-drag#${scope}:${boardId}`;++export const getGalleryBoardDragData = (+ board: Pick<GalleryBoard, 'id' | 'projectId'>,+ scope: string+): GalleryBoardDragData => ({ boardId: board.id, kind: 'gallery-board-drag', projectId: board.projectId, scope });++export const getGalleryBoardTierDropId = (projectId: string | null, scope: string): string =>+ `gallery-board-tier#${scope}:${projectId ?? 'library'}`;++export const getGalleryBoardTierDropData = (+ projectId: string | null,+ label: string,+ scope: string+): GalleryBoardTierDropData => ({ kind: 'gallery-board-tier', label, projectId, scope });++export const isGalleryBoardDragData = (value: unknown): value is GalleryBoardDragData =>+ isRecord(value) &&+ value.kind === 'gallery-board-drag' &&+ typeof value.boardId === 'string' &&+ typeof value.scope === 'string' &&+ (value.projectId === null || typeof value.projectId === 'string');++const isGalleryBoardTierDropData = (value: unknown): value is GalleryBoardTierDropData =>+ isRecord(value) &&+ value.kind === 'gallery-board-tier' &&+ typeof value.label === 'string' &&+ typeof value.scope === 'string' &&+ (value.projectId === null || typeof value.projectId === 'string');++/** Whether a dragged board would move by landing on the tier: it came from this gallery and is not there already. */+export const acceptsGalleryBoardMove = (activeData: unknown, projectId: string | null, scope: string): boolean =>+ isGalleryBoardDragData(activeData) && activeData.scope === scope && activeData.projectId !== projectId;++/** The move a board drop in this gallery asks for, or null when it was no board of its own or stayed in its tier. */+export const resolveGalleryBoardMove = (+ activeData: unknown,+ overData: unknown,+ scope: string+): GalleryBoardMove | null =>+ isGalleryBoardTierDropData(overData) &&+ overData.scope === scope &&+ acceptsGalleryBoardMove(activeData, overData.projectId, scope) &&+ isGalleryBoardDragData(activeData)+ ? { boardId: activeData.boardId, label: overData.label, projectId: overData.projectId }+ : null;+/** Real boards and Uncategorized hold items; date boards are views and accept no moves. */export const acceptsGalleryItemMoves = (boardKind: GalleryBoardKind): boolean =>boardKind === 'board' || boardKind === 'uncategorized';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxindex f2ef5c7769..311276ba5e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -3,7 +3,7 @@ import type { GallerySparseListing } from '@features/gallery/ui/useGalleryData';import type { KeyboardEvent, RefObject } from 'react';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { getGalleryProjectGroupLabel, getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { getGalleryUploadAccept, toGalleryItemKey } from '@features/gallery/core/items';import { GALLERY_PAGE_SIZE, galleryItemsPageOptions } from '@features/gallery/data/queries';import { BoardCover, BoardCoverIcon } from '@features/gallery/ui/GalleryBoardCover';@@ -250,6 +250,7 @@ export const GalleryPickerView = ({boards: data.boards,projectBoardId: getGalleryProjectBoardId(galleryValues),projectId,+ projectNames: new Map((projects ?? []).map((project) => [project.id, project.name])),searchTerm: scope.searchTerm,showArchived: settings.showArchivedBoards,showDates: settings.showDateBoards,@@ -257,15 +258,13 @@ export const GalleryPickerView = ({showOtherProjects: true,t,});- const projectNames = new Map((projects ?? []).map((project) => [project.id, project.name]));-return [{ boards: groups.projectBoards, id: 'project', label: projectName },{ boards: groups.libraryBoards, id: 'library', label: t('widgets.gallery.boardGroups.library') },...groups.otherProjects.map((group) => ({boards: group.boards,id: `project:${group.projectId}`,- label: getGalleryProjectGroupLabel(group.projectId, group.boards, projectNames, t),+ label: group.label,})),{ boards: groups.dateBoards, id: 'dates', label: t('widgets.gallery.boardGroups.byDate') },{ boards: groups.archivedBoards, id: 'archived', label: t('common.archived') },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 976a6ff69e..b5b5e3cde5 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@@ -1,5 +1,7 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { GalleryUiAdapter } from '@features/gallery/react';+import { GALLERY_AUTO_ADD_FOLLOW, getGallerySettings } from '@features/gallery/core/settings';import { GalleryUiProvider } from '@features/gallery/react';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -87,6 +89,7 @@ let root: Root | null = null;const actionsRef = createRef<GalleryActions>();const reconcileDeletedBoardOutcome = vi.fn();const selectBoard = vi.fn();+const updateSettings = vi.fn();const selectItem = vi.fn();const setItemMultiSelection = vi.fn();const patchGalleryValues = vi.fn();@@ -101,11 +104,12 @@ const Probe = ({ref: Ref<GalleryActions>;selectedBoardId: string;}) => {- const currentGalleryLocationRef = useRef({ galleryView, selectedBoardId });+ const { autoAddBoardId } = getGallerySettings(galleryValues);+ const currentGalleryLocationRef = useRef({ autoAddBoardId, galleryView, selectedBoardId });// Match GalleryWidgetView's render-assigned live-read port.// eslint-disable-next-line react/refs- currentGalleryLocationRef.current = { galleryView, selectedBoardId };+ currentGalleryLocationRef.current = { autoAddBoardId, galleryView, selectedBoardId };const getCurrentGalleryLocation = useCallback(() => currentGalleryLocationRef.current, []);const actions = useGalleryActions({boards: [@@ -171,7 +175,7 @@ const adapter: GalleryUiAdapter = {clearSearch: noop,setView: noop,toggleItemSelection: noop,- updateSettings: noop,+ updateSettings,},galleryValues: {},generateValues: {},@@ -195,11 +199,13 @@ const adapter: GalleryUiAdapter = {let selectedBoardId = 'board-1';let galleryView: 'images' | 'assets' = 'images';+let galleryValues: Record<string, unknown> = {};+const renderProbe = async () => {await act(() => {root?.render(<QueryClientProvider client={new QueryClient()}>- <GalleryUiProvider adapter={adapter}>+ <GalleryUiProvider adapter={{ ...adapter, galleryValues }}><Probe galleryView={galleryView} ref={actionsRef} selectedBoardId={selectedBoardId} /></GalleryUiProvider></QueryClientProvider>@@ -212,6 +218,7 @@ beforeEach(async () => {accountLifecycle.activate('user-a');selectedBoardId = 'board-1';galleryView = 'images';+ galleryValues = {};host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -308,6 +315,15 @@ describe('optimistic board updates', () => {it('makes the project exist on the server before creating or moving a board into it, never for the Library', async () => {mocks.createGalleryBoard.mockResolvedValue({ id: 'new', name: 'New' });mocks.updateGalleryBoard.mockResolvedValue(undefined);+ // Each ensure is held until the test lets it finish, so a request sent without waiting for it shows.+ let finishEnsure: () => void = () => undefined;+ const holdNextEnsure = () =>+ mocks.ensureProjectOnServer.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishEnsure = resolve;+ })+ );await act(async () => {await actionsRef.current?.createBoard('New', null);@@ -315,19 +331,104 @@ describe('optimistic board updates', () => {});expect(mocks.ensureProjectOnServer).not.toHaveBeenCalled();- await act(async () => {- await expect(actionsRef.current?.createBoard('New', 'p1')).resolves.toBe(true);+ let create!: Promise<boolean | undefined>;+ holdNextEnsure();+ await act(() => {+ create = actionsRef.current!.createBoard('New', 'p1');});expect(mocks.ensureProjectOnServer).toHaveBeenCalledOnce();- expect(mocks.ensureProjectOnServer.mock.invocationCallOrder[0]).toBeLessThan(- mocks.createGalleryBoard.mock.invocationCallOrder[1] ?? 0- );+ expect(mocks.createGalleryBoard).toHaveBeenCalledOnce();+ await act(async () => {+ finishEnsure();+ await expect(create).resolves.toBe(true);+ });expect(mocks.createGalleryBoard).toHaveBeenLastCalledWith('New', 'p1', expect.anything());- await act(async () => {- await actionsRef.current?.moveBoard('board-1', 'p1', 'Project');+ let move!: Promise<void>;+ holdNextEnsure();+ await act(() => {+ move = actionsRef.current!.moveBoard('board-1', 'p1', 'Project');});expect(mocks.ensureProjectOnServer).toHaveBeenCalledTimes(2);+ expect(mocks.updateGalleryBoard).toHaveBeenCalledOnce();+ await act(async () => {+ finishEnsure();+ await move;+ });+ expect(mocks.updateGalleryBoard).toHaveBeenLastCalledWith('board-1', { projectId: 'p1' }, expect.anything());+ });++ it('steps the selection and auto-add off a board moved into a project the panel hides, and back on failure', async () => {+ galleryValues = { autoAddBoardId: 'board-1' };+ await renderProbe();+ let rejectUpdate: (error: Error) => void = () => undefined;+ mocks.updateGalleryBoard.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectUpdate = reject;+ })+ );++ let move!: Promise<void>;+ await act(() => {+ move = actionsRef.current!.moveBoard('board-1', 'other-project', 'Other');+ });++ expect(selectBoard).toHaveBeenCalledExactlyOnceWith('none');+ expect(updateSettings).toHaveBeenCalledExactlyOnceWith({ autoAddBoardId: GALLERY_AUTO_ADD_FOLLOW });++ // Reflect both optimistic steps in the live gallery the failure path reads.+ selectedBoardId = 'none';+ galleryValues = { autoAddBoardId: GALLERY_AUTO_ADD_FOLLOW };+ await renderProbe();+ rejectUpdate(new Error('move failed'));+ await act(() => move);++ expect(selectBoard).toHaveBeenLastCalledWith('board-1');+ expect(updateSettings).toHaveBeenLastCalledWith({ autoAddBoardId: 'board-1' });+ });++ it('leaves choices the user made while a failing move was in flight', async () => {+ galleryValues = { autoAddBoardId: 'board-1' };+ await renderProbe();+ let rejectUpdate: (error: Error) => void = () => undefined;+ mocks.updateGalleryBoard.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectUpdate = reject;+ })+ );++ let move!: Promise<void>;+ await act(() => {+ move = actionsRef.current!.moveBoard('board-1', 'other-project', 'Other');+ });++ // Another board selected, and another made the auto-add target, before the failure arrived.+ selectedBoardId = 'board-2';+ galleryValues = { autoAddBoardId: 'board-3' };+ await renderProbe();+ rejectUpdate(new Error('move failed'));+ await act(() => move);++ expect(selectBoard).toHaveBeenCalledExactlyOnceWith('none');+ expect(updateSettings).toHaveBeenCalledExactlyOnceWith({ autoAddBoardId: GALLERY_AUTO_ADD_FOLLOW });+ });++ it('keeps the selection and auto-add on a board that stays in sight', async () => {+ mocks.updateGalleryBoard.mockResolvedValue(undefined);++ for (const [values, destination] of [+ [{ autoAddBoardId: 'board-1' }, 'project-1'],+ [{ autoAddBoardId: 'board-1', showOtherProjectBoards: true }, 'other-project'],+ ] as const) {+ galleryValues = values;+ await renderProbe();+ await act(async () => {+ await actionsRef.current?.moveBoard('board-1', destination, 'Somewhere');+ });+ }++ expect(selectBoard).not.toHaveBeenCalled();+ expect(updateSettings).not.toHaveBeenCalled();});it('keeps a successful rename applied without rolling back', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex f8ccc7b505..4300910b9e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -2,6 +2,7 @@ import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { toGalleryItemKey } from '@features/gallery/core/items';+import { GALLERY_AUTO_ADD_FOLLOW, getGallerySettings } from '@features/gallery/core/settings';import {createGalleryBoard,deleteGalleryBoard,@@ -33,11 +34,14 @@ export const useGalleryActions = ({selectedBoardId,}: {boards: GalleryBoard[];- getCurrentGalleryLocation: () => { galleryView: GalleryView; selectedBoardId: string };+ /** The latest rendered gallery, for settling an action the user may have moved on from while it ran. */+ getCurrentGalleryLocation: () => { autoAddBoardId: string; galleryView: GalleryView; selectedBoardId: string };loadMore: () => void;selectedBoardId: string;}): GalleryActions => {- const { ensureProjectOnServer, exportProject, gallery, notifications, widgets } = useGalleryUi();+ const { ensureProjectOnServer, exportProject, gallery, galleryValues, notifications, projectId, widgets } =+ useGalleryUi();+ const { autoAddBoardId, showOtherProjectBoards } = getGallerySettings(galleryValues);const queryClient = useQueryClient();const { t } = useTranslation();const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });@@ -183,17 +187,30 @@ export const useGalleryActions = ({},exportProject,loadMore,- moveBoard: async (boardId, projectId, destinationLabel) => {+ moveBoard: async (boardId, destinationProjectId, destinationLabel) => {const owner = captureAccountScope();- const rollback = patchGalleryBoardCaches(queryClient, boardId, { projectId });+ const rollback = patchGalleryBoardCaches(queryClient, boardId, { projectId: destinationProjectId });+ // Into another project while other projects are hidden, the board leaves the panel as an archived one does:+ // it stops being the selection and the auto-add target rather than take results nothing on screen shows.+ const leavesView =+ destinationProjectId !== null && destinationProjectId !== projectId && !showOtherProjectBoards;+ const movedSelectionAway = leavesView && boardId === selectedBoardId;+ const stoppedAutoAdding = leavesView && boardId === autoAddBoardId;++ if (movedSelectionAway) {+ gallery.selectBoard('none');+ }+ if (stoppedAutoAdding) {+ gallery.updateSettings({ autoAddBoardId: GALLERY_AUTO_ADD_FOLLOW });+ }try {- if (projectId !== null) {+ if (destinationProjectId !== null) {await ensureProjectOnServer?.();assertAccountScopeCurrent(owner);}- await updateGalleryBoard(boardId, { projectId }, owner.signal);+ await updateGalleryBoard(boardId, { projectId: destinationProjectId }, owner.signal);assertAccountScopeCurrent(owner);recordSuccess(@@ -206,6 +223,16 @@ export const useGalleryActions = ({}rollback();++ // Each only while the user has not chosen again since.+ const current = getCurrentGalleryLocation();+ if (movedSelectionAway && current.selectedBoardId === 'none') {+ gallery.selectBoard(boardId);+ }+ if (stoppedAutoAdding && current.autoAddBoardId === GALLERY_AUTO_ADD_FOLLOW) {+ gallery.updateSettings({ autoAddBoardId: boardId });+ }+recordError(error);}},@@ -257,6 +284,7 @@ export const useGalleryActions = ({uploadFiles,};}, [+ autoAddBoardId,boards,ensureProjectOnServer,exportProject,@@ -264,8 +292,10 @@ export const useGalleryActions = ({getCurrentGalleryLocation,loadMore,notifications,+ projectId,queryClient,selectedBoardId,+ showOtherProjectBoards,t,uploadFiles,widgets,diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex 419809f28f..e50834a37e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -138,12 +138,46 @@ describe('createProjectSettled', () => {it('leaves an unresolved outcome unresolved rather than authorizing a rollback', async () => {const failure = new TypeError('network error');- transport.apiFetchJson.mockRejectedValueOnce(failure).mockRejectedValueOnce(new TypeError('still offline'));+ transport.apiFetchJson+ .mockRejectedValueOnce(failure)+ .mockRejectedValueOnce(new TypeError('still offline'))+ // A read that finds nothing may have raced the first create's commit.+ .mockRejectedValueOnce(new ApiError('not found', 404));// The original failure, not a proof of absence: unknown must never authorize deletion.await expect(createProjectSettled(request, captureAccountScope())).rejects.toBe(failure);});+ it('adopts the project a read finds when neither create was answered', async () => {+ const project = {+ board_id: 'board-for-project-1',+ data: {},+ minimum_canvas_schema_version: 3,+ name: 'Imported',+ project_id: 'project-1',+ };+ transport.apiFetchJson+ .mockRejectedValueOnce(new TypeError('response lost'))+ .mockRejectedValueOnce(new ApiError('bad gateway', 502))+ .mockResolvedValueOnce(project);++ await expect(createProjectSettled(request, captureAccountScope())).resolves.toMatchObject(project);+ expect(transport.apiFetchJson).toHaveBeenNthCalledWith(+ 3,+ '/api/v1/projects/project-1?max_canvas_schema_version=4',+ expect.anything()+ );++ // Somebody else's project under the id is not this create's.+ const failure = new TypeError('response lost');+ transport.apiFetchJson+ .mockRejectedValueOnce(failure)+ .mockRejectedValueOnce(new TypeError('still offline'))+ .mockResolvedValueOnce({ ...project, data: { owner: 'somebody-else' }, name: "Somebody else's project" });++ await expect(createProjectSettled(request, captureAccountScope())).rejects.toBe(failure);+ });+it('treats exhausted ingress capacity as proof that an initial create did not run', async () => {vi.useFakeTimers();const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '0' }));@@ -183,9 +217,11 @@ describe('createProjectSettled', () => {await vi.runAllTimersAsync();await settled;- expect(transport.apiFetchJson).toHaveBeenCalledTimes(9);+ // Nine creates, then the read that finds nothing settled.+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(10);expect(serializedValueReads).toBe(1);- expect(new Set(transport.apiFetchJson.mock.calls.map((call) => (call[1] as RequestInit).body)).size).toBe(1);+ const creates = transport.apiFetchJson.mock.calls.slice(0, 9);+ expect(new Set(creates.map((call) => (call[1] as RequestInit).body)).size).toBe(1);vi.useRealTimers();random.mockRestore();});diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex f479c2444e..80da305e59 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -326,7 +326,8 @@ export class ProjectCreateAbsentError extends Error {/*** Settle ambiguous creates with a second POST: SQLite serializes writers, while GET 404 can race the initial* commit. A 201 succeeds; after 409, GET distinguishes an existing project from a board conflict. Other- * deterministic rejections prove absence. Transport failure remains unknown and must never authorize deletion.+ * deterministic rejections prove absence. When the retry settles nothing either, a GET that finds this create's+ * project still proves it committed. Transport failure remains unknown and must never authorize deletion.*/const settleProjectCreate = async (request: ProjectCreateRequest, owner: AccountScope): Promise<ProjectRecordDTO> => {const projectId = request.project_id;@@ -354,6 +355,24 @@ const settleProjectCreate = async (request: ProjectCreateRequest, owner: Account}};+ /** No answer settled the create; only finding its project does. A 404 here may predate the commit, so proves nothing. */+ const settleUnanswered = async (unanswered: unknown, id: string): Promise<ProjectRecordDTO> => {+ let record: ProjectRecordDTO | null = null;++ try {+ record = await getProject(id, owner.signal);+ } catch {+ // Still unknown.+ }+ assertAccountScopeCurrent(owner);++ if (record === null || !projectRecordMatchesCreate(record, body)) {+ throw unanswered;+ }++ return record;+ };+const classify = (error: unknown): Promise<ProjectRecordDTO> => {if (isProjectConflictError(error)) {return settleConflict(error);@@ -379,7 +398,7 @@ const settleProjectCreate = async (request: ProjectCreateRequest, owner: Account// An ambiguous retry must retain uploads; unknown never authorizes cleanup.if (isIndeterminate(retryError) || isProjectWriteBusyError(retryError)) {- throw error;+ return settleUnanswered(error, projectId);}return classify(retryError);@@ -393,13 +412,20 @@ export const createProjectSettled = async (): Promise<ProjectRecordDTO> => {const record = await settleProjectCreate(request, owner);- // The server mints the project's board with it, so board lists fetched before now are missing it. Loaded lazily- // to keep the gallery data layer off the launchpad's startup graph.+ // The server mints the project's board with it, so board lists fetched before now are missing it.+ invalidateBoardLists(owner);++ return record;+};++/**+ * Mark the account's board lists stale after a change the board endpoints do not announce. Loaded lazily to keep the+ * gallery data layer off the launchpad's startup graph.+ */+export const invalidateBoardLists = (owner: AccountScope): void => {void import('@features/gallery/queries').then(({ galleryKeys }) =>queryClient.invalidateQueries({ queryKey: galleryKeys.boardsForAccount(owner) }));-- return record;};/** A response arrived and refused the create outright, so nothing was written. */diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsxindex 65f143185a..d8638c4bf4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsx@@ -67,8 +67,9 @@ const noop = () => undefined;let host: HTMLDivElement | null = null;let root: Root | null = null;-const renderDialog = async (projectId: string, seed = true) => {- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+let queryClient = new QueryClient();++const renderDialog = async (projectId: string, seed = true, isOpen = true) => {if (seed) {// Archived members are included: they go with the project just the same.queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, boards);@@ -80,7 +81,7 @@ const renderDialog = async (projectId: string, seed = true) => {<QueryClientProvider client={queryClient}><DeleteProjectDialogbody="Delete this project?"- isOpen+ isOpen={isOpen}projectId={projectId}onClose={noop}onConfirm={onConfirm}@@ -99,6 +100,7 @@ const confirmButton = () =>beforeEach(() => {onConfirm.mockClear();+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -137,6 +139,33 @@ describe('DeleteProjectDialog', () => {expect(onConfirm).toHaveBeenCalledExactlyOnceWith('delete');});+ it('starts every opening from keeping the boards, even one that comes before the last finished closing', async () => {+ const chooseDelete = () =>+ act(() =>+ userEvent.click(+ [...document.querySelectorAll<HTMLElement>('[role="alertdialog"] label')].find((label) =>+ label.textContent?.includes('Delete its other boards too')+ )!+ )+ );+ const p3Boards = [createBoard({ id: 'p3-member', name: 'Elevations', projectId: 'p3' })];+ queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, [...boards, ...p3Boards]);++ await renderDialog('p1', false);+ await chooseDelete();+ // Reopened for another project with no exit in between.+ await renderDialog('p3', false);+ await act(() => userEvent.click(confirmButton()));+ expect(onConfirm).toHaveBeenLastCalledWith('release');++ await chooseDelete();+ // Closed and reopened for the same project before its exit finished.+ await renderDialog('p3', false, false);+ await renderDialog('p3', false);+ await act(() => userEvent.click(confirmButton()));+ expect(onConfirm).toHaveBeenLastCalledWith('release');+ });+it('holds confirmation until the boards are known, and says so when they cannot be', async () => {vi.mocked(apiFetchJson).mockReturnValue(new Promise(() => {}));await renderDialog('p1', false);diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsxindex 9e06533b8a..bac976e2bd 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsx@@ -30,6 +30,16 @@ export const DeleteProjectDialog = ({}) => {const { t } = useTranslation();const [boards, setBoards] = useState<DeleteProjectBoards>('release');+ // Each opening starts from the safe choice again, set as it opens rather than once the last one finished closing:+ // a dialog reopened during that exit, for this project or another, must not inherit a destructive choice.+ const [choiceOpenFor, setChoiceOpenFor] = useState<string | null>(null);+ const openFor = isOpen ? projectId : null;+ if (openFor !== choiceOpenFor) {+ setChoiceOpenFor(openFor);+ if (openFor !== null) {+ setBoards('release');+ }+ }// Archived members go with the project just the same, so the list must include them.const { data, isError, isLoading } = useQuery({...galleryBoardsOptions({ includeArchived: true }),@@ -45,8 +55,6 @@ export const DeleteProjectDialog = ({setBoards(event.value === 'delete' ? 'delete' : 'release');}, []);const handleConfirm = useCallback(() => onConfirm(boards), [boards, onConfirm]);- // Each opening starts from the safe choice again.- const handleExitComplete = useCallback(() => setBoards('release'), []);return (<ConfirmDialog@@ -106,7 +114,6 @@ export const DeleteProjectDialog = ({title={t('projects.deleteProjectQuestion')}onClose={onClose}onConfirm={handleConfirm}- onExitComplete={handleExitComplete}/>);};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsindex 54400f4178..c97cc5b702 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -19,6 +19,7 @@ import type * as duplicateProjectModule from './duplicateProject';const api = vi.hoisted(() => ({createProjectSettled: vi.fn(),getProject: vi.fn(),+ invalidateBoardLists: vi.fn(),isProjectNotFoundError: (error: unknown) =>typeof error === 'object' && error !== null && 'status' in error && error.status === 404,}));@@ -292,15 +293,19 @@ describe('duplicateProjectRecord', () => {.mockResolvedValueOnce('member-staging').mockResolvedValueOnce('empty-staging');- const result = await duplicateProject.duplicateProjectRecord({- boards: [- ...inboxOf([boardItem()]),- { archived: true, board_id: 'old', is_inbox: false, items: [boardItem({ name: 'old.png' })], name: 'Old' },- { archived: false, board_id: 'empty', is_inbox: false, items: [], name: 'Empty' },- ],- owner,- record: sourceRecord(),- });+ const onProgress = vi.fn();+ const result = await duplicateProject.duplicateProjectRecord(+ {+ boards: [+ ...inboxOf([boardItem()]),+ { archived: true, board_id: 'old', is_inbox: false, items: [boardItem({ name: 'old.png' })], name: 'Old' },+ { archived: false, board_id: 'empty', is_inbox: false, items: [], name: 'Empty' },+ ],+ owner,+ record: sourceRecord(),+ },+ { onProgress }+ );// In source order, so the copy's boards keep their creation order; the empty one has nothing to copy.expect((transport.createStagingBoard.mock.calls as unknown[][]).map((call) => call[0])).toEqual([@@ -316,6 +321,17 @@ describe('duplicateProjectRecord', () => {['member-staging', result.record.project_id, true, owner.signal],['empty-staging', result.record.project_id, false, owner.signal],]);+ // Copying is counted by item, then the moves by board, so progress does not sit at its end while boards move.+ expect(onProgress.mock.calls.map(([progress]) => progress).slice(-3)).toEqual([+ { completed: 2, phase: 'restoring', total: 2 },+ { completed: 1, phase: 'placing-boards', total: 2 },+ { completed: 2, phase: 'placing-boards', total: 2 },+ ]);+ // Board lists refreshed before the moves finished would still show the members in the Library.+ expect(api.invalidateBoardLists).toHaveBeenCalledExactlyOnceWith(owner);+ expect(api.invalidateBoardLists.mock.invocationCallOrder[0]).toBeGreaterThan(+ transport.placeBoardInProject.mock.invocationCallOrder[1]!+ );expect(result.boardIssues).toEqual([]);});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsindex 997262bf29..76cc1f75dc 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -1,7 +1,7 @@import type { ProjectBoardSnapshotBoardDTO, ProjectRecordDTO } from '@workbench/projects/api';import { type AccountScope, assertAccountScopeCurrent, isAccountScopeCurrent } from '@platform/state/accountLifecycle';-import { createProjectSettled } from '@workbench/projects/api';+import { createProjectSettled, invalidateBoardLists } from '@workbench/projects/api';import { createProjectId } from '@workbench/projects/ids';import {collectLiveAssetRefs,@@ -40,7 +40,8 @@ export interface DuplicateProjectInput {export interface DuplicateProjectDeps {copyImages?: typeof copyImagesToBoard;copyVideos?: typeof copyVideosToBoard;- onProgress?: (progress: { completed: number; total: number }) => void;+ /** Copying the media, then moving the other boards into the copy. */+ onProgress?: (progress: { completed: number; phase: 'placing-boards' | 'restoring'; total: number }) => void;}export interface DuplicateProjectResult extends ProjectTransferIssues {@@ -68,28 +69,34 @@ export const createCopyMediaMaterializer = (return { copied: [], failed: names };};- return async (items, boardId, onItemSettled) => {- const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);- const videoNames = items.filter((item) => item.kind === 'video').map((item) => item.name);- const [images, videos] = await Promise.all([- copyImages(imageNames, boardId, deps.signal).catch(allFailed(imageNames)),- copyVideos(videoNames, boardId, deps.signal).catch(allFailed(videoNames)),- ]);-- for (let index = 0; index < items.length; index += 1) {- onItemSettled();- }+ // Board by board: each board's media is one batched copy the server does in a single request, so overlapping them+ // would add server load rather than save round trips.+ return async (boards, onItemSettled) => {+ const result: Awaited<ReturnType<MediaMaterializer>> = { failed: [], materialized: [] };++ for (const { items, stagingBoardId } of boards) {+ const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);+ const videoNames = items.filter((item) => item.kind === 'video').map((item) => item.name);+ const [images, videos] = await Promise.all([+ copyImages(imageNames, stagingBoardId, deps.signal).catch(allFailed(imageNames)),+ copyVideos(videoNames, stagingBoardId, deps.signal).catch(allFailed(videoNames)),+ ]);++ for (let index = 0; index < items.length; index += 1) {+ onItemSettled();+ }- return {- failed: [+ result.failed.push(...images.failed.map((name) => ({ kind: 'image' as const, name, reason: 'upload-failed' as const })),- ...videos.failed.map((name) => ({ kind: 'video' as const, name, reason: 'upload-failed' as const })),- ],- materialized: [+ ...videos.failed.map((name) => ({ kind: 'video' as const, name, reason: 'upload-failed' as const }))+ );+ result.materialized.push(...images.copied.map((entry) => ({ kind: 'image' as const, name: entry.name, sourceName: entry.sourceName })),- ...videos.copied.map((entry) => ({ kind: 'video' as const, name: entry.name, sourceName: entry.sourceName })),- ],- };+ ...videos.copied.map((entry) => ({ kind: 'video' as const, name: entry.name, sourceName: entry.sourceName }))+ );+ }++ return result;};};@@ -171,7 +178,9 @@ export const duplicateProjectRecord = async (...(deps.copyVideos === undefined ? {} : { copyVideos: deps.copyVideos }),signal: owner.signal,}),- ...(deps.onProgress === undefined ? {} : { onProgress: deps.onProgress }),+ ...(deps.onProgress === undefined+ ? {}+ : { onProgress: (progress) => deps.onProgress?.({ ...progress, phase: 'restoring' }) }),signal: owner.signal,});@@ -192,8 +201,12 @@ export const duplicateProjectRecord = async (didCreateProject = true;assertAccountScopeCurrent(owner);- // The copy exists; its other boards can now belong to it. Reported, never fatal, from here on.- const boardIssues = await placeMemberBoards(stagedBoards, record.project_id, { signal: owner.signal });+ // The copy exists; its other boards can now belong to it. Reported, never fatal, from here on. Lists fetched+ // while they were still staged, the create's own refresh among them, would keep showing them in the Library.+ const boardIssues = await placeMemberBoards(stagedBoards, record.project_id, {+ onProgress: (completed, total) => deps.onProgress?.({ completed, phase: 'placing-boards', total }),+ signal: owner.signal,+ }).finally(() => invalidateBoardLists(owner));assertAccountScopeCurrent(owner);return {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex f2dbc29fe2..110bc49c63 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -187,8 +187,12 @@ describe('createArchiveMediaMaterializer', () => {const settled = vi.fn();const result = await materialize(- [boardItem({ category: 'control' }), boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })],- 'staging',+ [+ {+ items: [boardItem({ category: 'control' }), boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })],+ stagingBoardId: 'staging',+ },+ ],settled);@@ -215,8 +219,7 @@ describe('createArchiveMediaMaterializer', () => {Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 }));const result = await createArchiveMediaMaterializer(archive(), { uploadBoardImage })(- [boardItem()],- 'staging',+ [{ items: [boardItem()], stagingBoardId: 'staging' }],() => undefined);@@ -226,8 +229,7 @@ describe('createArchiveMediaMaterializer', () => {it('reports a descriptor the archive carried no bytes for', async () => {const uploadBoardImage = vi.fn(() => Promise.reject(new Error('should not be called')));const result = await createArchiveMediaMaterializer(archive(), { uploadBoardImage })(- [boardItem({ name: 'absent.png' })],- 'staging',+ [{ items: [boardItem({ name: 'absent.png' })], stagingBoardId: 'staging' }],() => undefined);@@ -246,14 +248,42 @@ describe('createArchiveMediaMaterializer', () => {withSecond.images.set('b.png', bytes(3));const result = await createArchiveMediaMaterializer(withSecond, { uploadBoardImage })(- [boardItem(), boardItem({ name: 'b.png' })],- 'staging',+ [{ items: [boardItem(), boardItem({ name: 'b.png' })], stagingBoardId: 'staging' }],() => undefined);expect(result.failed).toEqual([{ kind: 'image', name: 'a.png', reason: 'upload-failed' }]);expect(result.materialized).toEqual([{ kind: 'image', name: 'fresh.png', sourceName: 'b.png' }]);});++ it('uploads across boards at once, so many small boards are not restored one at a time', async () => {+ const images = new Map(['a.png', 'b.png', 'c.png'].map((name, index) => [name, bytes(index)]));+ const releases: (() => void)[] = [];+ const uploadBoardImage = vi.fn(+ (_bytes: Uint8Array, fileName: string, options: { boardId?: string }) =>+ new Promise<{ height: number; imageName: string; width: number }>((resolve) => {+ releases.push(() => resolve({ height: 1, imageName: `${String(options.boardId)}/${fileName}`, width: 1 }));+ })+ );++ const materializing = createArchiveMediaMaterializer({ images, videos: new Map() }, { uploadBoardImage })(+ [+ { items: [boardItem({ name: 'a.png' })], stagingBoardId: 'one' },+ { items: [boardItem({ name: 'b.png' })], stagingBoardId: 'two' },+ { items: [boardItem({ name: 'c.png' })], stagingBoardId: 'three' },+ ],+ () => undefined+ );++ await vi.waitFor(() => expect(uploadBoardImage).toHaveBeenCalledTimes(3));+ releases.forEach((release) => release());++ expect((await materializing).materialized.map((entry) => entry.name).sort()).toEqual([+ 'one/a.png',+ 'three/c.png',+ 'two/b.png',+ ]);+ });});describe('restoreArchiveMedia', () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex 6b6ea19a55..519d0b50b0 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -173,10 +173,15 @@ export const createArchiveMediaMaterializer = (const uploadImage = deps.uploadBoardImage ?? uploadBoardImage;const uploadVideo = deps.uploadBoardVideo ?? uploadBoardVideo;- return async (items, boardId, onItemSettled) => {+ return async (boards, onItemSettled) => {const result: Awaited<ReturnType<MediaMaterializer>> = { failed: [], materialized: [] };+ // One pool across the boards: uploads are per item, so an archive of many small boards would otherwise run+ // little more than one at a time.+ const uploads = boards.flatMap(({ items, stagingBoardId }) =>+ items.map((item) => ({ boardId: stagingBoardId, item }))+ );- await mapWithConcurrency(items, INVK_TRANSFER_CONCURRENCY, async (item) => {+ await mapWithConcurrency(uploads, INVK_TRANSFER_CONCURRENCY, async ({ boardId, item }) => {const entries = item.kind === 'image' ? archive.images : archive.videos;const bytes = entries.get(item.name);diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.tsindex c2e519afdf..c9a7848210 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts@@ -18,6 +18,8 @@ export interface StagedBoard {}export interface MemberBoardPlacementDeps {+ /** After each board settles, placed or not. */+ onProgress?: (completed: number, total: number) => void;placeBoardInProject?: typeof placeBoardInProject;signal?: AbortSignal;}@@ -61,12 +63,9 @@ export const placeMemberBoards = async (): Promise<InvkBoardIssue[]> => {const place = deps.placeBoardInProject ?? placeBoardInProject;const issues: InvkBoardIssue[] = [];+ const members = staged.filter(({ board }) => !board.isInbox);- for (const { board, stagingBoardId } of staged) {- if (board.isInbox) {- continue;- }-+ for (const [index, { board, stagingBoardId }] of members.entries()) {try {await place(stagingBoardId, projectId, board.archived, deps.signal);} catch (error) {@@ -76,6 +75,8 @@ export const placeMemberBoards = async (issues.push({ name: board.name });}++ deps.onProgress?.(index + 1, members.length);}return issues;diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.tsindex eb5c7206ca..795625e83f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts@@ -24,17 +24,23 @@ const imageRef = (name: string): InvkMediaRef => ({ kind: 'image', name });/** Materializes everything, under the fresh names the destination server would assign. */const freshNameMaterializer =(options: { fail?: ReadonlySet<string> } = {}): MediaMaterializer =>- (items, boardId, onItemSettled) => {+ (boards, onItemSettled) => {const result: MaterializeResult = { failed: [], materialized: [] };- for (const item of items) {- if (options.fail?.has(item.name)) {- result.failed.push({ kind: item.kind, name: item.name, reason: 'upload-failed' });- } else {- result.materialized.push({ kind: item.kind, name: `${boardId}-${item.name}`, sourceName: item.name });- }+ for (const { items, stagingBoardId } of boards) {+ for (const item of items) {+ if (options.fail?.has(item.name)) {+ result.failed.push({ kind: item.kind, name: item.name, reason: 'upload-failed' });+ } else {+ result.materialized.push({+ kind: item.kind,+ name: `${stagingBoardId}-${item.name}`,+ sourceName: item.name,+ });+ }- onItemSettled();+ onItemSettled();+ }}return Promise.resolve(result);@@ -198,7 +204,7 @@ describe('board media', () => {const result = await restore({ boardItems: [boardItem({ name: 'described.png' })] },{- materializeBoardMedia: (_items, _boardId, onItemSettled) => {+ materializeBoardMedia: (_boards, onItemSettled) => {onItemSettled();return Promise.resolve({@@ -238,10 +244,10 @@ describe('board media', () => {const result = await restore({ boardItems: [boardItem({ name: 'gone.png' })], documentRefs: [imageRef('gone.png')] },{- materializeBoardMedia: (items, _boardId, onItemSettled) => {+ materializeBoardMedia: (boards, onItemSettled) => {onItemSettled();- return Promise.resolve({ failed: failuresFor(items), materialized: [] });+ return Promise.resolve({ failed: failuresFor(boards.flatMap((board) => board.items)), materialized: [] });},});@@ -413,10 +419,12 @@ describe('progress', () => {it('counts the items of every staged board, each materialized onto its own board', async () => {const onProgress = vi.fn();const targets: [string, string][] = [];- const materializeBoardMedia: MediaMaterializer = (items, boardId, onItemSettled) => {- targets.push(...items.map((item): [string, string] => [item.name, boardId]));+ const materializeBoardMedia: MediaMaterializer = (boards, onItemSettled) => {+ for (const { items, stagingBoardId } of boards) {+ targets.push(...items.map((item): [string, string] => [item.name, stagingBoardId]));+ }- return freshNameMaterializer()(items, boardId, onItemSettled);+ return freshNameMaterializer()(boards, onItemSettled);};await restore(diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.tsindex fba7fd6050..641d477cfb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts@@ -62,10 +62,12 @@ export interface MaterializeResult {materialized: MaterializedMedia[];}-/** onItemSettled fires exactly once per descriptor. */+/**+ * Takes every board at once, so it schedules the work across them: many small boards should not run one at a time.+ * onItemSettled fires exactly once per descriptor.+ */export type MediaMaterializer = (- items: readonly InvkBoardItem[],- boardId: string,+ boards: readonly RestoreBoardInput[],onItemSettled: () => void) => Promise<MaterializeResult>;@@ -282,15 +284,8 @@ export const restoreProjectMedia = async (: checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),]);- // Board by board, in order: a staging board holds exactly its source board's media.- const boardResult: MaterializeResult = { failed: [], materialized: [] };-- for (const board of stagedBoards) {- const result = await deps.materializeBoardMedia(board.items, board.stagingBoardId, advance);-- boardResult.failed.push(...result.failed);- boardResult.materialized.push(...result.materialized);- }+ // Each staging board receives exactly its source board's media.+ const boardResult = await deps.materializeBoardMedia(stagedBoards, advance);const starTargets = { image: [] as string[], video: [] as string[] };const sourceNamesByFreshName = new Map<string, string>();@@ -507,7 +502,7 @@ export const rollbackRestoredMedia = async (]);await Promise.allSettled(- // An unclaimed private board is invisible clutter, not a broken state, so each is best-effort.+ // A staging board left behind is a Library board its owner can delete, not a broken state, so each is best-effort.ledger.boardIds.map((boardId) => deleteBoard(boardId, deps.signal)));};diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 30a43f6dde..dddb384605 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -10,6 +10,7 @@ import { createSingleFlight } from '@platform/state/singleFlight';import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';import { DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION, isCanvasSchemaVersionSupported } from '@workbench/canvasSchemaVersion';+import type { DuplicateProjectDeps } from './invk/duplicateProject';import type { ProjectTransferIssues } from './invk/transfer';import {@@ -312,7 +313,7 @@ export interface DuplicatedProject extends ProjectTransferIssues {*/export const duplicateLibraryProject = async (projectId: string,- options: { onProgress?: (progress: { completed: number; total: number }) => void; owner?: AccountScope } = {}+ options: Pick<DuplicateProjectDeps, 'onProgress'> & { owner?: AccountScope } = {}): Promise<DuplicatedProject> => {const owner = options.owner ?? captureAccountScope();const record = await readAcknowledgedProject(projectId, owner);diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 1799c1a453..82a260dc3e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -19,6 +19,7 @@ const api = vi.hoisted(() => ({deleteClientStateValue: vi.fn(() => Promise.resolve()),getClientStateValue: vi.fn(() => Promise.resolve(null)),getProject: vi.fn(),+ invalidateBoardLists: vi.fn(),// Every export enumerates the project's board; most of these cases do not care what is on it.getProjectBoardSnapshot: vi.fn((): Promise<ProjectBoardSnapshotDTO> =>Promise.resolve({ boards: [{ archived: false, board_id: 'inbox', is_inbox: true, items: [], name: 'Project' }] })@@ -1168,6 +1169,11 @@ describe('importing every board of a project', () => {['staging-old', projectId, true, expect.anything()],['staging-empty', projectId, false, expect.anything()],]);+ // Board lists refreshed before the moves finished would still show the members in the Library.+ expect(api.invalidateBoardLists).toHaveBeenCalledOnce();+ expect(api.invalidateBoardLists.mock.invocationCallOrder[0]).toBeGreaterThan(+ transport.placeBoardInProject.mock.invocationCallOrder[1]!+ );expect(outcome.boardIssues).toEqual([]);expect(outcome.boardItemIssues).toEqual([]);});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 61494fa694..f074a28158 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -12,7 +12,7 @@ import { getProjectCanvasSchemaRequirement, MAX_SUPPORTED_CANVAS_SCHEMA_VERSIONimport type { ProjectTransferIssues } from './invk/transfer';-import { createProjectSettled, getProjectBoardSnapshot, type ProjectRecordDTO } from './api';+import { createProjectSettled, getProjectBoardSnapshot, invalidateBoardLists, type ProjectRecordDTO } from './api';import { recordProjectCover } from './covers';import { createProjectId } from './ids';import { INVK_EXTENSION, InvkFormatError, toInvkFormatReason } from './invk/format';@@ -60,7 +60,7 @@ export const parseProjectFile = (text: string): Record<string, unknown> | null =/** Asset-count phases exclude ZIP packing. */export interface ProjectFileProgress {completed: number;- phase: 'bundling' | 'packing' | 'restoring' | 'restoring-fonts';+ phase: 'bundling' | 'packing' | 'placing-boards' | 'restoring' | 'restoring-fonts';total: number;}@@ -338,11 +338,17 @@ export const importProjectFile = async (didCreateProject = true;assertAccountScopeCurrent(owner);- // The project exists; its other boards can now belong to it. Reported, never fatal, from here on.+ // The project exists; its other boards can now belong to it. Reported, never fatal, from here on. Lists fetched+ // while they were still staged, the create's own refresh among them, would keep showing them in the Library.const boardIssues =memberBoards === null? []- : await memberBoards.placeMemberBoards(stagedBoards, record.project_id, { signal: owner.signal });+ : await memberBoards+ .placeMemberBoards(stagedBoards, record.project_id, {+ onProgress: (completed, total) => options.onProgress?.({ completed, phase: 'placing-boards', total }),+ signal: owner.signal,+ })+ .finally(() => invalidateBoardLists(owner));assertAccountScopeCurrent(owner);upsertProjectSummary({diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.tsindex d646191af8..bcd95fccfb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts@@ -123,6 +123,16 @@ describe('startProjectFileReport', () => {);});+ it('counts the boards moved into the project once the media is in', () => {+ const report = toasts.startProjectFileReport(t, 'projects.importing');++ report.report({ completed: 1, phase: 'placing-boards', total: 3 });++ expect(toaster.update.mock.calls[0]![1].description).toBe(+ 'projects.file.placingBoardsProgress({"completed":1,"total":3})'+ );+ });+/** Count missing board media separately from missing document references. */it.each([['nothing', [], [], { title: 'projects.exported', type: 'success' }],diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex b935c45f05..2eb1bb8260 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -38,6 +38,9 @@ const describeProgress = (t: Translate, progress: ProjectFileProgress): string =if (progress.phase === 'restoring-fonts') {return t('projects.fonts.installing', { completed: progress.completed, total: progress.total });}+ if (progress.phase === 'placing-boards') {+ return t('projects.file.placingBoardsProgress', { completed: progress.completed, total: progress.total });+ }const key = progress.phase === 'bundling' ? 'projects.file.bundlingProgress' : 'projects.file.restoringProgress';diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsxindex 1d047a47fb..236b8d8ccf 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx@@ -1,6 +1,8 @@+import type { GalleryBoard } from '@features/gallery';import type { Project } from '@workbench/projectContracts';import type { ProjectCommandResult } from '@workbench/workbenchStore';+import { galleryBoardsOptions } from '@features/gallery/queries';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { createDraftProject } from '@workbench/workbenchState';@@ -20,6 +22,7 @@ const harness = vi.hoisted(() => ({notifyError: vi.fn(),persistEmptySession: vi.fn(),project: {} as Project,+ reconcileDeletedBoardOutcome: vi.fn(),releaseProjectSync: vi.fn(),reopenSession: vi.fn(),}));@@ -35,7 +38,10 @@ vi.mock('@tanstack/react-router', async (importOriginal) => ({vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: harness.notifyError }) }));vi.mock('@workbench/WorkbenchContext', () => ({useWorkbenchLiveCanvasEngines: () => ({ flushPendingPixels: harness.flushCanvasPixels }),- useWorkbenchCommands: () => ({ projects: { close: harness.close } }),+ useWorkbenchCommands: () => ({+ gallery: { reconcileDeletedBoardOutcome: harness.reconcileDeletedBoardOutcome },+ projects: { close: harness.close },+ }),useWorkbenchPersistenceAdapter: () => ({ getState: () => ({ projects: [harness.project] }) }),useWorkbenchPersistenceService: () => ({flushProjectToServer: harness.flush,@@ -62,6 +68,7 @@ const HarnessBody = () => {<><button onClick={() => closeProject(harness.project)}>close</button><button onClick={() => void deleteProject(harness.project)}>delete</button>+ <button onClick={() => void deleteProject(harness.project, 'delete')}>delete with boards</button></>);};@@ -85,6 +92,8 @@ beforeEach(() => {harness.flushCanvasPixels.mockReset();harness.flushCanvasPixels.mockResolvedValue(undefined);harness.navigate.mockReset();+ harness.reconcileDeletedBoardOutcome.mockReset();+ queryClient.clear();harness.notifyError.mockReset();harness.persistEmptySession.mockReset();harness.persistEmptySession.mockResolvedValue(undefined);@@ -115,6 +124,50 @@ describe('useProjectActions', () => {expect(harness.deleteLibraryProject).not.toHaveBeenCalled();});+ it('clears other open projects of the boards that went with a deleted project, and only once it is gone', async () => {+ const board = (id: string, projectId: string | null, isInbox = false, archived = false): GalleryBoard => ({+ archived,+ assetCount: 0,+ assetVideoCount: 0,+ id,+ imageCount: 0,+ isInbox,+ kind: 'board',+ name: id,+ projectId,+ videoCount: 0,+ });+ // The delete dialog's list holds archived boards, which go with the project too; the gallery's does not.+ queryClient.setQueryData(galleryBoardsOptions({}).queryKey, [+ board('inbox', harness.project.id, true),+ board('member', harness.project.id),+ board('elsewhere', 'other-project'),+ board('library', null),+ ]);+ queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, [+ board('inbox', harness.project.id, true),+ board('member', harness.project.id),+ board('old-member', harness.project.id, false, true),+ ]);+ const reconciledBoardIds = () =>+ harness.reconcileDeletedBoardOutcome.mock.calls.map((call) => (call[0] as { boardId: string }).boardId);+ await act(() => root?.render(<Harness />));++ harness.deleteLibraryProject.mockRejectedValueOnce(new Error('offline'));+ await act(() => userEvent.click(document.querySelectorAll('button')[2]!));+ expect(harness.reconcileDeletedBoardOutcome).not.toHaveBeenCalled();++ await act(() => userEvent.click(document.querySelectorAll('button')[1]!));+ expect(reconciledBoardIds()).toEqual(['inbox']);++ harness.reconcileDeletedBoardOutcome.mockReset();+ await act(() => userEvent.click(document.querySelectorAll('button')[2]!));+ expect(reconciledBoardIds()).toEqual(['inbox', 'member', 'old-member']);+ expect(harness.reconcileDeletedBoardOutcome).toHaveBeenCalledWith(+ expect.objectContaining({ deletedImageNames: [], deletedVideoNames: [], failedImageNames: [] })+ );+ });+it('blocks project close before flushing while a queue run is active', async () => {harness.project.queue.items = [{ status: 'pending' } as Project['queue']['items'][number]];await act(() => root?.render(<Harness />));diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 3ffc29af60..22890fac3a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -1,6 +1,7 @@+import type { GalleryBoardDeletionResult } from '@features/gallery';import type { Project } from '@workbench/projectContracts';-import { invalidateGallery } from '@features/gallery/queries';+import { getGalleryProjectBoardsFromCaches, invalidateGallery } from '@features/gallery/queries';import {assertAccountScopeCurrent,captureAccountScope,@@ -28,6 +29,16 @@ import { describeRefusedProject } from './projectLoadRefusal';const CLOSE_FLUSH_ATTEMPTS = 3;+/** A project's boards go without their media, which returns to Uncategorized. */+const NO_MEDIA_DELETED: Omit<GalleryBoardDeletionResult, 'boardId'> = {+ deletedBoardImageNames: [],+ deletedBoardVideoNames: [],+ deletedImageNames: [],+ deletedVideoNames: [],+ failedImageNames: [],+ failedVideoNames: [],+};+/*** Open reuses or hydrates a project. Close flushes while preserving the server record; closing the last tab* returns Home. Delete removes the server project.@@ -212,6 +223,11 @@ export const useProjectActions = (): {}const owner = captureAccountScope();+ // The boards that go with it, as the board lists know them: its inbox, and the rest when they go too. Read before+ // the delete, whose refresh drops them from the lists.+ const deletedBoardIds = getGalleryProjectBoardsFromCaches(queryClient, project.id)+ .filter((board) => board.isInbox || boards === 'delete')+ .map((board) => board.id);try {// Open projects delete through the sync engine so in-flight saves finish first.await deleteLibraryProject(project.id, boards);@@ -220,6 +236,10 @@ export const useProjectActions = (): {return;}+ // Other open projects may still select, auto-add to or queue results for those boards. Only this account's.+ for (const boardId of isAccountScopeCurrent(owner) ? deletedBoardIds : []) {+ commands.gallery.reconcileDeletedBoardOutcome({ ...NO_MEDIA_DELETED, boardId });+ }// Its boards were released or deleted with it; every board list on screen is stale either way.void invalidateGallery(queryClient);diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.tsindex 7ec77e8e14..790a9b75c6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts@@ -141,11 +141,7 @@ export const useDuplicateProject = (t,{ direction: 'write', failed: t('projects.duplicateFailed'), running: t('projects.duplicating') },async (report, owner) => {- const duplicated = await duplicateLibraryProject(projectId, {- // Duplication uses the restore phase; this owner defines its reporting vocabulary.- onProgress: ({ completed, total }) => report.report({ completed, phase: 'restoring', total }),- owner,- });+ const duplicated = await duplicateLibraryProject(projectId, { onProgress: report.report, owner });assertAccountScopeCurrent(owner);report.succeed(t('projects.projectDuplicated'), duplicated);diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.pyindex 052764f8de..a53e57da8c 100644--- a/tests/app/services/intermediates/test_intermediates_service.py+++ b/tests/app/services/intermediates/test_intermediates_service.py@@ -294,6 +294,33 @@ def test_summary_groups_rows_and_classifies_under_the_policy(invoker: Invoker, sassert all(row.user_id == "alice" for row in summary.items)+def test_a_project_row_takes_its_cover_from_whichever_of_its_boards_has_the_newest_image(+ invoker: Invoker, service: IntermediatesService+) -> None:+ project = _project(invoker, "alice", "Portraits", {})+ boards = {+ "inbox.png": invoker.services.project_records.get_board_id("alice", project),+ "member.png": invoker.services.board_records.save("Studies", "alice", project_id=project).board_id,+ # Newest of all, but in the Library, so not the project's.+ "library.png": invoker.services.board_records.save("Loose", "alice").board_id,+ }+ for index, (name, board_id) in enumerate(boards.items()):+ _seed_image(invoker, name, project_id=project, is_intermediate=False)+ invoker.services.board_image_records.add_image_to_board(board_id, name)+ with sqlite_cursor_of(invoker.services.session_queue) as cursor:+ cursor.execute(+ "UPDATE board_images SET created_at = ? WHERE image_name = ?;", (f"2020-01-0{index + 1} 00:00:00", name)+ )+ _seed_image(invoker, "intermediate.png", project_id=project, size=1)++ summary = service.get_summary(+ ALICE, owner_id=None, search=None, sort="project_name", descending=False, offset=0, limit=50+ )++ (row,) = [row for row in summary.items if row.project_id == project]+ assert row.cover_image_name == "member.png"++def test_summary_scopes_owners_search_sort_and_pages(invoker: Invoker, service: IntermediatesService) -> None:alpha = _project(invoker, "alice", "Alpha", {})beta = _project(invoker, "alice", "Beta", {})