Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(projects): clear references to deleted boards when a project loads

Josh Corbett6a0b0a62b721
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.mdx
index b5743b790f..a15ccacef4 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
@@ -29,7 +29,7 @@ Hover over a board and click its **⋮** button, or right-click it, to open its
* **Archive Board** / **Unarchive Board** — see [below](#archiving-a-board).
* **Delete Board** — see [below](#deleting-a-board).
-A project's **Inbox** is managed through its project: its menu has **Export project (.invk)**, **Auto-add to this board** and **Download Board** instead, and renaming the project renames it. **Uncategorized** offers only **Auto-add to this board** and **Download Board**, and date boards have no menu. If the auto-add board is deleted, results go back to following the selected board.
+A project's **Inbox** is managed through its project: its menu has **Export project (.invk)**, **Auto-add to this board** and **Download Board** instead, and renaming the project renames it. **Uncategorized** offers only **Auto-add to this board** and **Download Board**, and date boards have no menu. If the auto-add board is deleted, results go back to following the selected board. The same happens when you open a project after a board it used was deleted elsewhere — in another tab, or together with a project deleted from the Launchpad: the project stops selecting it, auto-adding to it and sending queued results to it.
### Archiving a board
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index 2c4e8d5df5..872bbf78f4 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -119,7 +119,7 @@ The skip is by key on purpose, because the members got there differently. `selec
Import 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. 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.
+**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 move whose answer is lost is confirmed by reading the board back before it is reported): 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.
@@ -147,7 +147,7 @@ An open project is flushed to the server before it is read, and a failed flush a
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.
+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. The board lists are refreshed afterwards: uploads announce their board, so a list may already show a staging board the rollback removed.
An asset that is neither on the server nor in the archive is reported as dangling and its reference is left alone, so the project opens with one broken layer rather than not at all. Both fetches and uploads are concurrency-limited to five by `mapWithConcurrency()`, over one queue spanning both kinds — the limit exists to be kind to the backend, and would not be if each kind got its own.
diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.py
index 5baf8a825d..24a9b130e0 100644
--- a/invokeai/app/api/routers/boards.py
+++ b/invokeai/app/api/routers/boards.py
@@ -11,6 +11,7 @@ from invokeai.app.api.routers.image_move_maintenance import assert_image_move_ma
from invokeai.app.services.board_records.board_records_common import (
BoardChanges,
BoardRecordInboxException,
+ BoardRecordNotFoundException,
BoardRecordOrderBy,
BoardRecordProjectNotFoundException,
BoardRecordProjectUnavailableException,
@@ -83,9 +84,10 @@ def get_board(
_assert_board_read_access(board_id, current_user)
+ # Only a board that is not there is a 404: clients take it as the board being gone, and clear what names it.
try:
return ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- except Exception:
+ except BoardRecordNotFoundException:
raise HTTPException(status_code=404, detail="Board not found")
diff --git a/invokeai/app/services/shared/database/queries/intermediates.py b/invokeai/app/services/shared/database/queries/intermediates.py
index 9b30013958..81ee425e54 100644
--- a/invokeai/app/services/shared/database/queries/intermediates.py
+++ b/invokeai/app/services/shared/database/queries/intermediates.py
@@ -494,7 +494,12 @@ def _newest_durable_on_project_board(column: ColumnElement[Any]) -> Any:
# newest comes from its own index range, so the cost follows the number of boards rather than the images on them.
_COVER = (
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)
+ .where(
+ _PROJECT_BOARD.c.user_id == _P.user_id,
+ _PROJECT_BOARD.c.project_id == _P.project_id,
+ # A board with no durable image has nothing to offer, wherever a dialect would sort its NULL.
+ _newest_durable_on_project_board(board_images.c.created_at).is_not(None),
+ )
.order_by(
_newest_durable_on_project_board(board_images.c.created_at).desc(),
_newest_durable_on_project_board(board_images.c.image_name).desc(),
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 08214190ca..ce082f7f7a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -1072,6 +1072,28 @@ export const getGalleryImageMetadata = async (
return body && typeof body === 'object' && !Array.isArray(body) ? (body as GalleryImageMetadata) : null;
};
+/**
+ * Whether a board a project names still exists for this account: false only when the server answers that it does
+ * not. A virtual board (Uncategorized, a date, every board) always exists; any other failure is thrown, unanswered.
+ */
+export const galleryBoardExists = async (boardId: string, signal?: AbortSignal): Promise<boolean> => {
+ if (getUploadBoardId(boardId) === undefined) {
+ return true;
+ }
+
+ try {
+ await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/${encodeURIComponent(boardId)}`, { signal });
+
+ return true;
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) {
+ return false;
+ }
+
+ throw error;
+ }
+};
+
/** `projectId` null creates in the Library; a project must be the caller's own, else the backend answers 404. */
export const createGalleryBoard = async (
boardName: string,
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index f1f177d4f0..1898036d9c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -43,3 +43,4 @@ export {
} from './data/queryCache';
export type { GalleryItemCachePatch } from './data/queryCache';
export { createGalleryRealtimeRuntime } from './data/realtimeRuntime';
+export { galleryBoardExists } from './data/backend';
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 8b2ab661ad..a29382d2bd 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -32,9 +32,12 @@ export interface GalleryBoardMenuTarget {
/** Keep the board dropdown open beneath its cursor-anchored actions menu; actions need not select the board. */
export const GalleryBoardMenu = ({
target,
+ onBoardRelocated,
onClose,
}: {
target: GalleryBoardMenuTarget | null;
+ /** A move or an archive was started from the menu: the board's row is leaving its place in the list. */
+ onBoardRelocated?: (boardId: string) => void;
onClose: () => void;
}) => {
const { t } = useTranslation();
@@ -154,8 +157,8 @@ export const GalleryBoardMenu = ({
{isManagedBoard && (
<>
<BoardRenameMenuItem board={board} onRename={setRenameTarget} onRenameValue={setRenameValue} />
- <BoardMoveSubMenu board={board} />
- <BoardArchiveMenuItem archived={board.archived} boardId={board.id} />
+ <BoardMoveSubMenu board={board} onBoardMoved={onBoardRelocated} />
+ <BoardArchiveMenuItem archived={board.archived} boardId={board.id} onArchive={onBoardRelocated} />
<Menu.Separator />
<BoardDeleteMenuItem board={board} onDelete={setDeleteTarget} />
</>
@@ -270,9 +273,23 @@ const SUBMENU_POSITIONING = { gutter: 2, placement: 'right-start' } as const;
* Where a board can go: the Library, the open project, then the account's other projects by name — every tier
* but the one it is in. Nested so the board menu keeps its one-level shape for the common actions.
*/
-const BoardMoveSubMenu = ({ board }: { board: GalleryBoard }) => {
+const BoardMoveSubMenu = ({
+ board,
+ onBoardMoved,
+}: {
+ board: GalleryBoard;
+ onBoardMoved?: (boardId: string) => void;
+}) => {
const { t } = useTranslation();
const { actions, projectId, projectName, projectNames } = useGalleryWidget();
+ const handleMove = useCallback(
+ (boardId: string, destinationId: string | null, label: string) => {
+ onBoardMoved?.(boardId);
+
+ return actions.moveBoard(boardId, destinationId, label);
+ },
+ [actions, onBoardMoved]
+ );
const destinations = useMemo(() => {
const others = [...projectNames]
.filter(([id]) => id !== projectId && id !== board.projectId)
@@ -310,7 +327,7 @@ const BoardMoveSubMenu = ({ board }: { board: GalleryBoard }) => {
boardId={board.id}
destinationId={destination.id}
label={destination.label}
- onMove={actions.moveBoard}
+ onMove={handleMove}
/>
))}
</MenuContent>
@@ -391,10 +408,21 @@ const BoardRenameMenuItem = ({
);
};
-const BoardArchiveMenuItem = ({ archived, boardId }: { archived: boolean; boardId: string }) => {
+const BoardArchiveMenuItem = ({
+ archived,
+ boardId,
+ onArchive,
+}: {
+ archived: boolean;
+ boardId: string;
+ onArchive?: (boardId: string) => void;
+}) => {
const { t } = useTranslation();
const { actions } = useGalleryWidget();
- const handleClick = useCallback(() => void actions.archiveBoard(boardId, !archived), [actions, archived, boardId]);
+ const handleClick = useCallback(() => {
+ onArchive?.(boardId);
+ void actions.archiveBoard(boardId, !archived);
+ }, [actions, archived, boardId, onArchive]);
return (
<BoardMenuItem
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
index be18b231a3..1360179116 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
@@ -34,6 +34,7 @@ export const GalleryBoardRow = ({
isMenuOpen,
isSelected,
loadedItemBoardIds,
+ onFocusLost,
onOpenMenu,
onSelectBoard,
}: {
@@ -51,6 +52,8 @@ export const GalleryBoardRow = ({
isMenuOpen?: boolean;
isSelected: boolean;
loadedItemBoardIds: ReadonlyMap<GalleryItemKey, string>;
+ /** The row left the list holding focus — moved to another tier, archived or deleted — so focus needs a new home. */
+ onFocusLost?: (boardId: string) => void;
/** Omitted for date rows, which have no board actions. */
onOpenMenu?: (board: GalleryBoard, x: number, y: number) => void;
onSelectBoard: (boardId: string) => void;
@@ -184,6 +187,23 @@ export const GalleryBoardRow = ({
[handleActionsClick, isMenuOpen, onOpenMenu, spokenLabel, stopPropagation, t]
);
+ // The container, which outlives neither a move to another tier (the row remounts there) nor an archive or delete.
+ const setRowRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (!node || !onFocusLost) {
+ return;
+ }
+
+ return () => {
+ if (node.contains(document.activeElement)) {
+ // After the commit, when the row's replacement (if any) is in the document.
+ queueMicrotask(() => onFocusLost(board.id));
+ }
+ };
+ },
+ [board.id, onFocusLost]
+ );
+
const dragPreviewStyle = useMemo(
() =>
dragOrigin
@@ -201,6 +221,8 @@ export const GalleryBoardRow = ({
return (
<Box
+ ref={setRowRef}
+ data-board-row={board.id}
// 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}
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.tsx
index 22ac74d6e2..10ac097187 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
@@ -43,6 +43,7 @@ vi.mock('react-i18next', () => ({
}));
const actions = {
+ archiveBoard: vi.fn(() => Promise.resolve()),
createBoard: vi.fn(() => Promise.resolve(true)),
moveBoard: vi.fn(() => Promise.resolve()),
selectBoard: vi.fn(),
@@ -463,6 +464,86 @@ describe('GalleryBoardsPanel', () => {
});
});
+ describe('focus after a board moves', () => {
+ it('follows a board archived from its menu into the Archived group', async () => {
+ await renderPanel(galleryWithFacadesIn('p1'));
+ const archive = await openMenuItem('widgets.gallery.archiveBoard');
+ actions.archiveBoard.mockImplementationOnce(() => {
+ void renderPanel(galleryWithFacadesIn('p1', true) as GalleryStateView);
+
+ return Promise.resolve();
+ });
+
+ await act(() => userEvent.click(archive));
+
+ await vi.waitFor(() => expect(document.activeElement).toBe(facadesButton()));
+ expect(sectionOf(facadesButton())).toMatch(/^Archived/);
+ });
+
+ const galleryWithFacadesIn = (projectId: string | null, archived = false) => ({
+ ...createGallery(),
+ boards: boards.map((board) => (board.id === 'mine-member' ? { ...board, archived, projectId } : board)),
+ });
+ const menuItem = (label: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((element) => element.textContent === label);
+ const openMenuItem = async (label: string) => {
+ await act(() => userEvent.click(facadesButton(), { button: 'right' }));
+
+ return vi.waitFor(() => {
+ expect(menuItem(label)).toBeDefined();
+ return menuItem(label)!;
+ });
+ };
+ const facadesButton = () => getBoardRows().find((button) => button.textContent?.startsWith('Façades'))!;
+ const sectionOf = (element: Element) =>
+ element.closest('[data-scope="collapsible"][data-part="root"]')?.querySelector('[data-part="trigger"]')
+ ?.textContent;
+
+ it('follows the board to its new tier', async () => {
+ await renderPanel(galleryWithFacadesIn('p1'));
+ facadesButton().focus();
+
+ await renderPanel(galleryWithFacadesIn(null) as GalleryStateView);
+ await act(() => Promise.resolve());
+
+ expect(document.activeElement).toBe(facadesButton());
+ expect(sectionOf(facadesButton())).toMatch(/^Library/);
+ });
+
+ it('follows a board moved from its menu once the menu has closed', async () => {
+ await renderPanel(galleryWithFacadesIn('p1'));
+ const menuItem = (label: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (element) => element.textContent === label
+ );
+ await act(() => userEvent.click(facadesButton(), { button: 'right' }));
+ const moveTo = await vi.waitFor(() => {
+ expect(menuItem('widgets.gallery.moveBoard')).toBeDefined();
+ return menuItem('widgets.gallery.moveBoard')!;
+ });
+ await act(() => userEvent.click(moveTo));
+ const library = await vi.waitFor(() => {
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (element) => element.textContent === 'Library'
+ );
+ expect(item).toBeDefined();
+ return item!;
+ });
+
+ // As in the app, the move patches the board lists at once: the row leaves while the menu is still open.
+ actions.moveBoard.mockImplementationOnce(() => {
+ void renderPanel(galleryWithFacadesIn(null) as GalleryStateView);
+
+ return Promise.resolve();
+ });
+ await act(() => userEvent.click(library));
+ expect(actions.moveBoard).toHaveBeenCalledExactlyOnceWith('mine-member', null, 'Library');
+
+ await vi.waitFor(() => expect(document.activeElement).toBe(facadesButton()));
+ expect(sectionOf(facadesButton())).toMatch(/^Library/);
+ });
+ });
+
it('names another project inbox for assistive tech while the visible row says Inbox', async () => {
await renderPanel(createGallery({ showOtherProjectBoards: true }));
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx
index 28d3df3c4e..b9dd99f694 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx
@@ -151,8 +151,6 @@ export const GalleryBoardsPanel = () => {
setBoardMenuTarget({ board, x, y });
}, []);
- const handleBoardMenuClose = useCallback(() => setBoardMenuTarget(null), []);
-
const handleToggleSection = useCallback(
(sectionId: GalleryBoardSectionId, isOpen: boolean) => {
const nextSections = isOpen
@@ -170,6 +168,36 @@ export const GalleryBoardsPanel = () => {
const isBoardListUnavailable = boardsState.status === 'error';
const isBoardListSettled = boardsState.status !== 'loading' && !isBoardListUnavailable;
const focusBoardList = useCallback(() => focusVisibleOperable(boardsViewportRef.current), []);
+ // A board's row wherever it is now: a move remounts it under its new tier. Without one, the list keeps focus.
+ const focusBoardRow = useCallback(
+ (boardId: string) => {
+ const row = boardsViewportRef.current?.querySelector<HTMLElement>(
+ `[data-board-row="${CSS.escape(boardId)}"] button[type="button"]:not(.board-row-actions)`
+ );
+
+ if (row) {
+ row.focus();
+ } else {
+ focusBoardList();
+ }
+ },
+ [focusBoardList]
+ );
+ // A move or archive from the menu takes the row away while the menu still holds focus, and with it the button the
+ // menu would hand focus back to; once it closes, focus goes to the board's row wherever it now is.
+ const relocatingBoardIdRef = useRef<string | null>(null);
+ const handleBoardRelocated = useCallback((boardId: string) => {
+ relocatingBoardIdRef.current = boardId;
+ }, []);
+ const handleBoardMenuClose = useCallback(() => {
+ setBoardMenuTarget(null);
+ const relocatedBoardId = relocatingBoardIdRef.current;
+ relocatingBoardIdRef.current = null;
+
+ if (relocatedBoardId !== null && document.activeElement?.closest('[data-scope="menu"]')) {
+ focusBoardRow(relocatedBoardId);
+ }
+ }, [focusBoardRow]);
const renderRow = (board: GalleryBoard, accessibleName?: string) => (
<GalleryBoardRow
@@ -181,6 +209,7 @@ export const GalleryBoardsPanel = () => {
isMenuOpen={boardMenuTarget?.board.id === board.id}
isSelected={board.id === gallery.selectedBoardId}
loadedItemBoardIds={loadedItemBoardIds}
+ onFocusLost={focusBoardRow}
onOpenMenu={openBoardMenu}
onSelectBoard={handleSelectBoard}
/>
@@ -360,7 +389,11 @@ export const GalleryBoardsPanel = () => {
<ScrollArea.Thumb />
</ScrollArea.Scrollbar>
</ScrollArea.Root>
- <GalleryBoardMenu target={boardMenuTarget} onClose={handleBoardMenuClose} />
+ <GalleryBoardMenu
+ target={boardMenuTarget}
+ onBoardRelocated={handleBoardRelocated}
+ onClose={handleBoardMenuClose}
+ />
<RenameDialog
cancelLabel={t('common.cancel')}
initialName={trimmedSearchTerm}
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.ts
new file mode 100644
index 0000000000..069dec3238
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.ts
@@ -0,0 +1,123 @@
+import type { Project } from '@workbench/projectContracts';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createGalleryBoardReferenceCheck } from './WorkbenchRuntime';
+import { createDraftProject } from './workbenchState';
+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
+
+const withGallery = (project: Project, values: Record<string, unknown>, queueBoardIds: string[] = []): Project => {
+ const state = { ...createInitialWorkbenchState(), activeProjectId: project.id, projects: [project] };
+ const [patched] = workbenchReducer(state, {
+ projectId: project.id,
+ type: 'patchWidgetValues',
+ values,
+ widgetId: 'gallery',
+ }).projects;
+
+ return {
+ ...patched!,
+ queue: {
+ ...patched!.queue,
+ items: queueBoardIds.map(
+ (galleryBoardId, index) =>
+ ({
+ snapshot: { galleryBoardId },
+ status: index === 0 ? 'pending' : 'completed',
+ }) as Project['queue']['items'][number]
+ ),
+ },
+ };
+};
+
+const createStore = (projects: Project[], hasHydrated = true) => {
+ let snapshot = { hasHydrated, projects };
+ const listeners = new Set<() => void>();
+ const reconcileDeletedBoardOutcome = vi.fn();
+
+ return {
+ commands: { gallery: { reconcileDeletedBoardOutcome } },
+ getSnapshot: () => snapshot,
+ reconcileDeletedBoardOutcome,
+ set: (next: Partial<typeof snapshot>) => {
+ snapshot = { ...snapshot, ...next };
+ listeners.forEach((listener) => listener());
+ },
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+ };
+};
+
+const settle = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+const reconciled = (store: ReturnType<typeof createStore>) =>
+ store.reconcileDeletedBoardOutcome.mock.calls.map(([outcome]) => (outcome as { boardId: string }).boardId);
+
+beforeEach(() => {
+ accountLifecycle.activate('board-reference-check-test');
+});
+
+describe('createGalleryBoardReferenceCheck', () => {
+ it('clears the boards loaded projects name that the server says are gone, asking about each once', async () => {
+ const first = createDraftProject([]);
+ const second = createDraftProject([first]);
+ const store = createStore(
+ [
+ withGallery(first, { autoAddBoardId: 'kept', projectBoardId: 'own-inbox', selectedBoardId: 'gone' }),
+ // Its own inbox is not asked about, nor the board a finished result went to.
+ withGallery(second, { projectBoardId: 'own-inbox-2', selectedBoardId: 'own-inbox-2' }, ['gone', 'finished']),
+ ],
+ false
+ );
+ const boardExists = vi.fn((boardId: string) =>
+ boardId === 'unreachable' ? Promise.reject(new TypeError('offline')) : Promise.resolve(boardId === 'kept')
+ );
+
+ createGalleryBoardReferenceCheck(store as never, boardExists);
+ // Nothing is asked before the session is loaded.
+ expect(boardExists).not.toHaveBeenCalled();
+
+ store.set({ hasHydrated: true });
+ await settle();
+
+ expect(boardExists.mock.calls.map(([boardId]) => boardId).sort()).toEqual(['gone', 'kept']);
+ expect(reconciled(store)).toEqual(['gone']);
+ expect(store.reconcileDeletedBoardOutcome).toHaveBeenCalledWith(
+ expect.objectContaining({ deletedImageNames: [], deletedVideoNames: [] })
+ );
+
+ // A project opened later is checked as it arrives; an unanswered question clears nothing.
+ const third = withGallery(createDraftProject([first, second]), { autoAddBoardId: 'unreachable' }, ['also-gone']);
+ boardExists.mockClear();
+ store.set({ projects: [...store.getSnapshot().projects, third] });
+ await settle();
+
+ expect(boardExists.mock.calls.map(([boardId]) => boardId).sort()).toEqual(['also-gone', 'unreachable']);
+ expect(reconciled(store)).toEqual(['gone', 'also-gone']);
+ });
+
+ it('acts on no answer that arrives after the workbench is gone', async () => {
+ const project = withGallery(createDraftProject([]), { selectedBoardId: 'gone' });
+ const store = createStore([project]);
+ let answer: (exists: boolean) => void = () => undefined;
+ const check = createGalleryBoardReferenceCheck(
+ store as never,
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ })
+ );
+
+ check.dispose();
+ answer(false);
+ await settle();
+
+ expect(store.reconcileDeletedBoardOutcome).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
index b50f266bd6..0cef435f9f 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
@@ -1,13 +1,21 @@
import type { ReactNode } from 'react';
+import { galleryBoardExists } from '@features/gallery/queries';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { useState } from 'react';
+import type { WorkbenchInternalStore } from './workbenchStore';
+
import { createCanvasDimsSync } from './canvasDimsSync';
import { createWorkbenchFocusController, FocusRegionProvider } from './focusRegions';
import { createShortcutHintSources, ShortcutHintSourcesProvider } from './hotkeys/hintSources';
import { useWorkbenchInternalStore, useWorkbenchQueries, useWorkbenchSubscription } from './WorkbenchContext';
+import { getProjectGalleryBoardReferences } from './workbenchState';
/** Workbench-owned lifecycle adapter for aggregate-local synchronization. Cross-module adapters are constructed by App. */
export const WorkbenchRuntime = () => {
@@ -15,15 +23,87 @@ export const WorkbenchRuntime = () => {
useMountEffect(() => {
const canvasDimsSync = createCanvasDimsSync(store);
+ const boardReferenceCheck = createGalleryBoardReferenceCheck(store);
return () => {
canvasDimsSync.dispose();
+ boardReferenceCheck.dispose();
};
});
return null;
};
+/**
+ * Clears what each project loaded into the workbench says about boards that are gone. A board can go while the project
+ * is not open — deleted from another tab, or with a project deleted from the Launchpad — and the project's saved
+ * selection, auto-add board and unfinished queue items would keep naming it, sending results to a board that no longer
+ * exists. Each project is checked once, as it is loaded, and each board it names is asked about once.
+ */
+export const createGalleryBoardReferenceCheck = (
+ store: Pick<WorkbenchInternalStore, 'commands' | 'getSnapshot' | 'subscribe'>,
+ boardExists: (boardId: string, signal?: AbortSignal) => Promise<boolean> = galleryBoardExists
+): { dispose: () => void } => {
+ const owner = captureAccountScope();
+ const lifetime = new AbortController();
+ const signal = AbortSignal.any([owner.signal, lifetime.signal]);
+ const checkedProjectIds = new Set<string>();
+ const askedBoardIds = new Set<string>();
+ let checkedProjects: unknown = null;
+
+ const ask = (boardId: string) => {
+ askedBoardIds.add(boardId);
+ boardExists(boardId, signal)
+ .then((exists) => {
+ if (!exists && !signal.aborted && isAccountScopeCurrent(owner)) {
+ store.commands.gallery.reconcileDeletedBoardOutcome({
+ boardId,
+ deletedBoardImageNames: [],
+ deletedBoardVideoNames: [],
+ deletedImageNames: [],
+ deletedVideoNames: [],
+ failedImageNames: [],
+ failedVideoNames: [],
+ });
+ }
+ })
+ // Unanswered says nothing about the board; it stays named.
+ .catch(() => undefined);
+ };
+
+ // Every edit notifies; only a change to the set of loaded projects can bring one in to check.
+ const check = () => {
+ const { hasHydrated, projects } = store.getSnapshot();
+
+ if (!hasHydrated || projects === checkedProjects || signal.aborted) {
+ return;
+ }
+
+ checkedProjects = projects;
+
+ for (const project of projects) {
+ if (checkedProjectIds.has(project.id)) {
+ continue;
+ }
+
+ checkedProjectIds.add(project.id);
+ getProjectGalleryBoardReferences(project)
+ .filter((boardId) => !askedBoardIds.has(boardId))
+ .forEach(ask);
+ }
+ };
+
+ check();
+ const unsubscribe = store.subscribe(check);
+
+ return {
+ dispose: () => {
+ unsubscribe();
+ lifetime.abort();
+ },
+ };
+};
+
/**
* Owns workbench focus for everything below it — the shell and the hotkey runtime read the same target. Focus is
* transient: it is forgotten, along with any focus move still in flight, when the project on screen changes, the
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 6fbc76e08c..49a97f37dd 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -660,6 +660,11 @@ export const placeBoardInProject = async (
});
};
+/** The project a board is in; null is the Library. */
+export const getBoardProjectId = async (boardId: string, signal?: AbortSignal): Promise<string | null> =>
+ (await apiFetchJson<{ project_id?: string | null }>(`${BOARDS_BASE}/${encodeURIComponent(boardId)}`, { signal }))
+ .project_id ?? null;
+
/**
* Drop a staging board whose project was never created. `include_images=false` deliberately: the
* restore deletes its own identities one by one, and a generation that landed on the board
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
index c97cc5b702..719a257104 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
@@ -33,6 +33,7 @@ const transport = vi.hoisted(() => ({
deleteStagingBoard: vi.fn(() => Promise.resolve()),
findExistingImageNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),
findExistingVideoNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),
+ getBoardProjectId: vi.fn((): Promise<string | null> => Promise.resolve(null)),
mimeForEntryName: () => 'image/png',
placeBoardInProject: vi.fn(() => Promise.resolve()),
starImages: vi.fn(() => Promise.resolve({ failed: [] as string[] })),
@@ -353,6 +354,21 @@ describe('duplicateProjectRecord', () => {
expect(transport.deleteStagingBoard).not.toHaveBeenCalled();
});
+ it('refreshes board lists even when placing the boards is cancelled part way', async () => {
+ transport.placeBoardInProject.mockRejectedValueOnce(new DOMException('cancelled', 'AbortError'));
+ transport.createStagingBoard.mockResolvedValueOnce('staging-board').mockResolvedValueOnce('member-staging');
+
+ await expect(
+ duplicateProject.duplicateProjectRecord({
+ boards: [...inboxOf([]), { archived: false, board_id: 'old', is_inbox: false, items: [], name: 'Old' }],
+ owner,
+ record: sourceRecord(),
+ })
+ ).rejects.toThrow('cancelled');
+
+ expect(api.invalidateBoardLists).toHaveBeenCalledExactlyOnceWith(owner);
+ });
+
it('stages and claims the inbox even when it is empty, copying nothing', async () => {
await duplicateProject.duplicateProjectRecord({ boards: inboxOf([]), owner, record: sourceRecord() });
@@ -413,6 +429,11 @@ describe('duplicateProjectRecord', () => {
expect(transport.deleteArchiveImages).toHaveBeenCalledWith(['copy-shared.png'], owner.signal);
expect(transport.deleteArchiveVideos).toHaveBeenCalledWith(['copy-clip.mp4'], owner.signal);
expect(transport.deleteStagingBoard).toHaveBeenCalledWith('staging-board', owner.signal);
+ // Uploads announce their board, so lists can already show the staging board it deleted.
+ expect(api.invalidateBoardLists).toHaveBeenCalledExactlyOnceWith(owner);
+ expect(api.invalidateBoardLists.mock.invocationCallOrder[0]).toBeGreaterThan(
+ transport.deleteStagingBoard.mock.invocationCallOrder[0]!
+ );
});
/** Retain media for unproven create outcomes; GET 404 can race commit. */
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
index 76cc1f75dc..f01bdb35b1 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
@@ -220,7 +220,9 @@ export const duplicateProjectRecord = async (
},
};
} catch (error) {
- const rollback = () => rollbackRestoredMedia(ledger, { signal: owner.signal });
+ // The staging boards it deletes may already be listed: uploads to them announce themselves.
+ const rollback = () =>
+ rollbackRestoredMedia(ledger, { signal: owner.signal }).finally(() => invalidateBoardLists(owner));
// Before the create was even attempted nothing is ambiguous: whatever was staged or copied is ours to drop.
if (!didAttemptProjectCreate && isAccountScopeCurrent(owner)) {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts
index defe2fc1cf..d344b87e7d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts
@@ -45,7 +45,10 @@ describe('placeMemberBoards', () => {
{ board: old, stagingBoardId: 'staged-old' },
{ board: empty, stagingBoardId: 'staged-empty' },
];
- const deps = () => ({ placeBoardInProject: vi.fn(() => Promise.resolve()) });
+ const deps = () => ({
+ getBoardProjectId: vi.fn((): Promise<string | null> => Promise.resolve(null)),
+ placeBoardInProject: vi.fn(() => Promise.resolve()),
+ });
it('moves every board but the inbox into the project as it was', async () => {
const d = deps();
@@ -65,6 +68,15 @@ describe('placeMemberBoards', () => {
expect(d.placeBoardInProject).toHaveBeenCalledTimes(2);
});
+ it('counts a move whose answer was lost when the board is in the project after all', async () => {
+ const d = deps();
+ d.placeBoardInProject.mockRejectedValueOnce(new TypeError('response lost'));
+ d.getBoardProjectId.mockResolvedValueOnce('p1');
+
+ await expect(placeMemberBoards(staged, 'p1', d)).resolves.toEqual([]);
+ expect(d.getBoardProjectId).toHaveBeenCalledExactlyOnceWith('staged-old', undefined);
+ });
+
it('ends the placement when the operation was cancelled', async () => {
const d = deps();
d.placeBoardInProject.mockRejectedValueOnce(new DOMException('gone', 'AbortError'));
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts
index c9a7848210..4651f411e3 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts
@@ -2,7 +2,7 @@ import type { InvkBoard } from './board';
import type { RestoredMediaLedger } from './restoreProjectMedia';
import type { InvkBoardIssue } from './transfer';
-import { createStagingBoard, isRequestCancellation, placeBoardInProject } from './assetTransport';
+import { createStagingBoard, getBoardProjectId, isRequestCancellation, placeBoardInProject } from './assetTransport';
/**
* A project's boards travel as a set, but only the inbox rides the project create: the server claims it in the same
@@ -18,6 +18,7 @@ export interface StagedBoard {
}
export interface MemberBoardPlacementDeps {
+ getBoardProjectId?: typeof getBoardProjectId;
/** After each board settles, placed or not. */
onProgress?: (completed: number, total: number) => void;
placeBoardInProject?: typeof placeBoardInProject;
@@ -62,7 +63,20 @@ export const placeMemberBoards = async (
deps: MemberBoardPlacementDeps = {}
): Promise<InvkBoardIssue[]> => {
const place = deps.placeBoardInProject ?? placeBoardInProject;
+ const readProjectId = deps.getBoardProjectId ?? getBoardProjectId;
const issues: InvkBoardIssue[] = [];
+ /** A move with no usable answer may still have been made; the board says where it is. */
+ const wasPlaced = async (stagingBoardId: string): Promise<boolean> => {
+ try {
+ return (await readProjectId(stagingBoardId, deps.signal)) === projectId;
+ } catch (error) {
+ if (isRequestCancellation(error)) {
+ throw error;
+ }
+
+ return false;
+ }
+ };
const members = staged.filter(({ board }) => !board.isInbox);
for (const [index, { board, stagingBoardId }] of members.entries()) {
@@ -73,7 +87,9 @@ export const placeMemberBoards = async (
throw error;
}
- issues.push({ name: board.name });
+ if (!(await wasPlaced(stagingBoardId))) {
+ issues.push({ name: board.name });
+ }
}
deps.onProgress?.(index + 1, members.length);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 82a260dc3e..f5217fc4bb 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -61,6 +61,7 @@ const transport = vi.hoisted(() => ({
findExistingImageNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
findExistingVideoNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
mimeForEntryName: () => 'image/png',
+ getBoardProjectId: vi.fn((): Promise<string | null> => Promise.resolve(null)),
placeBoardInProject: vi.fn(() => Promise.resolve()),
starImages: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),
starVideos: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index f074a28158..5eb29714b1 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -385,7 +385,9 @@ export const importProjectFile = async (
}
// Media-free legacy JSON imports do not load restore rollback.
if (ledger !== null && restoreMedia !== null) {
- const rollback = () => restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal });
+ // The staging boards it deletes may already be listed: uploads to them announce themselves.
+ const rollback = () =>
+ restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal }).finally(() => invalidateBoardLists(owner));
if (!didAttemptProjectCreate && isAccountScopeCurrent(owner)) {
await rollback();
} else {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index 81799c53bb..bd7f087ef0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -228,6 +228,7 @@ vi.mock('@features/gallery/queries', () => ({
isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),
flattenGalleryItemsData: (data: InfiniteData<GalleryItemsPage, number> | undefined) =>
data?.pages.flatMap((page) => page.items) ?? [],
+ galleryBoardExists: () => Promise.resolve(true),
galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),
getGalleryListingBoardsQuery: () => ({}),
galleryStarredStripOptions: (query: { boardId: string; starred?: boolean }) => ({
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 2e860c44ae..6112f9212a 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -3021,6 +3021,31 @@ const removeGalleryItemsFromAllProjects = (
return didChange ? { ...state, projects } : state;
};
+/**
+ * The boards a project's gallery and unfinished queue items will act on: its selected board, its auto-add board and the
+ * boards pending or running results are bound for. Its own inbox is left out: a draft project's inbox exists only once
+ * the project does, and it goes only with the project.
+ */
+export const getProjectGalleryBoardReferences = (project: Project): string[] => {
+ const values = getWidgetValues(project, 'gallery');
+ const { autoAddBoardId } = getGallerySettings(values);
+ const references = new Set<string>();
+
+ for (const boardId of [
+ values.selectedBoardId,
+ autoAddBoardId,
+ ...project.queue.items
+ .filter((item) => item.status === 'pending' || item.status === 'running')
+ .map((item) => item.snapshot.galleryBoardId),
+ ]) {
+ if (typeof boardId === 'string' && boardId !== GALLERY_AUTO_ADD_FOLLOW && boardId !== values.projectBoardId) {
+ references.add(boardId);
+ }
+ }
+
+ return [...references];
+};
+
const reconcileDeletedGalleryBoard = (
state: WorkbenchState,
boardId: string,
diff --git a/tests/app/routers/test_boards_projects.py b/tests/app/routers/test_boards_projects.py
index 71570698b2..4c3eee9e61 100644
--- a/tests/app/routers/test_boards_projects.py
+++ b/tests/app/routers/test_boards_projects.py
@@ -14,6 +14,7 @@ from fastapi import status
from fastapi.testclient import TestClient
from sqlalchemy import insert
+from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.database.database import Database
from invokeai.app.services.shared.database.schema.boards import shared_boards
from tests.app.routers.conftest import _auth, _create_board
@@ -41,6 +42,26 @@ def _move(client: TestClient, token: str, board_id: str, project_id: str | None)
return client.patch(f"/api/v1/boards/{board_id}", json={"project_id": project_id}, headers=_auth(token))
+def test_reading_a_board_is_a_404_only_when_the_board_is_gone(
+ client: TestClient, user1_token: str, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch
+):
+ """Clients take a 404 here as the board being deleted and clear what names it, so a failure is never one."""
+ board_id = _create_board(client, user1_token, "Kept")
+ assert client.delete(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).status_code == status.HTTP_200_OK
+ assert client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).status_code == 404
+
+ kept = _create_board(client, user1_token, "Kept")
+
+ def fail(board_id: str) -> None:
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(mock_invoker.services.boards, "get_dto", fail)
+ unraised = TestClient(client.app, raise_server_exceptions=False)
+ response = unraised.get(f"/api/v1/boards/{kept}", headers=_auth(user1_token))
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+
+
# --- creating ---------------------------------------------------------------------------------
diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.py
index a53e57da8c..2f2b838c21 100644
--- a/tests/app/services/intermediates/test_intermediates_service.py
+++ b/tests/app/services/intermediates/test_intermediates_service.py
@@ -311,6 +311,9 @@ def test_a_project_row_takes_its_cover_from_whichever_of_its_boards_has_the_newe
cursor.execute(
"UPDATE board_images SET created_at = ? WHERE image_name = ?;", (f"2020-01-0{index + 1} 00:00:00", name)
)
+ # The newest board of all, with nothing durable on it: a database that sorts its empty newest first must not
+ # hand the project no cover.
+ invoker.services.board_records.save("Empty", "alice", project_id=project)
_seed_image(invoker, "intermediate.png", project_id=project, size=1)
summary = service.get_summary(