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.

feat(gallery): warn when deleting media that is still in use (#10126)

Josh Corbett6f1fb9b1aaff
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 f5169b1f07..f94c0ad78b 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
@@ -51,13 +51,13 @@ Choose **Delete board** from the board's menu. The confirmation dialog says what
<Image src={deleteBoard} alt="The Delete board dialog with the media it holds, the Also permanently delete its items checkbox, and Cancel and Delete board buttons." width={500} />
* **Delete board** — removes the board and moves everything on it to **Uncategorized**. This is the default.
-* **Also permanently delete its items** — tick it to delete the board's images and videos with it; the button then says how many, such as **Delete board and 99 items**. For a board with 50 items or more, you also type the board's name to confirm.
+* **Also permanently delete its items** — tick it to delete the board's images and videos with it; the button then says how many, such as **Delete board and 99 items**. For a board with 50 items or more, you also type the board's name to confirm; once the check has answered, only the items that will actually be deleted count toward that. Ticking it also checks what still uses the board's media and lists it, as [deleting media](/users-guide/gallery/introduction/#deleting-media) does.
A deleted board cannot be restored, and deleted media cannot be undone. While media is being deleted, a notice says so; when it finishes, another says what was moved or deleted, and how much could not be deleted, if any.
Queued or running jobs that were sending results to the deleted board send them to **Uncategorized** instead. A project's Inbox cannot be deleted from the Gallery; delete the project instead, which also asks what to do with the project's other boards.
-On a multi-user installation, only a board's owner or an administrator can delete it. When an owner deletes a shared board with its media, only their own media is deleted and other people's items move to Uncategorized; an administrator's deletion removes everything. If some files cannot be removed, those items are kept in Uncategorized and a warning says how many.
+On a multi-user installation, only a board's owner or an administrator can delete it. When an owner deletes a shared board with its media, only their own media is deleted and other people's items move to Uncategorized; once the check of what uses the media has answered, the dialog names only the owner's items, such as **Also permanently delete your 2 items** and **Delete board and your 2 items**, and when none of the media is theirs it says that all of it moves to Uncategorized. An administrator's deletion removes everything. If some files cannot be removed, those items are kept in Uncategorized and a warning says how many.
## The media menu
diff --git a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx
index 91a31243a6..8da5ae836d 100644
--- a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx
+++ b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx
@@ -164,7 +164,16 @@ Drag items onto a board in the board list; if the list is hidden, it opens while
Press **Delete** (or **Backspace**), choose **Delete image**, **Delete video** or **Delete selection** from the menu, or use the delete button in the selection bar. Deleting permanently removes the items from every board and from disk, and cannot be undone. A confirmation asks first, counting the images and videos and showing their thumbnails. When you delete a single item you can see, you can tick **Don't ask again when deleting one item** and confirm to stop asking for those (cancelling leaves it on); deleting several items, or an item that is not on screen, always asks. You can turn the confirmation back on, or off, with **Confirm image deletion** in Settings under Gallery.
-When the open project still uses something you are deleting, for example as a canvas layer, a reference image, an upscale or video input, or in a workflow, the confirmation always appears and lists where, even if you turned confirmations off. Only the open project's current work is checked: other projects, undo history and canvas snapshots are not, so check before you delete media you still need there. If deleting is interrupted, InvokeAI cleans up any leftover files the next time it starts.
+Before deleting, InvokeAI checks what still uses the items, and the confirmation shows **Checking where this media is used…** until it knows. It then says how many of the items are in use, such as **3 of these 5 images are still in use**, and lists where:
+
+* **This project** and your other projects, with the places in each: canvas layers, staged canvas results, canvas snapshots, reference images, the upscale or video input, project workflows, and **Elsewhere in the project** for anything else in the project that refers to them. A project that could not be opened to check is listed with the number of items it holds.
+* Workflows saved in your Library, the legacy editor's saved state, and projects kept for repair.
+* Your queued or running jobs that use the items. Those jobs fail if you delete the media.
+* **Other accounts' work**, on a server with several accounts: how many items other people's projects, workflows or jobs use, without saying whose.
+
+When something uses the items, the confirmation always appears, even if you turned confirmations off; deleting a single visible item without confirmation waits a few seconds for the check and still asks when it finds a use or cannot finish. **Delete** stays available, so you can delete anyway, and anything that used the media then points at a missing file. In the projects InvokeAI opens to check, a Gallery selection or image search, the recent results strip, the compare image, a workflow's last run and the last submitted Generate, Upscale or Video graph do not count as uses; neither do this session's queue, run log and undo history. A project open in this tab is checked as you have it now, unsaved changes included; if it was saved from another tab or device since this tab last loaded or saved it, the saved version is checked as well, and a use in either counts; if the saved version cannot be checked, the project keeps every item the server found in it, with a note saying so. A project it could not open to check (it is very large, could not be read, or is past the few it opens) is listed with every item it mentions, these included, and so is other accounts' work. If the check cannot reach the server, or too many items are selected to check them all, the confirmation says so: only the projects open in this tab were checked. When the check fails, **Retry** runs it again. With confirmations off, a deletion that needs to ask while another confirmation is open is not carried out, and a notice says to answer the open one first, or to wait for a deletion already under way.
+
+If deleting is interrupted, InvokeAI cleans up any leftover files the next time it starts.
## Related pages
diff --git a/invokeai/app/api/routers/_limits.py b/invokeai/app/api/routers/_limits.py
index ffd23e4e14..b004410ad9 100644
--- a/invokeai/app/api/routers/_limits.py
+++ b/invokeai/app/api/routers/_limits.py
@@ -8,3 +8,14 @@ is allowed to do (`_access.py`) or how a listing is paged (`shared/pagination.py
# copy each — so one request's cost is unbounded without a cap. The frontend's largest batch is a
# project board being duplicated, which its own archive limits already keep well under this.
MAX_COPY_BATCH_SIZE = 1000
+
+# Every name in a batch body costs at least one DB lookup, so an unbounded list lets an
+# authenticated client pin a worker with a single request.
+#
+# "At least one" is doing real work in that sentence. The authorization helpers in _access.py
+# short-circuit for an admin (no query) and a direct owner (one), but a user acting on someone
+# else's item on a board they share costs three indexed reads per name: the item's owner, its
+# board, and that board's access facts. That is the case the bound has to hold, and it is why no
+# route gets a laxer one: the oversized selections this cap rejects are split client-side instead.
+MAX_IMAGE_BATCH_SIZE = 1000
+MAX_VIDEO_BATCH_SIZE = 1000
diff --git a/invokeai/app/api/routers/board_images.py b/invokeai/app/api/routers/board_images.py
index ed5586308c..702ca0f402 100644
--- a/invokeai/app/api/routers/board_images.py
+++ b/invokeai/app/api/routers/board_images.py
@@ -11,8 +11,9 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_image_action as _assert_image_action,
)
+from invokeai.app.api.routers._limits import MAX_IMAGE_BATCH_SIZE
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
-from invokeai.app.api.routers.images import MAX_IMAGE_BATCH_SIZE, ImageName
+from invokeai.app.api.routers.images import ImageName
from invokeai.app.services.board_access.board_access_common import ItemAction
from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException
from invokeai.app.services.images.images_common import AddImagesToBoardResult, RemoveImagesFromBoardResult
diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.py
index 84c8072e5f..6e01f4e693 100644
--- a/invokeai/app/api/routers/boards.py
+++ b/invokeai/app/api/routers/boards.py
@@ -167,13 +167,7 @@ def delete_board(
) -> DeleteBoardResult:
"""Deletes a board: its owner's, or an admin's, to do"""
access = _assert_board_changes(board_id, current_user, [BoardAction.Delete])
-
- # An owner deleting their board, admin or not, only deletes their own contributions, so what
- # other users put on a shared board is preserved (it cascades to "uncategorized" via the FK on
- # board_videos / board_images). Only an admin overriding, deleting someone else's board,
- # deletes everything on it; that is the case the DTO reports as `admin_override`, so the client
- # can warn before it.
- cascade_user_id: Optional[str] = None if access.admin_override else current_user.user_id
+ cascade_user_id = access.media_deleted_with_board(current_user.user_id)
deleted_images: list[str] = []
deleted_videos: list[str] = []
board_deleted = False
diff --git a/invokeai/app/api/routers/gallery.py b/invokeai/app/api/routers/gallery.py
index a7361b1139..9d4256c753 100644
--- a/invokeai/app/api/routers/gallery.py
+++ b/invokeai/app/api/routers/gallery.py
@@ -1,12 +1,16 @@
from datetime import date
-from typing import Optional
+from typing import Annotated, Optional, Self
-from fastapi import HTTPException, Query
+from fastapi import Body, HTTPException, Query
from fastapi.routing import APIRouter
+from pydantic import BaseModel, Field, model_validator
from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers._access import assert_board_changes
+from invokeai.app.api.routers._limits import MAX_IMAGE_BATCH_SIZE, MAX_VIDEO_BATCH_SIZE
from invokeai.app.api.routers.images import _assert_board_read_access
+from invokeai.app.services.board_access.board_access_common import BoardAction
from invokeai.app.services.gallery.gallery_base import GalleryMediaKind
from invokeai.app.services.gallery.gallery_common import (
GalleryItem,
@@ -14,6 +18,7 @@ from invokeai.app.services.gallery.gallery_common import (
GalleryItemLocation,
GalleryItemNames,
GalleryItemNamesResult,
+ GalleryMediaUsage,
)
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatedResults, SQLiteDirection
@@ -29,6 +34,37 @@ BoardIdQuery = Query(
"administrator), or 'all' for those items plus the items on every non-archived board the current user may read.",
)
+UsageMediaName = Annotated[str, Field(min_length=1, max_length=255)]
+
+
+class GalleryMediaUsageRequest(BaseModel):
+ """The media to check: named images and videos, or every item on one board."""
+
+ image_names: list[UsageMediaName] = Field(
+ default_factory=list,
+ max_length=MAX_IMAGE_BATCH_SIZE,
+ description="Images to check. Those the caller may not delete, and unknown ones, are ignored, as "
+ "`POST /images/delete` skips them.",
+ )
+ video_names: list[UsageMediaName] = Field(
+ default_factory=list,
+ max_length=MAX_VIDEO_BATCH_SIZE,
+ description="Videos to check. Those the caller may not delete, and unknown ones, are ignored, as "
+ "`POST /videos/delete` skips them.",
+ )
+ board_id: Optional[str] = Field(
+ default=None,
+ description="Check the images and videos `DELETE /boards/{board_id}?include_images=true` would delete, under "
+ "the same access rules. Not combined with names.",
+ )
+
+ @model_validator(mode="after")
+ def _one_scope(self) -> Self:
+ if self.board_id is not None and (self.image_names or self.video_names):
+ raise ValueError("Check either names or a board, not both")
+ return self
+
+
MediaKindQuery = Query(
default=None,
description="List only images ('image') or only videos ('video'). Omit to include both. Totals, positions and "
@@ -266,3 +302,23 @@ def get_gallery_item_names(
)
except Exception:
raise HTTPException(status_code=500, detail="Failed to get gallery item names")
+
+
+@gallery_router.post("/usage", operation_id="get_gallery_media_usage", response_model=GalleryMediaUsage)
+def get_gallery_media_usage(
+ current_user: CurrentUserOrDefault,
+ request: GalleryMediaUsageRequest = Body(description="The media to check"),
+) -> GalleryMediaUsage:
+ """Reports what still uses media before it is deleted: the caller's saved documents and active queue work by
+ name, other accounts' as counts. Deleting stays a separate request; this only reads."""
+ gallery = ApiDependencies.invoker.services.gallery
+ if request.board_id is None:
+ return gallery.get_media_usage(
+ request.image_names, request.video_names, current_user.user_id, current_user.is_admin
+ )
+ access = assert_board_changes(request.board_id, current_user, [BoardAction.Delete])
+ if request.board_id in ApiDependencies.invoker.services.board_records.get_inbox_board_ids([request.board_id]):
+ raise HTTPException(status_code=409, detail="This board is the project's inbox; delete the project instead")
+ return gallery.get_board_media_usage(
+ request.board_id, current_user.user_id, access.media_deleted_with_board(current_user.user_id)
+ )
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 622a364ed1..2602928854 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -31,7 +31,7 @@ from invokeai.app.api.routers._access import (
item_action_for_changes,
redact_project_ids,
)
-from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE
+from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE, MAX_IMAGE_BATCH_SIZE
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.invocations.fields import MetadataField
from invokeai.app.services.board_access.board_access_common import ItemAction
@@ -62,16 +62,6 @@ images_router = APIRouter(prefix="/v1/images", tags=["images"])
# images are immutable; set a high max-age
IMAGE_MAX_AGE = 31536000
-# Every name in a batch body costs at least one DB lookup, so an unbounded list lets an
-# authenticated client pin a worker with a single request. Mirrors MAX_VIDEO_BATCH_SIZE
-# in the videos router.
-#
-# "At least one" is doing real work in that sentence. The authorization helpers in _access.py
-# short-circuit for an admin (no query) and a direct owner (one), but a user acting on someone
-# else's item on a board they share costs three indexed reads per name: the item's owner, its
-# board, and that board's access facts. That is the case the bound has to hold, and it is why no
-# route gets a laxer one: the oversized selections this cap rejects are split client-side instead.
-MAX_IMAGE_BATCH_SIZE = 1000
# Names are UUID-derived filenames; the bound only exists to keep a hostile body from
# turning into megabytes of SQL parameters.
ImageName = Annotated[str, StringConstraints(max_length=255)]
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index e01a18fb33..793541afe3 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -38,7 +38,7 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_video_read_access as _assert_video_read_access,
)
-from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE
+from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE, MAX_VIDEO_BATCH_SIZE
from invokeai.app.api.routers.images import WorkflowAndGraphResponse
from invokeai.app.invocations.fields import MetadataField, MetadataFieldValidator
from invokeai.app.services.board_access.board_access_common import ItemAction
@@ -135,7 +135,6 @@ MAX_CONCURRENT_VIDEO_UPLOADS = 2
# Per-user bound (multiuser mode only): keeps one tenant's slow uploads from holding
# every global slot and starving the other users into 429s.
MAX_CONCURRENT_VIDEO_UPLOADS_PER_USER = 1
-MAX_VIDEO_BATCH_SIZE = 1000
VideoName = Annotated[str, StringConstraints(max_length=255)]
diff --git a/invokeai/app/services/board_access/board_access_common.py b/invokeai/app/services/board_access/board_access_common.py
index 9c62ac3edc..e22c156b32 100644
--- a/invokeai/app/services/board_access/board_access_common.py
+++ b/invokeai/app/services/board_access/board_access_common.py
@@ -113,6 +113,17 @@ class BoardAccess:
"""Whether admin rights give the caller more than their own role does."""
return self.is_admin and self.role is not BoardRole.Owner
+ def media_deleted_with_board(self, user_id: str) -> Optional[str]:
+ """Whose media the caller (`user_id`) deletes by deleting the board with its media: their own, or everyone's
+ (None).
+
+ An owner deleting their board, admin or not, only deletes their own contributions, so what other users put on
+ a shared board is preserved (it cascades to "uncategorized" via the FK on board_videos / board_images). Only an
+ admin overriding, deleting someone else's board, deletes everything on it; that is the case the DTO reports as
+ `admin_override`, so the client can warn before it.
+ """
+ return None if self.admin_override else user_id
+
def allows(self, action: BoardAction) -> bool:
return not (self.is_inbox and action in _MANAGED_BY_PROJECT) and self.role_allows(action)
diff --git a/invokeai/app/services/gallery/gallery_base.py b/invokeai/app/services/gallery/gallery_base.py
index a98a607a45..b02deb7213 100644
--- a/invokeai/app/services/gallery/gallery_base.py
+++ b/invokeai/app/services/gallery/gallery_base.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from collections.abc import Collection
from typing import Literal, Optional
from invokeai.app.services.gallery.gallery_common import (
@@ -8,6 +9,7 @@ from invokeai.app.services.gallery.gallery_common import (
GalleryItemLocation,
GalleryItemNames,
GalleryItemNamesResult,
+ GalleryMediaUsage,
)
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.shared.pagination import OffsetPaginatedResults, SQLiteDirection
@@ -132,3 +134,17 @@ class GalleryServiceABC(ABC):
def get_board_media_summaries(self, board_ids: list[str]) -> dict[str, BoardMediaSummary]:
"""Returns covers and media counts for each requested board."""
pass
+
+ @abstractmethod
+ def get_media_usage(
+ self, image_names: Collection[str], video_names: Collection[str], user_id: str, is_admin: bool
+ ) -> GalleryMediaUsage:
+ """What still uses the named media that the caller may delete: the names `POST /images/delete` and
+ `POST /videos/delete` would delete. Other names, unknown ones included, are left out as those skip them."""
+ pass
+
+ @abstractmethod
+ def get_board_media_usage(self, board_id: str, user_id: str, contributor_id: Optional[str]) -> GalleryMediaUsage:
+ """What still uses the media that deleting the board with its media would delete: `contributor_id`'s items on
+ it, or every item when None. The caller (`user_id`) must already be allowed to delete the board."""
+ pass
diff --git a/invokeai/app/services/gallery/gallery_common.py b/invokeai/app/services/gallery/gallery_common.py
index 1b147a13c8..3950a41ddb 100644
--- a/invokeai/app/services/gallery/gallery_common.py
+++ b/invokeai/app/services/gallery/gallery_common.py
@@ -3,7 +3,7 @@
import datetime
from dataclasses import dataclass
from enum import Enum
-from typing import Optional, Union
+from typing import Literal, Optional, Union
from pydantic import BaseModel, Field
@@ -88,6 +88,93 @@ class GalleryItemNames(BaseModel):
total_count: int = Field(description="Total number of items matching the query.")
+# A usage check names at most this many documents (`documents_total` counts them all), and at most this many media
+# names per document or queue entry (their counts are exact).
+MAX_USAGE_DOCUMENTS = 100
+MAX_USAGE_NAMES = 1000
+
+GalleryMediaUsageDocumentKind = Literal["project", "workflow", "legacy_editor", "quarantined_project"]
+
+
+class GalleryMediaUsageDocument(BaseModel):
+ """One of the caller's saved documents that names checked media."""
+
+ kind: GalleryMediaUsageDocumentKind = Field(
+ description="'project': a project's content and the caller's own workspace in it. 'workflow': a library "
+ "workflow. 'legacy_editor': the legacy editor's saved state, all of it as one entry. 'quarantined_project': "
+ "a project kept for repair."
+ )
+ id: str = Field(description="The project or workflow id; 'legacy_editor' for the legacy editor's state.")
+ name: Optional[str] = Field(description="The document's name; null for the legacy editor or a missing document.")
+ image_names: list[str] = Field(
+ description=f"The checked images the document names, sorted; at most {MAX_USAGE_NAMES}."
+ )
+ video_names: list[str] = Field(
+ description=f"The checked videos the document names, sorted; at most {MAX_USAGE_NAMES}."
+ )
+ image_count: int = Field(description="How many checked images the document names, past the list's cap too.")
+ video_count: int = Field(description="How many checked videos the document names, past the list's cap too.")
+ revision: Optional[int] = Field(
+ description="For a project: its content revision when the names were read, as the project read reports it "
+ "(`revision`). Null for other kinds, and for a project the caller does not own."
+ )
+ workspace_revision: Optional[int] = Field(
+ description="For a project: the caller's workspace revision when the names were read, as the project read "
+ "reports it (`workspace.revision`); null while the caller has no workspace in it. Null for other kinds."
+ )
+
+
+class GalleryMediaUsageQueue(BaseModel):
+ """The caller's active queue work that names checked media."""
+
+ item_count: int = Field(
+ description="The caller's active queue items (pending, in progress or waiting, and the completed children of "
+ "an active root) whose sessions name checked media."
+ )
+ image_names: list[str] = Field(
+ description=f"The checked images those items name, sorted; at most {MAX_USAGE_NAMES}."
+ )
+ video_names: list[str] = Field(
+ description=f"The checked videos those items name, sorted; at most {MAX_USAGE_NAMES}."
+ )
+ image_count: int = Field(description="How many checked images those items name, past the list's cap too.")
+ video_count: int = Field(description="How many checked videos those items name, past the list's cap too.")
+
+
+class GalleryMediaUsageOthers(BaseModel):
+ """Other accounts' documents and queue work that name checked media, without identifying them."""
+
+ document_count: int = Field(description="Other accounts' documents naming checked media.")
+ queue_item_count: int = Field(description="Other accounts' active queue items naming checked media.")
+ image_count: int = Field(description="Distinct checked images other accounts' documents or queue work name.")
+ video_count: int = Field(description="Distinct checked videos other accounts' documents or queue work name.")
+
+
+class GalleryMediaUsage(BaseModel):
+ """What still uses media a deletion would remove. Saved documents count conservatively: anything they name,
+ history included."""
+
+ checked_image_count: int = Field(
+ description="Images checked: the requested ones the caller may delete, or the images the board's deletion "
+ "would delete."
+ )
+ checked_video_count: int = Field(
+ description="Videos checked: the requested ones the caller may delete, or the videos the board's deletion "
+ "would delete."
+ )
+ in_use_image_count: int = Field(description="Distinct checked images that anything below names.")
+ in_use_video_count: int = Field(description="Distinct checked videos that anything below names.")
+ documents: list[GalleryMediaUsageDocument] = Field(
+ description=f"The caller's own documents naming checked media, by kind, then name, then id; at most "
+ f"{MAX_USAGE_DOCUMENTS}."
+ )
+ documents_total: int = Field(description="How many of the caller's documents name checked media.")
+ queue: GalleryMediaUsageQueue = Field(description="The caller's own active queue work naming checked media.")
+ other_accounts: GalleryMediaUsageOthers = Field(
+ description="Other accounts' documents and queue work naming checked media, as counts only."
+ )
+
+
@dataclass(frozen=True)
class BoardMediaSummary:
cover_image_name: Optional[str] = None
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index 7731109506..51cc6c1fae 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -1,7 +1,12 @@
+from collections.abc import Collection
+from dataclasses import dataclass, field
from typing import Any, Optional, Sequence
+from invokeai.app.services.board_access.board_access_common import ItemAction, item_allows
from invokeai.app.services.gallery.gallery_base import GalleryMediaKind, GalleryServiceABC
from invokeai.app.services.gallery.gallery_common import (
+ MAX_USAGE_DOCUMENTS,
+ MAX_USAGE_NAMES,
BoardMediaSummary,
GalleryItem,
GalleryItemKind,
@@ -9,15 +14,53 @@ from invokeai.app.services.gallery.gallery_common import (
GalleryItemNames,
GalleryItemNamesResult,
GalleryItemRef,
+ GalleryMediaUsage,
+ GalleryMediaUsageDocument,
+ GalleryMediaUsageDocumentKind,
+ GalleryMediaUsageOthers,
+ GalleryMediaUsageQueue,
)
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.database.database import Database
+from invokeai.app.services.shared.database.queries import Queries
from invokeai.app.services.shared.database.queries.gallery import Filters
+from invokeai.app.services.shared.media_references import MediaKind, MediaReferences
from invokeai.app.services.shared.pagination import OffsetPaginatedResults, SQLiteDirection
from invokeai.app.services.video_records.video_records_common import coerce_media_origin
from invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO
+# A reference index owner: (owner kind, owner account, owner id).
+_Owner = tuple[str, str, str]
+
+_LEGACY_EDITOR_ID = "legacy_editor"
+
+
+def _document_of(owner_kind: str, owner_id: str) -> tuple[GalleryMediaUsageDocumentKind, str]:
+ """The document a reference owner belongs to, as the usage check lists it: a project's content and its
+ workspaces are one project, and the legacy editor's client state is one document however many keys it uses."""
+ if owner_kind in ("project", "project_workspace"):
+ return "project", owner_id
+ if owner_kind == "client_state":
+ return "legacy_editor", _LEGACY_EDITOR_ID
+ if owner_kind == "workflow":
+ return "workflow", owner_id
+ return "quarantined_project", owner_id
+
+
+def _add(references: MediaReferences, kind: MediaKind, name: str) -> None:
+ (references.images if kind == "image" else references.videos).add(name)
+
+
+@dataclass
+class _DocumentUse:
+ names: MediaReferences = field(default_factory=MediaReferences)
+ owners: set[_Owner] = field(default_factory=set)
+
+
+def _capped(names: set[str]) -> list[str]:
+ return sorted(names)[:MAX_USAGE_NAMES]
+
class GalleryService(GalleryServiceABC):
"""A gallery of images and videos as one list (see `queries/gallery.py`)."""
@@ -227,6 +270,138 @@ class GalleryService(GalleryServiceABC):
)
return summaries
+ def get_media_usage(
+ self, image_names: Collection[str], video_names: Collection[str], user_id: str, is_admin: bool
+ ) -> GalleryMediaUsage:
+ checked = MediaReferences(
+ images=self._deletable("image", image_names, user_id, is_admin),
+ videos=self._deletable("video", video_names, user_id, is_admin),
+ )
+ return self._usage(checked, user_id)
+
+ def get_board_media_usage(self, board_id: str, user_id: str, contributor_id: Optional[str]) -> GalleryMediaUsage:
+ # The enumeration `DELETE /boards/{id}?include_images=true` deletes.
+ services = self.__invoker.services
+ images = services.board_image_records.get_all_board_image_names_for_board(
+ board_id, None, None, user_id=contributor_id
+ )
+ videos = services.board_video_records.get_all_board_video_names_for_board(
+ board_id, None, None, user_id=contributor_id
+ )
+ return self._usage(MediaReferences(images=set(images), videos=set(videos)), user_id)
+
+ def _deletable(self, kind: MediaKind, names: Collection[str], user_id: str, is_admin: bool) -> set[str]:
+ """The existing named items the caller may delete, in one query. The delete endpoints decide each item with
+ `item_allows`; no board role grants a permanent delete, so the board an item is on does not enter it."""
+ if not names:
+ return set()
+ return {
+ name
+ for name, owner in self._queries.gallery.item_owners(kind, set(names))
+ if item_allows(is_item_owner=owner == user_id, is_admin=is_admin, board=None, action=ItemAction.Delete)
+ }
+
+ def _usage(self, checked: MediaReferences, user_id: str) -> GalleryMediaUsage:
+ """Who uses the checked media: the caller's documents and queue work by name, everyone else's as counts."""
+ by_kind: tuple[tuple[MediaKind, set[str]], ...] = (("image", checked.images), ("video", checked.videos))
+
+ def read(
+ q: Queries,
+ ) -> tuple[list[tuple[MediaKind, str, _Owner]], dict[_Owner, str], dict[str, tuple[int, Optional[int]]]]:
+ rows = [
+ (kind, media, (owner_kind, owner_user, owner_id))
+ for kind, names in by_kind
+ if names
+ for media, owner_kind, owner_user, owner_id in q.media_references.owners(kind, names)
+ ]
+ callers = {owner for _, _, owner in rows if owner[1] == user_id}
+ # Only the caller's own documents are named. A project's revisions are read in the same transaction as
+ # its references, which are written in the transaction that saves it: they describe the state the names
+ # were read from, which a client compares with the copy it holds.
+ projects = sorted(
+ {owner_id for owner_kind, _, owner_id in callers if _document_of(owner_kind, owner_id)[0] == "project"}
+ )
+ return rows, q.media_references.document_names(callers), q.projects.revisions(user_id, projects)
+
+ rows, document_names, revisions = (
+ self._queries.run(read, read_only=True) if not checked.is_empty() else ([], {}, {})
+ )
+ active = self.__invoker.services.intermediates.get_active_queue_uses(checked)
+
+ in_use = MediaReferences()
+ mine: dict[tuple[GalleryMediaUsageDocumentKind, str], _DocumentUse] = {}
+ other_documents: set[tuple[GalleryMediaUsageDocumentKind, str, str]] = set()
+ other_media = MediaReferences()
+ for kind, media, owner in rows:
+ owner_kind, owner_user, owner_id = owner
+ document = _document_of(owner_kind, owner_id)
+ _add(in_use, kind, media)
+ if owner_user == user_id:
+ use = mine.setdefault(document, _DocumentUse())
+ _add(use.names, kind, media)
+ use.owners.add(owner)
+ else:
+ # Another account's workspace in the caller's project is that account's document.
+ other_documents.add((document[0], owner_user, document[1]))
+ _add(other_media, kind, media)
+
+ queue_items = 0
+ queue_media = MediaReferences()
+ other_queue_items = 0
+ for item in active:
+ # As the queue's own owner checks: an item stored without an owner is no caller's.
+ if item.user_id == user_id:
+ queue_items += 1
+ target = queue_media
+ else:
+ other_queue_items += 1
+ target = other_media
+ for names in (in_use, target):
+ names.images |= item.images
+ names.videos |= item.videos
+
+ documents: list[GalleryMediaUsageDocument] = []
+ for (kind, document_id), use in mine.items():
+ revision, workspace_revision = (
+ revisions.get(document_id, (None, None)) if kind == "project" else (None, None)
+ )
+ documents.append(
+ GalleryMediaUsageDocument(
+ kind=kind,
+ id=document_id,
+ # A project's own name before a workspace's: sorted owners put `project` first.
+ name=next((document_names[o] for o in sorted(use.owners) if o in document_names), None),
+ image_names=_capped(use.names.images),
+ video_names=_capped(use.names.videos),
+ image_count=len(use.names.images),
+ video_count=len(use.names.videos),
+ revision=revision,
+ workspace_revision=workspace_revision,
+ )
+ )
+ documents.sort(key=lambda d: (d.kind, (d.name or "").casefold(), d.id))
+ return GalleryMediaUsage(
+ checked_image_count=len(checked.images),
+ checked_video_count=len(checked.videos),
+ in_use_image_count=len(in_use.images),
+ in_use_video_count=len(in_use.videos),
+ documents=documents[:MAX_USAGE_DOCUMENTS],
+ documents_total=len(documents),
+ queue=GalleryMediaUsageQueue(
+ item_count=queue_items,
+ image_names=_capped(queue_media.images),
+ video_names=_capped(queue_media.videos),
+ image_count=len(queue_media.images),
+ video_count=len(queue_media.videos),
+ ),
+ other_accounts=GalleryMediaUsageOthers(
+ document_count=len(other_documents),
+ queue_item_count=other_queue_items,
+ image_count=len(other_media.images),
+ video_count=len(other_media.videos),
+ ),
+ )
+
def _to_item(self, row: Sequence[Any]) -> GalleryItem:
kind, name, width, height, category, starred, is_intermediate, board_id, created_at, duration, fps, origin = row
urls = self.__invoker.services.urls
diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.py
index 4142bd3a99..a5f6013791 100644
--- a/invokeai/app/services/intermediates/intermediates_base.py
+++ b/invokeai/app/services/intermediates/intermediates_base.py
@@ -3,6 +3,7 @@ from dataclasses import dataclass
from typing import Optional
from invokeai.app.services.intermediates.intermediates_common import (
+ ActiveQueueMediaUse,
IntermediatesBrowserHoldRequest,
IntermediatesOperation,
IntermediatesOperationRequest,
@@ -30,6 +31,12 @@ class IntermediatesServiceBase(ABC):
"""Pin existing cached media until the consuming queue session ends; False means recompute."""
pass
+ @abstractmethod
+ def get_active_queue_uses(self, references: MediaReferences) -> list[ActiveQueueMediaUse]:
+ """The active queue items whose sessions name any of these media, with each item's account: the work the
+ cleanup treats as active."""
+ pass
+
@abstractmethod
def replace_browser_hold(
self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequest
diff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.py
index 33cadfd48c..6c1b078c12 100644
--- a/invokeai/app/services/intermediates/intermediates_common.py
+++ b/invokeai/app/services/intermediates/intermediates_common.py
@@ -1,5 +1,6 @@
"""Contracts of the intermediates manager: summaries, previews and cleanup operations."""
+from dataclasses import dataclass
from datetime import datetime
from typing import Annotated, Literal, Optional
@@ -39,6 +40,16 @@ MAX_ACKNOWLEDGED_DOCUMENTS = 10_000
MediaName = Annotated[str, Field(min_length=1, max_length=255)]
+@dataclass(frozen=True)
+class ActiveQueueMediaUse:
+ """An active queue item (see `queries/intermediates.py`) whose session names some of the media asked about."""
+
+ # The queue item's account; None for a row stored without one.
+ user_id: Optional[str]
+ images: frozenset[str]
+ videos: frozenset[str]
+
+
class IntermediatesBrowserHoldRequest(BaseModel):
images: list[MediaName] = Field(default_factory=list, max_length=MAX_BROWSER_HOLD_NAMES)
videos: list[MediaName] = Field(default_factory=list, max_length=MAX_BROWSER_HOLD_NAMES)
diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.py
index 2a72da54e4..a7930339b1 100644
--- a/invokeai/app/services/intermediates/intermediates_default.py
+++ b/invokeai/app/services/intermediates/intermediates_default.py
@@ -29,6 +29,7 @@ from invokeai.app.services.intermediates.intermediates_common import (
MAX_AFFECTED_DOCUMENTS,
PREVIEW_TTL_SECONDS,
RECENT_GRACE_SECONDS,
+ ActiveQueueMediaUse,
IntermediatesAffectedDocument,
IntermediatesBrowserHoldRequest,
IntermediatesImpact,
@@ -165,6 +166,9 @@ class IntermediatesService(IntermediatesServiceBase):
def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:
return self._records.hold_cached_media(session_id, references)
+ def get_active_queue_uses(self, references: MediaReferences) -> list[ActiveQueueMediaUse]:
+ return self._records.get_active_uses(references)
+
def replace_browser_hold(
self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequest
) -> None:
diff --git a/invokeai/app/services/intermediates/intermediates_records_default.py b/invokeai/app/services/intermediates/intermediates_records_default.py
index f990ecfea5..b757cc1353 100644
--- a/invokeai/app/services/intermediates/intermediates_records_default.py
+++ b/invokeai/app/services/intermediates/intermediates_records_default.py
@@ -27,6 +27,7 @@ from invokeai.app.services.intermediates.intermediates_common import (
BROWSER_HOLD_TTL_SECONDS,
MAX_BROWSER_HOLD_LEASES_PER_USER,
RECENT_GRACE_SECONDS,
+ ActiveQueueMediaUse,
IntermediatesCleanupMode,
IntermediatesKindCounts,
)
@@ -92,6 +93,15 @@ class _Classifying:
}
+class _ActiveInputs(NamedTuple):
+ """The media names one active queue item's stored session names, as of one session revision."""
+
+ revision: int
+ user_id: Optional[str]
+ images: frozenset[str]
+ videos: frozenset[str]
+
+
class ReferenceOwner(NamedTuple):
"""A saved document naming a media item, as `media_references` keys it."""
@@ -178,7 +188,7 @@ class IntermediatesRecords:
# workflow-call parent resuming with its child's outputs) is scanned again, a status change alone is not.
# Entries live as long as the item is active. Derived from committed rows only, so it is right whichever
# transaction rolls back; transactions on a server fill it side by side, hence the lock.
- self._active_inputs: dict[int, tuple[int, frozenset[str], frozenset[str]]] = {}
+ self._active_inputs: dict[int, _ActiveInputs] = {}
self._active_inputs_lock = threading.Lock()
def start(self) -> None:
@@ -191,33 +201,53 @@ class IntermediatesRecords:
guard waiting on one of them would hold up every write that protects media."""
self._queries.intermediates.expire_session_holds(now=clock.now, recent_cutoff=clock.recent_cutoff)
- def _classifying(self, q: Queries, clock: _Clock) -> _Classifying:
+ def _scan_active(self, q: Queries) -> dict[int, _ActiveInputs]:
"""Brings the scan of active queue items up to date, on the caller's transaction, and writes nothing.
Runs on the caller's transaction, so that a classification and an enqueue it might race are ordered by the
- database, never by a stale cache. Holds not expired yet only protect more: a hold of a session that ended
- still counts as active until it is released.
+ database, never by a stale cache.
"""
active = q.intermediates.active_items()
with self._active_inputs_lock:
- known = {item: entry for item, entry in self._active_inputs.items() if active.get(item) == entry[0]}
+ known = {item: entry for item, entry in self._active_inputs.items() if active.get(item) == entry.revision}
changed = [item for item in active if item not in known]
- for item, stamp, session in q.intermediates.sessions(changed):
+ for item, stamp, user_id, session in q.intermediates.sessions(changed):
text = session if isinstance(session, str) else ""
- known[item] = (
+ known[item] = _ActiveInputs(
stamp,
+ user_id,
frozenset(_IMAGE_NAME_RE.findall(text)),
frozenset(_VIDEO_NAME_RE.findall(text)),
)
with self._active_inputs_lock:
self._active_inputs = known
+ return known
+
+ def _classifying(self, q: Queries, clock: _Clock) -> _Classifying:
+ """The clock and active names of one classification. Holds not expired yet only protect more: a hold of a
+ session that ended still counts as active until it is released."""
images: set[str] = set()
videos: set[str] = set()
- for _, image_names, video_names in known.values():
- images.update(image_names)
- videos.update(video_names)
+ for entry in self._scan_active(q).values():
+ images.update(entry.images)
+ videos.update(entry.videos)
return _Classifying(clock, {"image": frozenset(images), "video": frozenset(videos)})
+ def get_active_uses(self, references: MediaReferences) -> list[ActiveQueueMediaUse]:
+ """The active queue items whose sessions name any of these media, one entry each, with the ones it names.
+
+ The same scan, and the same cache, as the cleanup's classification: one definition of active work."""
+ if references.is_empty():
+ return []
+ known = self._queries.run(self._scan_active, read_only=True)
+ uses: list[ActiveQueueMediaUse] = []
+ for entry in known.values():
+ images = entry.images & references.images
+ videos = entry.videos & references.videos
+ if images or videos:
+ uses.append(ActiveQueueMediaUse(entry.user_id, images, videos))
+ return uses
+
# region holds
def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:
@@ -447,28 +477,10 @@ class IntermediatesRecords:
def get_document_names(self, owners: Collection[ReferenceOwner]) -> dict[ReferenceOwner, str]:
"""Names of the referencing documents, one query per kind; client state has none."""
- wanted: dict[str, set[ReferenceOwner]] = defaultdict(set)
- for owner in owners:
- if owner.owner_kind in ("project", "project_workspace", "quarantined_project", "workflow"):
- wanted[owner.owner_kind].add(owner)
-
- def names(q: Queries) -> dict[ReferenceOwner, str]:
- found: dict[ReferenceOwner, str] = {}
- for owner_kind, kind_owners in wanted.items():
- ids = sorted({owner.owner_id for owner in kind_owners})
- named = {
- (owner, owner_id): name
- for owner, owner_id, name in q.intermediates.document_names(owner_kind, ids)
- if name is not None
- }
- for owner in kind_owners:
- unowned = owner_kind in ("workflow", "project_workspace")
- name = named.get((None if unowned else owner.user_id, owner.owner_id))
- if name is not None:
- found[owner] = name
- return found
-
- return self._queries.run(names, read_only=True)
+ return {
+ ReferenceOwner(*owner): name
+ for owner, name in self._queries.media_references.document_names(owners).items()
+ }
# endregion
@@ -499,7 +511,7 @@ class IntermediatesRecords:
named = set(names)
references: dict[str, set[ReferenceOwner]] = defaultdict(set)
if mode == "force":
- for media_name, owner_kind, owner_user, owner_id in q.intermediates.reference_owners(kind, named):
+ for media_name, owner_kind, owner_user, owner_id in q.media_references.owners(kind, named):
references[media_name].add(ReferenceOwner(owner_kind, owner_user, owner_id))
# Ownership is re-read here rather than trusted from the preview.
allowed = {
diff --git a/invokeai/app/services/shared/database/queries/gallery.py b/invokeai/app/services/shared/database/queries/gallery.py
index 70a6341bd0..2a5fd49f21 100644
--- a/invokeai/app/services/shared/database/queries/gallery.py
+++ b/invokeai/app/services/shared/database/queries/gallery.py
@@ -9,7 +9,7 @@ from page to page.
import functools
import itertools
import operator
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from typing import Any, Literal, NamedTuple, Optional
from sqlalchemy import (
@@ -18,6 +18,7 @@ from sqlalchemy import (
FromClause,
Row,
Select,
+ String,
Subquery,
Table,
and_,
@@ -41,8 +42,10 @@ from invokeai.app.services.image_records.image_records_common import (
)
from invokeai.app.services.shared.database.dialect import (
CaseInsensitiveLike,
+ InBoundSet,
JsonString,
OrderedJoin,
+ bound_set,
fixed_limit,
like_contains,
)
@@ -66,6 +69,13 @@ _HALVES = {
"video": _Half(videos, board_videos, "video_name", "video_category", "video_origin"),
}
+_ITEM_OWNERS = {
+ kind: select(half.media.c[half.name], half.media.c.user_id).where(
+ InBoundSet(half.media.c[half.name], bindparam("names", type_=String()))
+ )
+ for kind, half in _HALVES.items()
+}
+
class _Shape(NamedTuple):
"""Which filters a listing has: never their values, which are bound, so that the shapes are few."""
@@ -463,3 +473,10 @@ class GalleryQueries(QueryModule):
BoardSummary(str(r[0]), int(r[1] or 0), int(r[2] or 0), int(r[3] or 0), int(r[4] or 0), r[5], r[6])
)
return summaries
+
+ @read
+ def item_owners(
+ self, conn: Connection, kind: Literal["image", "video"], names: Collection[str]
+ ) -> list[tuple[str, str]]:
+ """(name, owner) of each named item of `kind` that exists."""
+ return [(str(r[0]), str(r[1])) for r in conn.execute(_ITEM_OWNERS[kind], {"names": bound_set(names)}).all()]
diff --git a/invokeai/app/services/shared/database/queries/intermediates.py b/invokeai/app/services/shared/database/queries/intermediates.py
index d0e67e720d..8ab013b5a5 100644
--- a/invokeai/app/services/shared/database/queries/intermediates.py
+++ b/invokeai/app/services/shared/database/queries/intermediates.py
@@ -60,10 +60,9 @@ from invokeai.app.services.shared.database.schema.intermediates import (
intermediates_unmeasurable,
)
from invokeai.app.services.shared.database.schema.media_references import media_references
-from invokeai.app.services.shared.database.schema.projects import orphaned_projects_2026_08_06, projects
+from invokeai.app.services.shared.database.schema.projects import projects
from invokeai.app.services.shared.database.schema.session_queue import session_queue
from invokeai.app.services.shared.database.schema.videos import videos
-from invokeai.app.services.shared.database.schema.workflows import workflow_library
MediaKind = Literal["image", "video"]
Classification = Literal["safe", "referenced", "active", "recent"]
@@ -106,7 +105,7 @@ def _protected_items() -> Subquery:
_PROTECTED = _protected_items()
_ACTIVE_ITEMS = select(_PROTECTED.c.item_id, func.coalesce(_PROTECTED.c.session_revision, 0))
-_SESSIONS = select(_Q.item_id, func.coalesce(_Q.session_revision, 0), _Q.session).where(
+_SESSIONS = select(_Q.item_id, func.coalesce(_Q.session_revision, 0), _Q.user_id, _Q.session).where(
_Q.item_id.in_(bindparam("item_ids", expanding=True))
)
_SESSION_IS_ACTIVE = select(literal(1)).where(
@@ -133,23 +132,6 @@ _RELEASE_LEASES = delete(intermediates_browser_holds).where(
_CLEAR_UNMEASURABLE = delete(intermediates_unmeasurable)
-_DOCUMENT_NAMES = {
- "project": select(_P.user_id, _P.project_id, _P.name).where(_P.project_id.in_(bindparam("ids", expanding=True))),
- # A workspace is named after its project, whose owner need not be the workspace's.
- "project_workspace": select(null(), _P.project_id, _P.name).where(
- _P.project_id.in_(bindparam("ids", expanding=True))
- ),
- "quarantined_project": select(
- orphaned_projects_2026_08_06.c.user_id,
- orphaned_projects_2026_08_06.c.project_id,
- orphaned_projects_2026_08_06.c.name,
- ).where(orphaned_projects_2026_08_06.c.project_id.in_(bindparam("ids", expanding=True))),
- # Workflow ids are unique across accounts, so the owner is not part of the match.
- "workflow": select(null(), workflow_library.c.workflow_id, workflow_library.c.name).where(
- workflow_library.c.workflow_id.in_(bindparam("ids", expanding=True))
- ),
-}
-
def _is_intermediate(media: Table) -> ColumnElement[bool]:
# As the partial indexes on intermediates spell it, so that SQLite uses them.
@@ -437,13 +419,6 @@ def _hold_for_lease(kind: MediaKind, dialect_name: str) -> Any:
)
-def _reference_owners(kind: MediaKind) -> Select[Any]:
- return select(_R.media_name, _R.owner_kind, _R.user_id, _R.owner_id).where(
- _R.media_kind == literal(kind), InBoundSet(_R.media_name, bindparam("names", type_=String()))
- )
-
-
def _unmeasured(kind: MediaKind) -> tuple[Table, list[ColumnElement[bool]]]:
media, name_column, _ = _MEDIA[kind]
marked = exists(select(literal(1)).where(_U.media_kind == literal(kind), _U.media_name == media.c[name_column]))
@@ -554,13 +529,15 @@ class IntermediateQueries(QueryModule):
return {int(row[0]): int(row[1]) for row in conn.execute(_ACTIVE_ITEMS).all()}
@read
- def sessions(self, conn: Connection, item_ids: Collection[int]) -> list[tuple[int, int, Optional[str]]]:
- """(item, revision, session JSON) of each named queue item."""
- rows: list[tuple[int, int, Optional[str]]] = []
+ def sessions(
+ self, conn: Connection, item_ids: Collection[int]
+ ) -> list[tuple[int, int, Optional[str], Optional[str]]]:
+ """(item, revision, owner, session JSON) of each named queue item."""
+ rows: list[tuple[int, int, Optional[str], Optional[str]]] = []
ordered = sorted(item_ids)
for start in range(0, len(ordered), IN_CHUNK):
chunk = ordered[start : start + IN_CHUNK]
- rows.extend((int(r[0]), int(r[1]), r[2]) for r in conn.execute(_SESSIONS, {"item_ids": chunk}).all())
+ rows.extend((int(r[0]), int(r[1]), r[2], r[3]) for r in conn.execute(_SESSIONS, {"item_ids": chunk}).all())
return rows
@read
@@ -748,19 +725,9 @@ class IntermediateQueries(QueryModule):
}
return [(str(r[0]), str(r[1])) for r in conn.execute(_still_deletable(kind, mode, is_admin), parameters).all()]
- @read
- def reference_owners(
- self, conn: Connection, kind: MediaKind, names: Collection[str]
- ) -> list[tuple[str, str, str, str]]:
- """(media, owner kind, owner account, owner id) of each document naming one of the named media."""
- return [
- (str(r[0]), str(r[1]), str(r[2]), str(r[3]))
- for r in conn.execute(_reference_owners(kind), {"names": bound_set(names)}).all()
- ]
-
# endregion
- # region documents and projects
+ # region projects
@read
def projects(self, conn: Connection, user_id: Optional[str]) -> list[tuple[str, str, str, Optional[str]]]:
@@ -769,19 +736,6 @@ class IntermediateQueries(QueryModule):
statement = _OWNERS_PROJECTS if user_id is not None else _PROJECTS
return [(str(r[0]), str(r[1]), str(r[2]), r[3]) for r in conn.execute(statement, {"user_id": user_id}).all()]
- @read
- def document_names(
- self, conn: Connection, owner_kind: str, ids: Sequence[str]
- ) -> list[tuple[Optional[str], str, Optional[str]]]:
- """(owner, id, name) of the documents of `owner_kind` with the given ids; workflows have no owner here."""
- rows: list[tuple[Optional[str], str, Optional[str]]] = []
- for start in range(0, len(ids), IN_CHUNK):
- chunk = list(ids[start : start + IN_CHUNK])
- rows.extend(
- (r[0], str(r[1]), r[2]) for r in conn.execute(_DOCUMENT_NAMES[owner_kind], {"ids": chunk}).all()
- )
- return rows
-
# endregion
# region measurement
diff --git a/invokeai/app/services/shared/database/queries/media_references.py b/invokeai/app/services/shared/database/queries/media_references.py
index 4b8edf344e..0e69c7c4db 100644
--- a/invokeai/app/services/shared/database/queries/media_references.py
+++ b/invokeai/app/services/shared/database/queries/media_references.py
@@ -8,12 +8,19 @@ while the delete runs has no row the delete could have locked, and must keep the
import itertools
from collections.abc import Collection
+from typing import Optional
-from sqlalchemy import Connection, bindparam, delete, insert
+from sqlalchemy import Connection, String, bindparam, delete, insert, null, select
-from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, write
+from invokeai.app.services.shared.database.dialect import InBoundSet, bound_set
+from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, read, write
from invokeai.app.services.shared.database.schema.media_references import media_references
-from invokeai.app.services.shared.media_references import MediaReferenceOwnerKind, MediaReferences
+from invokeai.app.services.shared.database.schema.projects import orphaned_projects_2026_08_06, projects
+from invokeai.app.services.shared.database.schema.workflows import workflow_library
+from invokeai.app.services.shared.media_references import MediaKind, MediaReferenceOwnerKind, MediaReferences
+
+_R = media_references.c
+_P = projects.c
_DELETE_OWNER = delete(media_references).where(
media_references.c.owner_kind == bindparam("owner_kind"),
@@ -31,6 +38,27 @@ _DELETE_OWNED_BY = delete(media_references).where(
)
_INSERT = insert(media_references)
+_OWNERS = select(_R.media_name, _R.owner_kind, _R.user_id, _R.owner_id).where(
+ _R.media_kind == bindparam("media_kind"), InBoundSet(_R.media_name, bindparam("names", type_=String()))
+)
+
+_DOCUMENT_NAMES = {
+ "project": select(_P.user_id, _P.project_id, _P.name).where(_P.project_id.in_(bindparam("ids", expanding=True))),
+ # A workspace is named after its project, whose owner need not be the workspace's.
+ "project_workspace": select(null(), _P.project_id, _P.name).where(
+ _P.project_id.in_(bindparam("ids", expanding=True))
+ ),
+ "quarantined_project": select(
+ orphaned_projects_2026_08_06.c.user_id,
+ orphaned_projects_2026_08_06.c.project_id,
+ orphaned_projects_2026_08_06.c.name,
+ ).where(orphaned_projects_2026_08_06.c.project_id.in_(bindparam("ids", expanding=True))),
+ # Workflow ids are unique across accounts, so the owner is not part of the match.
+ "workflow": select(null(), workflow_library.c.workflow_id, workflow_library.c.name).where(
+ workflow_library.c.workflow_id.in_(bindparam("ids", expanding=True))
+ ),
+}
+
class MediaReferenceQueries(QueryModule):
@write
@@ -76,3 +104,36 @@ class MediaReferenceQueries(QueryModule):
"""Deletes the references of every document of these kinds that the account owns, for documents deleted
with the account: deleting its row locks theirs, and keeps new ones from being written meanwhile."""
conn.execute(_DELETE_OWNED_BY, {"user_id": user_id, "owner_kinds": list(owner_kinds)})
+
+ @read
+ def owners(self, conn: Connection, kind: MediaKind, names: Collection[str]) -> list[tuple[str, str, str, str]]:
+ """(media, owner kind, owner account, owner id) of each document naming one of the named media."""
+ return [
+ (str(r[0]), str(r[1]), str(r[2]), str(r[3]))
+ for r in conn.execute(_OWNERS, {"media_kind": kind, "names": bound_set(names)}).all()
+ ]
+
+ @read
+ def document_names(
+ self, conn: Connection, owners: Collection[tuple[str, str, str]]
+ ) -> dict[tuple[str, str, str], str]:
+ """The names of the documents behind these (owner kind, owner account, owner id) keys, one query per kind and
+ chunk. Client state has none, nor has a document that no longer exists."""
+ wanted: dict[str, set[tuple[str, str, str]]] = {}
+ for owner in owners:
+ if owner[0] in _DOCUMENT_NAMES:
+ wanted.setdefault(owner[0], set()).add(owner)
+ found: dict[tuple[str, str, str], str] = {}
+ for owner_kind, kind_owners in wanted.items():
+ ids = sorted({owner_id for _, _, owner_id in kind_owners})
+ named: dict[tuple[Optional[str], str], str] = {}
+ for chunk in itertools.batched(ids, IN_CHUNK):
+ for r in conn.execute(_DOCUMENT_NAMES[owner_kind], {"ids": list(chunk)}).all():
+ if r[2] is not None:
+ named[(r[0], str(r[1]))] = r[2]
+ unowned = owner_kind in ("workflow", "project_workspace")
+ for owner in kind_owners:
+ name = named.get((None if unowned else owner[1], owner[2]))
+ if name is not None:
+ found[owner] = name
+ return found
diff --git a/invokeai/app/services/shared/database/queries/projects.py b/invokeai/app/services/shared/database/queries/projects.py
index 78b309ab5b..a661fa9c55 100644
--- a/invokeai/app/services/shared/database/queries/projects.py
+++ b/invokeai/app/services/shared/database/queries/projects.py
@@ -77,6 +77,13 @@ _SUMMARIES = (
.order_by(projects.c.created_at, projects.c.project_id)
)
_BOARD_ID = select(projects.c.board_id).where(*_THE_PROJECT)
+_REVISIONS = (
+ select(projects.c.project_id, projects.c.revision, _W.revision)
+ .select_from(_WITH_CALLERS_WORKSPACE)
+ .where(
+ projects.c.user_id == bindparam("user_id"), projects.c.project_id.in_(bindparam("project_ids", expanding=True))
+ )
+)
_OWNED_IDS = select(projects.c.project_id).where(
projects.c.user_id == bindparam("user_id"), projects.c.project_id.in_(bindparam("project_ids", expanding=True))
)
@@ -259,6 +266,20 @@ class ProjectQueries(QueryModule):
def board_id(self, conn: Connection, user_id: str, project_id: str) -> Optional[str]:
return conn.execute(_BOARD_ID, {"user_id": user_id, "project_id": project_id}).scalar_one_or_none()
+ @read
+ def revisions(
+ self, conn: Connection, user_id: str, project_ids: Sequence[str]
+ ) -> dict[str, tuple[int, Optional[int]]]:
+ """(content revision, the account's workspace revision or None without one) of each of these project ids
+ that names one of the account's projects."""
+ found: dict[str, tuple[int, Optional[int]]] = {}
+ for chunk in itertools.batched(project_ids, IN_CHUNK):
+ rows: Sequence[Sequence[Any]] = conn.execute(
+ _REVISIONS, {"user_id": user_id, "project_ids": list(chunk)}
+ ).all()
+ found.update((str(row[0]), (int(row[1]), None if row[2] is None else int(row[2]))) for row in rows)
+ return found
+
@read
def owned_ids(self, conn: Connection, user_id: str, project_ids: Sequence[str]) -> set[str]:
"""Those of these project ids that name one of the account's projects."""
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index adc6fb1472..8d9b63dff2 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -11581,6 +11581,52 @@
}
}
},
+ "/api/v1/gallery/usage": {
+ "post": {
+ "tags": ["gallery"],
+ "summary": "Get Gallery Media Usage",
+ "description": "Reports what still uses media before it is deleted: the caller's saved documents and active queue work by\nname, other accounts' as counts. Deleting stays a separate request; this only reads.",
+ "operationId": "get_gallery_media_usage",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMediaUsageRequest",
+ "description": "The media to check"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMediaUsage"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/app/gallery/maintenance/preview": {
"post": {
"tags": ["gallery_maintenance"],
@@ -45457,6 +45503,263 @@
],
"title": "GalleryMaintenanceResult"
},
+ "GalleryMediaUsage": {
+ "properties": {
+ "checked_image_count": {
+ "type": "integer",
+ "title": "Checked Image Count",
+ "description": "Images checked: the requested ones the caller may delete, or the images the board's deletion would delete."
+ },
+ "checked_video_count": {
+ "type": "integer",
+ "title": "Checked Video Count",
+ "description": "Videos checked: the requested ones the caller may delete, or the videos the board's deletion would delete."
+ },
+ "in_use_image_count": {
+ "type": "integer",
+ "title": "In Use Image Count",
+ "description": "Distinct checked images that anything below names."
+ },
+ "in_use_video_count": {
+ "type": "integer",
+ "title": "In Use Video Count",
+ "description": "Distinct checked videos that anything below names."
+ },
+ "documents": {
+ "items": {
+ "$ref": "#/components/schemas/GalleryMediaUsageDocument"
+ },
+ "type": "array",
+ "title": "Documents",
+ "description": "The caller's own documents naming checked media, by kind, then name, then id; at most 100."
+ },
+ "documents_total": {
+ "type": "integer",
+ "title": "Documents Total",
+ "description": "How many of the caller's documents name checked media."
+ },
+ "queue": {
+ "$ref": "#/components/schemas/GalleryMediaUsageQueue",
+ "description": "The caller's own active queue work naming checked media."
+ },
+ "other_accounts": {
+ "$ref": "#/components/schemas/GalleryMediaUsageOthers",
+ "description": "Other accounts' documents and queue work naming checked media, as counts only."
+ }
+ },
+ "type": "object",
+ "required": [
+ "checked_image_count",
+ "checked_video_count",
+ "in_use_image_count",
+ "in_use_video_count",
+ "documents",
+ "documents_total",
+ "queue",
+ "other_accounts"
+ ],
+ "title": "GalleryMediaUsage",
+ "description": "What still uses media a deletion would remove. Saved documents count conservatively: anything they name,\nhistory included."
+ },
+ "GalleryMediaUsageDocument": {
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["project", "workflow", "legacy_editor", "quarantined_project"],
+ "title": "Kind",
+ "description": "'project': a project's content and the caller's own workspace in it. 'workflow': a library workflow. 'legacy_editor': the legacy editor's saved state, all of it as one entry. 'quarantined_project': a project kept for repair."
+ },
+ "id": {
+ "type": "string",
+ "title": "Id",
+ "description": "The project or workflow id; 'legacy_editor' for the legacy editor's state."
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Name",
+ "description": "The document's name; null for the legacy editor or a missing document."
+ },
+ "image_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Image Names",
+ "description": "The checked images the document names, sorted; at most 1000."
+ },
+ "video_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Video Names",
+ "description": "The checked videos the document names, sorted; at most 1000."
+ },
+ "image_count": {
+ "type": "integer",
+ "title": "Image Count",
+ "description": "How many checked images the document names, past the list's cap too."
+ },
+ "video_count": {
+ "type": "integer",
+ "title": "Video Count",
+ "description": "How many checked videos the document names, past the list's cap too."
+ },
+ "revision": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Revision",
+ "description": "For a project: its content revision when the names were read, as the project read reports it (`revision`). Null for other kinds, and for a project the caller does not own."
+ },
+ "workspace_revision": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Workspace Revision",
+ "description": "For a project: the caller's workspace revision when the names were read, as the project read reports it (`workspace.revision`); null while the caller has no workspace in it. Null for other kinds."
+ }
+ },
+ "type": "object",
+ "required": [
+ "kind",
+ "id",
+ "name",
+ "image_names",
+ "video_names",
+ "image_count",
+ "video_count",
+ "revision",
+ "workspace_revision"
+ ],
+ "title": "GalleryMediaUsageDocument",
+ "description": "One of the caller's saved documents that names checked media."
+ },
+ "GalleryMediaUsageOthers": {
+ "properties": {
+ "document_count": {
+ "type": "integer",
+ "title": "Document Count",
+ "description": "Other accounts' documents naming checked media."
+ },
+ "queue_item_count": {
+ "type": "integer",
+ "title": "Queue Item Count",
+ "description": "Other accounts' active queue items naming checked media."
+ },
+ "image_count": {
+ "type": "integer",
+ "title": "Image Count",
+ "description": "Distinct checked images other accounts' documents or queue work name."
+ },
+ "video_count": {
+ "type": "integer",
+ "title": "Video Count",
+ "description": "Distinct checked videos other accounts' documents or queue work name."
+ }
+ },
+ "type": "object",
+ "required": ["document_count", "queue_item_count", "image_count", "video_count"],
+ "title": "GalleryMediaUsageOthers",
+ "description": "Other accounts' documents and queue work that name checked media, without identifying them."
+ },
+ "GalleryMediaUsageQueue": {
+ "properties": {
+ "item_count": {
+ "type": "integer",
+ "title": "Item Count",
+ "description": "The caller's active queue items (pending, in progress or waiting, and the completed children of an active root) whose sessions name checked media."
+ },
+ "image_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Image Names",
+ "description": "The checked images those items name, sorted; at most 1000."
+ },
+ "video_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Video Names",
+ "description": "The checked videos those items name, sorted; at most 1000."
+ },
+ "image_count": {
+ "type": "integer",
+ "title": "Image Count",
+ "description": "How many checked images those items name, past the list's cap too."
+ },
+ "video_count": {
+ "type": "integer",
+ "title": "Video Count",
+ "description": "How many checked videos those items name, past the list's cap too."
+ }
+ },
+ "type": "object",
+ "required": ["item_count", "image_names", "video_names", "image_count", "video_count"],
+ "title": "GalleryMediaUsageQueue",
+ "description": "The caller's active queue work that names checked media."
+ },
+ "GalleryMediaUsageRequest": {
+ "properties": {
+ "image_names": {
+ "items": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ },
+ "type": "array",
+ "maxItems": 1000,
+ "title": "Image Names",
+ "description": "Images to check. Those the caller may not delete, and unknown ones, are ignored, as `POST /images/delete` skips them."
+ },
+ "video_names": {
+ "items": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ },
+ "type": "array",
+ "maxItems": 1000,
+ "title": "Video Names",
+ "description": "Videos to check. Those the caller may not delete, and unknown ones, are ignored, as `POST /videos/delete` skips them."
+ },
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Board Id",
+ "description": "Check the images and videos `DELETE /boards/{board_id}?include_images=true` would delete, under the same access rules. Not combined with names."
+ }
+ },
+ "type": "object",
+ "title": "GalleryMediaUsageRequest",
+ "description": "The media to check: named images and videos, or every item on one board."
+ },
"GeminiImageGenerationInvocation": {
"category": "image",
"class": "invocation",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 2da575047f..4f87283bad 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -2540,6 +2540,27 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/gallery/usage": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Get Gallery Media Usage
+ * @description Reports what still uses media before it is deleted: the caller's saved documents and active queue work by
+ * name, other accounts' as counts. Deleting stays a separate request; this only reads.
+ */
+ post: operations["get_gallery_media_usage"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/app/gallery/maintenance/preview": {
parameters: {
query?: never;
@@ -18166,6 +18187,177 @@ export type components = {
/** Errors */
errors?: string[];
};
+ /**
+ * GalleryMediaUsage
+ * @description What still uses media a deletion would remove. Saved documents count conservatively: anything they name,
+ * history included.
+ */
+ GalleryMediaUsage: {
+ /**
+ * Checked Image Count
+ * @description Images checked: the requested ones the caller may delete, or the images the board's deletion would delete.
+ */
+ checked_image_count: number;
+ /**
+ * Checked Video Count
+ * @description Videos checked: the requested ones the caller may delete, or the videos the board's deletion would delete.
+ */
+ checked_video_count: number;
+ /**
+ * In Use Image Count
+ * @description Distinct checked images that anything below names.
+ */
+ in_use_image_count: number;
+ /**
+ * In Use Video Count
+ * @description Distinct checked videos that anything below names.
+ */
+ in_use_video_count: number;
+ /**
+ * Documents
+ * @description The caller's own documents naming checked media, by kind, then name, then id; at most 100.
+ */
+ documents: components["schemas"]["GalleryMediaUsageDocument"][];
+ /**
+ * Documents Total
+ * @description How many of the caller's documents name checked media.
+ */
+ documents_total: number;
+ /** @description The caller's own active queue work naming checked media. */
+ queue: components["schemas"]["GalleryMediaUsageQueue"];
+ /** @description Other accounts' documents and queue work naming checked media, as counts only. */
+ other_accounts: components["schemas"]["GalleryMediaUsageOthers"];
+ };
+ /**
+ * GalleryMediaUsageDocument
+ * @description One of the caller's saved documents that names checked media.
+ */
+ GalleryMediaUsageDocument: {
+ /**
+ * Kind
+ * @description 'project': a project's content and the caller's own workspace in it. 'workflow': a library workflow. 'legacy_editor': the legacy editor's saved state, all of it as one entry. 'quarantined_project': a project kept for repair.
+ * @enum {string}
+ */
+ kind: "project" | "workflow" | "legacy_editor" | "quarantined_project";
+ /**
+ * Id
+ * @description The project or workflow id; 'legacy_editor' for the legacy editor's state.
+ */
+ id: string;
+ /**
+ * Name
+ * @description The document's name; null for the legacy editor or a missing document.
+ */
+ name: string | null;
+ /**
+ * Image Names
+ * @description The checked images the document names, sorted; at most 1000.
+ */
+ image_names: string[];
+ /**
+ * Video Names
+ * @description The checked videos the document names, sorted; at most 1000.
+ */
+ video_names: string[];
+ /**
+ * Image Count
+ * @description How many checked images the document names, past the list's cap too.
+ */
+ image_count: number;
+ /**
+ * Video Count
+ * @description How many checked videos the document names, past the list's cap too.
+ */
+ video_count: number;
+ /**
+ * Revision
+ * @description For a project: its content revision when the names were read, as the project read reports it (`revision`). Null for other kinds, and for a project the caller does not own.
+ */
+ revision: number | null;
+ /**
+ * Workspace Revision
+ * @description For a project: the caller's workspace revision when the names were read, as the project read reports it (`workspace.revision`); null while the caller has no workspace in it. Null for other kinds.
+ */
+ workspace_revision: number | null;
+ };
+ /**
+ * GalleryMediaUsageOthers
+ * @description Other accounts' documents and queue work that name checked media, without identifying them.
+ */
+ GalleryMediaUsageOthers: {
+ /**
+ * Document Count
+ * @description Other accounts' documents naming checked media.
+ */
+ document_count: number;
+ /**
+ * Queue Item Count
+ * @description Other accounts' active queue items naming checked media.
+ */
+ queue_item_count: number;
+ /**
+ * Image Count
+ * @description Distinct checked images other accounts' documents or queue work name.
+ */
+ image_count: number;
+ /**
+ * Video Count
+ * @description Distinct checked videos other accounts' documents or queue work name.
+ */
+ video_count: number;
+ };
+ /**
+ * GalleryMediaUsageQueue
+ * @description The caller's active queue work that names checked media.
+ */
+ GalleryMediaUsageQueue: {
+ /**
+ * Item Count
+ * @description The caller's active queue items (pending, in progress or waiting, and the completed children of an active root) whose sessions name checked media.
+ */
+ item_count: number;
+ /**
+ * Image Names
+ * @description The checked images those items name, sorted; at most 1000.
+ */
+ image_names: string[];
+ /**
+ * Video Names
+ * @description The checked videos those items name, sorted; at most 1000.
+ */
+ video_names: string[];
+ /**
+ * Image Count
+ * @description How many checked images those items name, past the list's cap too.
+ */
+ image_count: number;
+ /**
+ * Video Count
+ * @description How many checked videos those items name, past the list's cap too.
+ */
+ video_count: number;
+ };
+ /**
+ * GalleryMediaUsageRequest
+ * @description The media to check: named images and videos, or every item on one board.
+ */
+ GalleryMediaUsageRequest: {
+ /**
+ * Image Names
+ * @description Images to check. Those the caller may not delete, and unknown ones, are ignored, as `POST /images/delete` skips them.
+ */
+ image_names?: string[];
+ /**
+ * Video Names
+ * @description Videos to check. Those the caller may not delete, and unknown ones, are ignored, as `POST /videos/delete` skips them.
+ */
+ video_names?: string[];
+ /**
+ * Board Id
+ * @description Check the images and videos `DELETE /boards/{board_id}?include_images=true` would delete, under the same access rules. Not combined with names.
+ */
+ board_id?: string | null;
+ };
/**
* Gemini Image Generation
* @description Generate images using a Gemini-hosted external model.
@@ -63623,6 +63815,39 @@ export interface operations {
};
};
};
+ get_gallery_media_usage: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["GalleryMediaUsageRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryMediaUsage"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
preview_gallery_maintenance: {
parameters: {
query?: never;
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 4673d9e909..1ea7b998f2 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -363,12 +363,12 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1254258,
+ "brotliBytes": 1268052,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1247521,
+ "gzipBytes": 1261076,
"imageRawBytes": 44398,
- "initialRawBytes": 3460233,
+ "initialRawBytes": 3502701,
"largestAssetRawBytes": 751084,
"otherAssetRawBytes": 0,
"ownedRawBytes": 172801,
@@ -546,6 +546,7 @@
"source:src/features/gallery/ui/GalleryDragCursor.tsx",
"source:src/features/gallery/ui/GalleryItemSearch.tsx",
"source:src/features/gallery/ui/GalleryLoadError.tsx",
+ "source:src/features/gallery/ui/GalleryMediaUsagePanel.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
"source:src/features/gallery/ui/GallerySearchHelp.tsx",
"source:src/features/gallery/ui/GalleryTileFrame.tsx",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 329f6adda5..003b355706 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -30,7 +30,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 29,
"scriptRawBytes": 1931733,
"scriptRequestCount": 25,
@@ -68,7 +68,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 29,
"scriptRawBytes": 1931733,
"scriptRequestCount": 25,
@@ -106,11 +106,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 84,
- "scriptRawBytes": 4526560,
+ "scriptRawBytes": 4593749,
"scriptRequestCount": 79,
- "totalRawBytes": 4897225
+ "totalRawBytes": 4972738
},
"routeReadyMedianMs": 360.90000009536743,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -144,11 +144,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 84,
- "scriptRawBytes": 4526560,
+ "scriptRawBytes": 4593749,
"scriptRequestCount": 79,
- "totalRawBytes": 4897225
+ "totalRawBytes": 4972738
},
"routeReadyMedianMs": 367.80000019073486,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -182,11 +182,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 92,
- "scriptRawBytes": 5121466,
+ "scriptRawBytes": 5188468,
"scriptRequestCount": 87,
- "totalRawBytes": 5492131
+ "totalRawBytes": 5567457
},
"routeReadyMedianMs": 1095.3000001907349,
"scriptSourceOwnerSet": "editor-canvas-static",
@@ -220,11 +220,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 92,
- "scriptRawBytes": 5121466,
+ "scriptRawBytes": 5188468,
"scriptRequestCount": 87,
- "totalRawBytes": 5492131
+ "totalRawBytes": 5567457
},
"routeReadyMedianMs": 1042.5,
"scriptSourceOwnerSet": "editor-canvas-static",
@@ -258,11 +258,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 90,
- "scriptRawBytes": 4981491,
+ "scriptRawBytes": 5053151,
"scriptRequestCount": 84,
- "totalRawBytes": 5367569
+ "totalRawBytes": 5447553
},
"routeReadyMedianMs": 1093.0999999046326,
"scriptSourceOwnerSet": "editor-workflow-static",
@@ -296,11 +296,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 90,
- "scriptRawBytes": 4981491,
+ "scriptRawBytes": 5053151,
"scriptRequestCount": 84,
- "totalRawBytes": 5367569
+ "totalRawBytes": 5447553
},
"routeReadyMedianMs": 1105.0999999046326,
"scriptSourceOwnerSet": "editor-workflow-static",
@@ -334,11 +334,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 84,
- "scriptRawBytes": 4526560,
+ "scriptRawBytes": 4593749,
"scriptRequestCount": 79,
- "totalRawBytes": 4897225
+ "totalRawBytes": 4972738
},
"routeReadyMedianMs": 1324.5,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -372,11 +372,11 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751084,
- "otherRawBytes": 300444,
+ "otherRawBytes": 305228,
"requestCount": 84,
- "scriptRawBytes": 4526560,
+ "scriptRawBytes": 4593749,
"scriptRequestCount": 79,
- "totalRawBytes": 4897225
+ "totalRawBytes": 4972738
},
"routeReadyMedianMs": 1301.5,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -528,6 +528,7 @@
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/launchpad.ts",
"source:src/features/gallery/react.ts",
+ "source:src/features/gallery/ui/GalleryMediaUsagePanel.tsx",
"source:src/features/gallery/ui/GalleryUiContext.tsx",
"source:src/features/gallery/ui/galleryStateView.ts",
"source:src/features/gallery/ui/launchpad/RecentOutputs.tsx",
@@ -962,6 +963,7 @@
"source:src/features/gallery/ui/GalleryItemSearch.tsx",
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryLoadError.tsx",
+ "source:src/features/gallery/ui/GalleryMediaUsagePanel.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GalleryProjectGroup.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
@@ -1659,7 +1661,6 @@
"source:src/workbench/image-actions/galleryOptimisticRollback.ts",
"source:src/workbench/image-actions/imageRecall.ts",
"source:src/workbench/image-actions/index.ts",
- "source:src/workbench/image-actions/mediaUsage.ts",
"source:src/workbench/image-actions/pbrMapsGraph.ts",
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/recordedModel.ts",
@@ -2127,6 +2128,7 @@
"source:src/features/gallery/ui/GalleryItemSearch.tsx",
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryLoadError.tsx",
+ "source:src/features/gallery/ui/GalleryMediaUsagePanel.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GalleryProjectGroup.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
@@ -2840,7 +2842,6 @@
"source:src/workbench/image-actions/galleryOptimisticRollback.ts",
"source:src/workbench/image-actions/imageRecall.ts",
"source:src/workbench/image-actions/index.ts",
- "source:src/workbench/image-actions/mediaUsage.ts",
"source:src/workbench/image-actions/pbrMapsGraph.ts",
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/recordedModel.ts",
@@ -3479,6 +3480,7 @@
"source:src/features/gallery/ui/GalleryItemSearch.tsx",
"source:src/features/gallery/ui/GalleryLayout.tsx",
"source:src/features/gallery/ui/GalleryLoadError.tsx",
+ "source:src/features/gallery/ui/GalleryMediaUsagePanel.tsx",
"source:src/features/gallery/ui/GalleryProgressSection.tsx",
"source:src/features/gallery/ui/GalleryProjectGroup.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
@@ -4248,7 +4250,6 @@
"source:src/workbench/image-actions/galleryOptimisticRollback.ts",
"source:src/workbench/image-actions/imageRecall.ts",
"source:src/workbench/image-actions/index.ts",
- "source:src/workbench/image-actions/mediaUsage.ts",
"source:src/workbench/image-actions/pbrMapsGraph.ts",
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/recordedModel.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 4f93e6ef96..5e4ee5494f 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -5849,9 +5849,16 @@
"dateFilterInvalid": "Unrecognized date “{{value}}” — use YYYY-MM-DD, today, yesterday, 7d, 2w, 1m",
"dateFilterRange": "{{from}} – {{to}}",
"dateFilterThrough": "Through {{date}}",
+ "deleteBlockedByPending_one": "{{media}} wasn’t deleted: answer the open deletion first, then try again.",
+ "deleteBlockedByPending_other": "{{media}} weren’t deleted: answer the open deletion first, then try again.",
+ "deleteBlockedByRunning_one": "{{media}} wasn’t deleted: wait for the deletion under way to finish, then try again.",
+ "deleteBlockedByRunning_other": "{{media}} weren’t deleted: wait for the deletion under way to finish, then try again.",
"deleteBoard": "Delete board",
"deleteBoardDescription_one": "A deleted board can’t be restored. Its {{media}} moves to Uncategorized in the Library.",
"deleteBoardDescription_other": "A deleted board can’t be restored. Its {{media}} move to Uncategorized in the Library.",
+ "deleteBoardWithMediaDescription": "A deleted board can’t be restored. Its {{media}} will be permanently deleted too.",
+ "deleteBoardWithNoOwnMediaDescription": "A deleted board can’t be restored. None of its media is yours, so all of it moves to Uncategorized in the Library.",
+ "deleteBoardWithOwnMediaDescription": "A deleted board can’t be restored. Your {{media}} on it will be permanently deleted too; other accounts’ media moves to Uncategorized.",
"deleteBoardMoveOutcome": "Moved {{media}} to Uncategorized.",
"deleteBoardPartialTitle": "Deleted board \"{{name}}\" with partial media cleanup",
"deleteBoardQuestion": "Delete board \"{{name}}\"?",
@@ -5860,20 +5867,59 @@
"deleteConfirmSkip": "Don’t ask again when deleting one item",
"deleteConfirmSkipHint": "You can turn this confirmation back on in Settings under Gallery.",
"deleteInUse": {
- "heading": "Still used in this project:",
+ "checking": "Checking where this media is used…",
+ "failed": "Couldn’t check where this media is used. Retry, or delete anyway.",
+ "group": {
+ "legacyEditor": "Legacy editor",
+ "moreDocuments_one": "{{count}} more project or workflow",
+ "moreDocuments_other": "{{count}} more projects or workflows",
+ "openProject": "This project",
+ "otherAccounts": "Other accounts’ work",
+ "otherDocument": "Saved work “{{name}}”",
+ "otherDocumentUnnamed": "Other saved work",
+ "project": "Project “{{name}}”",
+ "projectUnnamed": "Untitled project",
+ "quarantinedProject": "Project kept for repair “{{name}}”",
+ "quarantinedProjectUnnamed": "Project kept for repair",
+ "queue_one": "{{count}} queued or running job",
+ "queue_other": "{{count}} queued or running jobs",
+ "workflow": "Library workflow “{{name}}”",
+ "workflowUnnamed": "Untitled library workflow"
+ },
+ "itemCount_one": "{{count}} item",
+ "itemCount_other": "{{count}} items",
+ "listLabel": "Where the media is used",
+ "none": "Nothing uses this media.",
+ "projectUncheckedHint": "Couldn’t open it to see where.",
+ "queueWarning_one": "Jobs that use it will fail.",
+ "queueWarning_other": "Jobs that use them will fail.",
+ "savedCopyUncheckedHint": "Its saved version couldn’t be checked.",
+ "summaryAll": "All {{media}} are still in use:",
+ "summaryBoardAll": "All {{media}} this deletes are still in use:",
+ "summaryBoard_one": "{{count}} of the {{media}} this deletes is still in use:",
+ "summaryBoard_other": "{{count}} of the {{media}} this deletes are still in use:",
+ "summaryOne": "Still in use:",
+ "summary_one": "{{count}} of these {{media}} is still in use:",
+ "summary_other": "{{count}} of these {{media}} are still in use:",
"surface": {
"canvasControl": "Canvas control layers",
"canvasInpaintMask": "Canvas inpaint masks",
"canvasRaster": "Canvas raster layers",
"canvasRegionalGuidance": "Canvas regional guidance",
+ "canvasSnapshot": "Canvas snapshot “{{name}}”",
+ "canvasStaging": "Canvas staged results",
"generateReferenceImages": "Generate reference images",
+ "otherProjectState": "Elsewhere in the project",
"upscale": "Upscale source image",
"video": "Video panel",
"workflow": "Workflow “{{name}}”"
},
- "usedCount_one": "{{count}} selected item",
- "usedCount_other": "{{count}} selected items",
- "warning": "The affected work keeps pointing at media that will no longer exist."
+ "tooManyItems": "Too many items to check them all: only projects open here were checked. Select fewer to check all.",
+ "unchecked": "Other projects, workflows and jobs weren’t checked. Retry to complete the list.",
+ "uncheckedNone_one": "Nothing open here uses it. Other projects, workflows and jobs weren’t checked: retry to check them.",
+ "uncheckedNone_other": "Nothing open here uses them. Other projects, workflows and jobs weren’t checked: retry to check them.",
+ "warning_one": "Work that uses it will point at missing media.",
+ "warning_other": "Work that uses them will point at missing media."
},
"deleteImagesConfirmBody_one": "This permanently deletes the image from every board and from disk. This cannot be undone.",
"deleteImagesConfirmBody_other": "This permanently deletes these images from every board and from disk. This cannot be undone.",
@@ -6256,9 +6302,14 @@
"deleteBoardIncludeMedia_one": "Also permanently delete its {{count}} item",
"deleteBoardIncludeMedia_other": "Also permanently delete its {{count}} items",
"deleteBoardIncludeMediaHint": "Deleted media is removed from every board and from disk, and can’t be restored.",
+ "deleteBoardIncludeOwnMedia_one": "Also permanently delete your {{count}} item",
+ "deleteBoardIncludeOwnMedia_other": "Also permanently delete your {{count}} items",
+ "deleteBoardIncludeOwnMediaNone": "Also permanently delete your items",
"deleteBoardTypeName": "Type “{{name}}” to confirm",
"deleteBoardAndMedia_one": "Delete board and {{count}} item",
"deleteBoardAndMedia_other": "Delete board and {{count}} items",
+ "deleteBoardAndOwnMedia_one": "Delete board and your {{count}} item",
+ "deleteBoardAndOwnMedia_other": "Delete board and your {{count}} items",
"deleteBoardInProgress": "Deleting board “{{name}}” and its media…",
"deleteBoardMediaDeleted": "Deleted {{media}}.",
"deleteBoardMediaFailed": "{{media}} could not be deleted.",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 912b65f5db..5df3515a4d 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -652,6 +652,167 @@ const readJsonBody = async (request, fallback = {}) => {
return body ? JSON.parse(body) : fallback;
};
+const MEDIA_IMAGE_NAME_KEYS = new Set(['imageName', 'image_name']);
+const MEDIA_VIDEO_NAME_KEYS = new Set(['videoName', 'video_name', 'source_video_name']);
+const MEDIA_USAGE_NAME_CAP = 1000;
+const MEDIA_USAGE_DOCUMENT_CAP = 100;
+const ACTIVE_QUEUE_STATUSES = new Set(['pending', 'in_progress', 'waiting']);
+
+/** Every name under the server's media keys, at any depth, as its `media_references` extractor reads documents. */
+const collectReferencedMedia = (roots) => {
+ const images = new Set();
+ const videos = new Set();
+ const pending = [...roots];
+
+ while (pending.length > 0) {
+ const node = pending.pop();
+
+ if (Array.isArray(node)) {
+ pending.push(...node);
+ } else if (node && typeof node === 'object') {
+ for (const [key, value] of Object.entries(node)) {
+ if (typeof value === 'string') {
+ if (MEDIA_IMAGE_NAME_KEYS.has(key)) {
+ images.add(value);
+ } else if (MEDIA_VIDEO_NAME_KEYS.has(key)) {
+ videos.add(value);
+ }
+ } else if (value && typeof value === 'object') {
+ pending.push(value);
+ }
+ }
+ }
+ }
+
+ return { images, videos };
+};
+
+const usedNamesOf = (referenced, checked) => {
+ const imageNames = [...checked.images].filter((name) => referenced.images.has(name)).sort();
+ const videoNames = [...checked.videos].filter((name) => referenced.videos.has(name)).sort();
+
+ return {
+ image_count: imageNames.length,
+ image_names: imageNames.slice(0, MEDIA_USAGE_NAME_CAP),
+ video_count: videoNames.length,
+ video_names: videoNames.slice(0, MEDIA_USAGE_NAME_CAP),
+ };
+};
+
+const parseClientStateValue = (value) => {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Mirrors `POST /api/v1/gallery/usage` over the fixtures: projects (content and the caller's workspace), library
+ * workflows, legacy editor client state and active queue items that name checked media. The mock has one account, so
+ * other accounts never use anything.
+ */
+const galleryMediaUsage = (state, faults, body) => {
+ const imageNames = Array.isArray(body.image_names) ? body.image_names : [];
+ const videoNames = Array.isArray(body.video_names) ? body.video_names : [];
+ const boardId = typeof body.board_id === 'string' ? body.board_id : null;
+
+ if (boardId !== null && imageNames.length + videoNames.length > 0) {
+ return [422, { detail: 'board_id cannot be combined with image_names or video_names' }];
+ }
+
+ // As the server: only media the caller may delete is checked, images and videos alike (fixture images carry no
+ // owner and are the caller's).
+ const isCallers = (item) => (item.owner_user_id ?? MOCK_USER_ID) === MOCK_USER_ID;
+ let checked;
+
+ if (boardId !== null) {
+ const board = state.boards.get(boardId);
+
+ if (!board) {
+ return [404, { detail: 'Board not found' }];
+ }
+ if (!boardAccessFor(state, faults, board, { ignoreInbox: true }).allows('delete')) {
+ return BOARD_ACTION_FORBIDDEN;
+ }
+ const onBoard = (items) => [...items].filter((item) => item.board_id === boardId && isCallers(item));
+ checked = {
+ images: new Set(onBoard(state.images.values()).map((image) => image.image_name)),
+ videos: new Set(onBoard(state.videos.values()).map((video) => video.video_name)),
+ };
+ } else {
+ const deletable = (store, names) => names.filter((name) => store.has(name) && isCallers(store.get(name)));
+ checked = {
+ images: new Set(deletable(state.images, imageNames)),
+ videos: new Set(deletable(state.videos, videoNames)),
+ };
+ }
+
+ const documents = [];
+ // As the server: a project reports the content and workspace revisions its names were read at; other kinds none.
+ const addDocument = (kind, id, name, roots, revisions = { revision: null, workspace_revision: null }) => {
+ const used = usedNamesOf(collectReferencedMedia(roots), checked);
+
+ if (used.image_count + used.video_count > 0) {
+ documents.push({ id, kind, name, ...used, ...revisions });
+ }
+ };
+
+ for (const project of state.projects.values()) {
+ addDocument('project', project.project_id, project.name, [project.data, project.workspace?.data], {
+ revision: project.revision,
+ workspace_revision: project.workspace?.revision ?? null,
+ });
+ }
+ for (const workflow of state.workflows.values()) {
+ if (workflow.category !== 'default') {
+ addDocument('workflow', workflow.workflow_id, workflow.name, [workflow.workflow]);
+ }
+ }
+ addDocument(
+ 'legacy_editor',
+ 'legacy_editor',
+ null,
+ [...state.clientState].filter(([key]) => !key.startsWith('webv2:')).map(([, value]) => parseClientStateValue(value))
+ );
+
+ const kindOrder = ['legacy_editor', 'project', 'quarantined_project', 'workflow'];
+ documents.sort(
+ (left, right) =>
+ kindOrder.indexOf(left.kind) - kindOrder.indexOf(right.kind) ||
+ (left.name ?? '').localeCompare(right.name ?? '') ||
+ left.id.localeCompare(right.id)
+ );
+
+ const activeItems = [...state.queueItems.values()].filter((item) => ACTIVE_QUEUE_STATUSES.has(item.status));
+ const queueItemsUsing = activeItems.filter((item) => {
+ const used = usedNamesOf(collectReferencedMedia([item.session, item.field_values]), checked);
+
+ return used.image_count + used.video_count > 0;
+ });
+ const queueUsed = usedNamesOf(
+ collectReferencedMedia(queueItemsUsing.flatMap((item) => [item.session, item.field_values])),
+ checked
+ );
+ // The fixture lists stay far below the name cap, so their union is every name in use.
+ const inUseImages = new Set([...documents.flatMap((document) => document.image_names), ...queueUsed.image_names]);
+ const inUseVideos = new Set([...documents.flatMap((document) => document.video_names), ...queueUsed.video_names]);
+
+ return [
+ 200,
+ {
+ checked_image_count: checked.images.size,
+ checked_video_count: checked.videos.size,
+ documents: documents.slice(0, MEDIA_USAGE_DOCUMENT_CAP),
+ documents_total: documents.length,
+ in_use_image_count: inUseImages.size,
+ in_use_video_count: inUseVideos.size,
+ other_accounts: { document_count: 0, image_count: 0, queue_item_count: 0, video_count: 0 },
+ queue: { item_count: queueItemsUsing.length, ...queueUsed },
+ },
+ ];
+};
+
const invocationNodeCount = (state) =>
Object.values(state.openApiDocument.components?.schemas ?? {}).filter((schema) => schema?.class === 'invocation')
.length;
@@ -2956,6 +3117,10 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt
return json(200, listGalleryItemNames(state, url, faults));
}
+ if (method === 'POST' && path === '/api/v1/gallery/usage') {
+ return json(...galleryMediaUsage(state, faults, await readJsonBody(request)));
+ }
+
const imageAssetMatch = /^\/api\/v1\/images\/i\/([^/]+)\/(full|thumbnail)$/.exec(path);
if (method === 'GET' && imageAssetMatch) {
const imageName = decodeURIComponent(imageAssetMatch[1]);
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx
index c4ab63eec1..108b4de6bd 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx
@@ -5,6 +5,7 @@ import type { ReactNode } from 'react';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
+import { reportProjectSync } from '@workbench/projects/syncStore';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { createWorkbenchStore } from '@workbench/workbenchStore';
import { act } from 'react';
@@ -40,6 +41,17 @@ vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({
}),
}));
const session = vi.hoisted(() => ({ multiuserEnabled: false }));
+const usage = vi.hoisted(() => ({ check: vi.fn(), readProject: vi.fn() }));
+// The server is doubled; the resolver runs for real over the store's projects.
+vi.mock('@features/gallery/mediaUsage', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ checkGalleryMediaUsage: (...args: unknown[]) => usage.check(...args),
+}));
+// Reading the server's copy of a project fails: a report that needed it would list the project unchecked.
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getProjectWithinSize: (...args: unknown[]) => usage.readProject(...args),
+}));
vi.mock('@features/identity', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuthSession: () => session,
@@ -139,3 +151,56 @@ describe('board sharing', () => {
}
);
});
+
+describe('board media usage', () => {
+ it("narrows a board's report by the open project's own state when the server holds what it builds on", async () => {
+ await renderAdapter();
+ const projectId = store.getSnapshot().activeProject.id;
+ usage.readProject.mockRejectedValue(new Error('Not read'));
+ // Saved at revisions 7 and 3 with both; the project now uses only a.png.
+ await act(() =>
+ store.commands.widgets.patchValues('generate', {
+ referenceImages: [{ config: { image: { image_name: 'a.png' } } }],
+ })
+ );
+ reportProjectSync({
+ hasPendingChanges: true,
+ localDraftStatus: 'ok',
+ projects: { [projectId]: { isPendingPush: true, revision: 7, workspaceRevision: 3 } },
+ recoverableDrafts: [],
+ });
+ usage.check.mockResolvedValue({
+ checkedImageCount: 3,
+ checkedVideoCount: 0,
+ documents: [
+ {
+ id: projectId,
+ imageCount: 2,
+ imageNames: ['a.png', 'b.png'],
+ kind: 'project',
+ name: 'Open',
+ revision: 7,
+ videoCount: 0,
+ videoNames: [],
+ workspaceRevision: 3,
+ },
+ ],
+ documentsTotal: 1,
+ inUseImageCount: 2,
+ inUseVideoCount: 0,
+ otherAccounts: { documentCount: 0, imageCount: 0, queueItemCount: 0, videoCount: 0 },
+ queue: { imageCount: 0, imageNames: [], itemCount: 0, videoCount: 0, videoNames: [] },
+ });
+
+ const report = await adapter.getBoardMediaUsage('board-1', new AbortController().signal);
+
+ expect(usage.check).toHaveBeenCalledWith({ boardId: 'board-1', kind: 'board' }, expect.any(AbortSignal));
+ expect(usage.readProject).not.toHaveBeenCalled();
+ expect(report).toMatchObject({
+ checkedCount: 3,
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'generateReferenceImages' }] }],
+ inUseCount: 1,
+ scope: 'board',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
index ece7bdd34d..e78e269745 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
@@ -10,6 +10,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { useWorkbenchFocus } from '@workbench/focusRegions';
import { useProjectLibrarySelector } from '@workbench/projects/library';
+import { getProjectSyncSnapshot } from '@workbench/projects/syncStore';
import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';
import {
areWorkbenchPreferencesReady,
@@ -125,6 +126,19 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
},
galleryValues,
generateValues,
+ // Loaded on first use, beside the item actions it shares with the item deletion dialog.
+ getBoardMediaUsage: (boardId, signal) =>
+ import('@workbench/image-actions/mediaUsageReport').then(({ resolveMediaUsage }) =>
+ resolveMediaUsage(
+ { boardId, kind: 'board' },
+ {
+ getLoadedProjects: () => queries.getSnapshot().projects,
+ getSyncBase: (targetProjectId) => getProjectSyncSnapshot().projects[targetProjectId],
+ openProjectId: projectId,
+ },
+ { signal }
+ )
+ ),
getItemLabel,
noteBoardBrowsed: (boardId) => {
const values = getGalleryValues(queries.getProject(projectId), queries.getSnapshot().scopedDefaults);
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index 970b412849..d8c72548f0 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -226,6 +226,7 @@ describe('feature public-interface registry', () => {
expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/workflow/paletteSearch')).toEqual([]);
expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/gallery/paletteSearch')).toEqual([]);
expect(checkDependency('workbench/settings/ImageStorageSettings.tsx', '@features/gallery/storage')).toEqual([]);
+ expect(checkDependency('workbench/image-actions/mediaUsageReport.ts', '@features/gallery/mediaUsage')).toEqual([]);
expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/queue/queries')).toEqual([]);
expect(checkDependency('workbench/palette/WorkbenchCommandPaletteDialog.tsx', '@features/queue/queries')).toEqual(
[]
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index c7fea1255f..570bb4126b 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -8,6 +8,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[
'contracts',
'launchpad',
'mediaSlot',
+ 'mediaUsage',
'paletteSearch',
'picker',
'queries',
diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.md
index ba8edaf82b..d82886c3ba 100644
--- a/invokeai/frontend/webv2/src/features/gallery/README.md
+++ b/invokeai/frontend/webv2/src/features/gallery/README.md
@@ -6,7 +6,7 @@ Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, P
## Selection and destination
-The multi-selection belongs to the listing on screen. `settleGalleryValues` (`ui/galleryStateView.ts`), applied to every write of gallery values, drops `selectedImageNames` when a write changes what the listing holds (board, view, search, search scope, starred or media filter) without setting the selection itself; the primary item stays for Preview, and the grid acts on it only while it is listed. A deletion that reaches an item no loaded page holds, or more than one item, always confirms, listing the items, whatever the user's "Don't ask again".
+The multi-selection belongs to the listing on screen. `settleGalleryValues` (`ui/galleryStateView.ts`), applied to every write of gallery values, drops `selectedImageNames` when a write changes what the listing holds (board, view, search, search scope, starred or media filter) without setting the selection itself; the primary item stays for Preview, and the grid acts on it only while it is listed. A deletion that reaches an item no loaded page holds, or more than one item, always confirms, listing the items, whatever the user's "Don't ask again". Item deletion and "Delete board and media" both report where the media is still used before it goes (`mediaUsage` entry: `POST /api/v1/gallery/usage` and the report types; `react` entry: `GalleryMediaUsagePanel`, the section both dialogs render, which loads the report view only once a check settles). The server's answer is conservative: it counts every media name a project document holds, Gallery selection, recents and workflow last runs included. The host narrows it (`workbench/image-actions/mediaUsageReport.ts`): projects loaded in the tab are scanned from memory, a few other named projects (up to 4 MiB each, measured decoded) are read and scanned, the rest stay as the server counts them. Each project entry carries the content and caller's workspace revisions its names were read at, from the same transaction. A loaded project's scan stands when it reports every name the server found, or when those revisions are the ones the tab's copy builds on (the sync store's `revision` and `workspaceRevision`; never while the copy is in conflict or schema-refused, since it then holds local work beside revisions it does not build on): an unsaved edit then removed what it dropped, and nothing is read. Otherwise (the server is ahead, or either side's revisions are unknown) the server's copy is read, ahead of closed projects and within the same cap, and a name either copy uses counts; when the read fails or is skipped, the project keeps what its copy uses and the server's count, with "Its saved version couldn’t be checked." The scan (`workbench/image-actions/mediaUsage.ts`) names the surfaces it knows (live work, staged canvas results, canvas snapshots) and fails safe: a name anywhere else in the project counts as "Elsewhere in the project", except in fields listed there as only showing or recording media (Gallery state, workflow last runs, last submitted graphs) or as session state never saved (queue, run log, undo histories). An item request counts the items asked about: the server checks only those the caller may delete, without naming them; workflows, the legacy editor, projects kept for repair, queued jobs and other accounts pass through. A use, or a check that could not finish, always asks; a silent deletion first looks again at the projects in this tab, for a use added while the check ran. A second deletion that needs asking while a dialog is open is refused with a notice; a deletion already under way for an item (checking, asking or deleting) drops a repeated request for it; the board dialog checks only once deleting the media is ticked, once per opening, through the adapter's `getBoardMediaUsage`, stops a running check when the box is unticked or the dialog closes by any path (closing leaves the opening's query key), and keeps the opening's answer while unticked. Once the check answers, the checkbox, description, button and typed-name threshold count the items the server says go: on a shared board only the caller's own ("your N items"), and none at all when they added none.
New results without a board of their own go to `autoAddBoardId` when one is chosen, else to the project's inbox (Uncategorized for a gallery without one); only `followSelectedBoard`, off by default, makes them follow the selected board. While following is off, selecting a board, Find in Gallery and reveals therefore never move the destination; while it is on, anything that selects a board moves it, by definition. Earlier builds stored `autoAddBoardId: 'follow'` for following, their default; it reads as the default destination. The header's Saving to control and the board list's destination marker name it as submissions resolve it (`useGalleryDestination`), redirection to the inbox included.
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts b/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts
new file mode 100644
index 0000000000..d988e6ddc2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts
@@ -0,0 +1,134 @@
+/**
+ * What still uses gallery media the user is about to delete: the server's reference check as the client reads it, and
+ * the report a deletion dialog shows. The server answer is conservative (it counts gallery selections, recents and
+ * workflow last runs inside projects); a host that can open projects narrows it before building the report, dropping
+ * only what it knows shows or records media rather than working on it.
+ */
+
+import type { GalleryItemRef } from './items';
+
+/** What to check: these items, or every item on a board (what deleting the board with its media removes). */
+export type GalleryMediaUsageRequest =
+ | { kind: 'items'; refs: readonly GalleryItemRef[] }
+ | { boardId: string; kind: 'board' };
+
+/** Names a source uses among the checked media. The lists are capped; the counts are true. */
+export interface GalleryMediaUsageNames {
+ imageCount: number;
+ imageNames: string[];
+ videoCount: number;
+ videoNames: string[];
+}
+
+export type GalleryMediaUsageDocumentKind = 'legacyEditor' | 'project' | 'quarantinedProject' | 'workflow';
+
+/** One of the caller's own saved documents; `other` stands for a kind this build does not know. */
+export interface GalleryMediaUsageDocument extends GalleryMediaUsageNames {
+ id: string;
+ kind: GalleryMediaUsageDocumentKind | 'other';
+ name: string | null;
+ /** For a project: the content revision its names were read at; null for other kinds, or when not known. */
+ revision: number | null;
+ /**
+ * For a project whose `revision` is known: the caller's workspace revision its names were read at, null while the
+ * caller has none there. Null for other kinds.
+ */
+ workspaceRevision: number | null;
+}
+
+export interface GalleryMediaUsage {
+ checkedImageCount: number;
+ checkedVideoCount: number;
+ /** The caller's documents that use checked media, at most a hundred of `documentsTotal`. */
+ documents: GalleryMediaUsageDocument[];
+ documentsTotal: number;
+ inUseImageCount: number;
+ inUseVideoCount: number;
+ /** Other accounts' documents and queue work, counted without saying whose. */
+ otherAccounts: { documentCount: number; imageCount: number; queueItemCount: number; videoCount: number };
+ /** The caller's waiting or running queue work that names checked media. */
+ queue: GalleryMediaUsageNames & { itemCount: number };
+}
+
+/** Project surfaces that can hold media, in panel order; the labels are the Gallery's translations. */
+export type GalleryMediaUsageSurface =
+ | 'generateReferenceImages'
+ | 'canvasRaster'
+ | 'canvasControl'
+ | 'canvasRegionalGuidance'
+ | 'canvasInpaintMask'
+ | 'canvasStaging'
+ | 'canvasSnapshot'
+ | 'upscale'
+ | 'video'
+ | 'workflow'
+ /** Anything else in the project that names the media: the scan fails safe on fields it has no surface for. */
+ | 'otherProjectState';
+
+export interface GalleryMediaUsageSurfaceRow {
+ /** How many checked items the surface uses. */
+ count: number;
+ /** The workflow's or snapshot's name, for the surfaces that have one. */
+ label?: string;
+ surface: GalleryMediaUsageSurface;
+}
+
+/** One line of the report; `count` is how many checked items the source uses. */
+export type GalleryMediaUsageGroup =
+ /** The project the deletion is made from; `savedCopyUnchecked` as for `project`. */
+ | { count: number; kind: 'openProject'; savedCopyUnchecked?: true; surfaces: GalleryMediaUsageSurfaceRow[] }
+ | {
+ count: number;
+ kind: 'project';
+ name: string | null;
+ /**
+ * The project is open, but its saved version, which the server says uses more of the media, could not be
+ * checked; `count` includes those uses, `surfaces` only what the open copy uses.
+ */
+ savedCopyUnchecked?: true;
+ surfaces: GalleryMediaUsageSurfaceRow[];
+ }
+ /** A project the host could not open to see where it uses the media. */
+ | { count: number; kind: 'projectUnchecked'; name: string | null }
+ | { count: number; kind: 'quarantinedProject'; name: string | null }
+ | { count: number; kind: 'workflow'; name: string | null }
+ | { count: number; kind: 'legacyEditor' }
+ | { count: number; kind: 'otherDocument'; name: string | null }
+ /** Documents past the server's listing cap. */
+ | { documentCount: number; kind: 'moreDocuments' }
+ | { count: number; jobCount: number; kind: 'queue' }
+ | { count: number; kind: 'otherAccounts' };
+
+export interface GalleryMediaUsageReport {
+ /** Items checked: the requested items, or the board's as the server counted them (the items deleting it removes). */
+ checkedCount: number;
+ groups: GalleryMediaUsageGroup[];
+ /** Distinct checked items something uses; a lower bound where the server's name lists were capped. */
+ inUseCount: number;
+ /** Every checked item is an image, so the summary can say "images". */
+ onlyImages: boolean;
+ scope: 'board' | 'items';
+ /**
+ * Whether the server check ran: `unavailable` when it did not finish (offline, an older server, a timeout),
+ * `tooManyItems` when the selection is past what one check takes. Either way only projects open in this tab were
+ * checked, not other projects, workflows, the legacy editor, queued jobs or other accounts. A board's report always
+ * has the server's answer, which alone knows the board's items.
+ */
+ serverCheck: 'complete' | 'tooManyItems' | 'unavailable';
+}
+
+/** What a deletion dialog shows while the check runs, when it failed outright, and once it has a report. */
+/** A check that has answered: its report, or that it failed outright. */
+export type GalleryMediaUsageSettledCheck = { status: 'failed' } | { report: GalleryMediaUsageReport; status: 'ready' };
+
+/**
+ * What a deletion dialog shows: the check running, failed outright, or its report. A retry runs while the previous
+ * answer stays on screen (`previous`), so what is already known does not vanish for the length of the check.
+ */
+export type GalleryMediaUsageCheck =
+ | { previous?: GalleryMediaUsageSettledCheck; status: 'checking' }
+ | GalleryMediaUsageSettledCheck;
+
+/** Whether the report gives no reason to stop and ask: nothing uses the media and every source was checked. */
+export const isGalleryMediaUnused = (report: GalleryMediaUsageReport): boolean =>
+ report.groups.length === 0 && report.serverCheck === 'complete';
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index a10e2e5165..15eec7ba04 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -22,6 +22,7 @@ import { ApiError } from '@platform/transport/http';
import {
ALL_READABLE_BOARDS_ID,
addImagesToGalleryBoard,
+ checkGalleryMediaUsage,
createGalleryBoard,
galleryBoardExists,
deleteGalleryBoard,
@@ -105,6 +106,152 @@ describe('deleteGalleryBoard outcomes', () => {
});
});
+describe('checkGalleryMediaUsage', () => {
+ const usageBody = (overrides: Record<string, unknown> = {}) => ({
+ checked_image_count: 2,
+ checked_video_count: 1,
+ documents: [
+ {
+ id: 'legacy_editor',
+ image_count: 1,
+ image_names: ['a.png'],
+ kind: 'legacy_editor',
+ name: null,
+ revision: null,
+ video_count: 0,
+ video_names: [],
+ workspace_revision: null,
+ },
+ {
+ id: 'project-1',
+ image_count: 1200,
+ image_names: ['a.png', 'b.png'],
+ kind: 'project',
+ name: 'Harbor Tower',
+ revision: 7,
+ video_count: 1,
+ video_names: ['c.mp4'],
+ workspace_revision: 3,
+ },
+ {
+ id: 'later-kind',
+ image_count: 1,
+ image_names: ['b.png'],
+ kind: 'storyboard',
+ name: ' ',
+ // Revisions are only a hint: a malformed one reads as unknown rather than failing the check.
+ revision: '2',
+ video_count: 0,
+ video_names: [],
+ workspace_revision: -1,
+ },
+ ],
+ documents_total: 140,
+ in_use_image_count: 2,
+ in_use_video_count: 1,
+ other_accounts: { document_count: 3, image_count: 1, queue_item_count: 2, video_count: 0 },
+ queue: { image_count: 1, image_names: ['a.png'], item_count: 2, video_count: 0, video_names: [] },
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ accountLifecycle.activate('user-a');
+ mocks.apiFetchJson.mockReset();
+ });
+
+ it('asks about the items by kind, or about a whole board, and maps the answer', async () => {
+ mocks.apiFetchJson.mockResolvedValue(usageBody());
+
+ const usage = await checkGalleryMediaUsage({
+ kind: 'items',
+ refs: [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'video', name: 'c.mp4' },
+ { kind: 'image', name: 'b.png' },
+ ],
+ });
+ await checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });
+
+ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[0]?.[1]?.body))).toEqual({
+ image_names: ['a.png', 'b.png'],
+ video_names: ['c.mp4'],
+ });
+ expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toBe('/api/v1/gallery/usage');
+ expect(mocks.apiFetchJson.mock.calls[0]?.[1]?.method).toBe('POST');
+ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[1]?.[1]?.body))).toEqual({ board_id: 'board-1' });
+ expect(usage).toEqual({
+ checkedImageCount: 2,
+ checkedVideoCount: 1,
+ documents: [
+ {
+ id: 'legacy_editor',
+ imageCount: 1,
+ imageNames: ['a.png'],
+ kind: 'legacyEditor',
+ name: null,
+ revision: null,
+ videoCount: 0,
+ videoNames: [],
+ workspaceRevision: null,
+ },
+ {
+ id: 'project-1',
+ imageCount: 1200,
+ imageNames: ['a.png', 'b.png'],
+ kind: 'project',
+ name: 'Harbor Tower',
+ revision: 7,
+ videoCount: 1,
+ videoNames: ['c.mp4'],
+ workspaceRevision: 3,
+ },
+ // A kind this build does not know still uses the media; a blank name reads as none.
+ {
+ id: 'later-kind',
+ imageCount: 1,
+ imageNames: ['b.png'],
+ kind: 'other',
+ name: null,
+ revision: null,
+ videoCount: 0,
+ videoNames: [],
+ workspaceRevision: null,
+ },
+ ],
+ documentsTotal: 140,
+ inUseImageCount: 2,
+ inUseVideoCount: 1,
+ otherAccounts: { documentCount: 3, imageCount: 1, queueItemCount: 2, videoCount: 0 },
+ queue: { imageCount: 1, imageNames: ['a.png'], itemCount: 2, videoCount: 0, videoNames: [] },
+ });
+ });
+
+ it('fails on a malformed answer rather than reading it as nothing in use', async () => {
+ mocks.apiFetchJson.mockResolvedValue(usageBody({ in_use_image_count: undefined }));
+
+ await expect(checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' })).rejects.toThrow(TypeError);
+ });
+
+ it('drops an answer that arrives after the account changed', async () => {
+ let answer: (value: unknown) => void = () => {};
+ mocks.apiFetchJson.mockReturnValue(
+ new Promise((resolve) => {
+ answer = resolve;
+ })
+ );
+
+ const check = checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });
+ const signal = mocks.apiFetchJson.mock.calls[0]?.[1]?.signal as AbortSignal;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ answer(usageBody());
+
+ await expect(check).rejects.toThrow('no longer active');
+ expect(signal.aborted).toBe(true);
+ });
+});
+
describe('image mutation outcomes', () => {
beforeEach(() => {
accountLifecycle.activate('user-a');
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 34551cd102..1e638536d1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -8,6 +8,12 @@ import type {
GalleryItemsPage,
GalleryVideoItem,
} from '@features/gallery/core/items';
+import type {
+ GalleryMediaUsage,
+ GalleryMediaUsageDocumentKind,
+ GalleryMediaUsageNames,
+ GalleryMediaUsageRequest,
+} from '@features/gallery/core/mediaUsage';
import type { GallerySemanticQuery } from '@features/gallery/core/semanticImageQuery';
import type {
GalleryBoard,
@@ -1173,6 +1179,110 @@ export const deleteGalleryBoard = async (
};
};
+type GalleryMediaUsageWire = components['schemas']['GalleryMediaUsage'];
+type GalleryMediaUsageNamesWire = Pick<
+ components['schemas']['GalleryMediaUsageQueue'],
+ 'image_count' | 'image_names' | 'video_count' | 'video_names'
+>;
+type GalleryMediaUsageRequestWire = components['schemas']['GalleryMediaUsageRequest'];
+
+const GALLERY_MEDIA_USAGE_DOCUMENT_KINDS: Readonly<Record<string, GalleryMediaUsageDocumentKind>> = {
+ legacy_editor: 'legacyEditor',
+ project: 'project',
+ quarantined_project: 'quarantinedProject',
+ workflow: 'workflow',
+};
+
+/** A malformed answer must fail the check, never read as "nothing uses it". */
+const readUsageCount = (value: unknown, field: string): number => {
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
+ throw new TypeError(`Gallery media usage field "${field}" must be a non-negative integer.`);
+ }
+
+ return value;
+};
+
+const readUsageNames = (value: unknown, field: string): string[] => {
+ if (!Array.isArray(value) || !value.every((name): name is string => typeof name === 'string')) {
+ throw new TypeError(`Gallery media usage field "${field}" must be an array of strings.`);
+ }
+
+ return value;
+};
+
+/** A revision is only a hint for narrowing: one that is not a non-negative integer reads as unknown. */
+const readUsageRevision = (value: unknown): number | null =>
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
+
+const mapGalleryMediaUsageNames = (wire: GalleryMediaUsageNamesWire, field: string): GalleryMediaUsageNames => ({
+ imageCount: readUsageCount(wire.image_count, `${field}.image_count`),
+ imageNames: readUsageNames(wire.image_names, `${field}.image_names`),
+ videoCount: readUsageCount(wire.video_count, `${field}.video_count`),
+ videoNames: readUsageNames(wire.video_names, `${field}.video_names`),
+});
+
+const mapGalleryMediaUsage = (body: GalleryMediaUsageWire): GalleryMediaUsage => {
+ if (!Array.isArray(body.documents) || typeof body.queue !== 'object' || typeof body.other_accounts !== 'object') {
+ throw new TypeError('Gallery media usage response is malformed.');
+ }
+
+ return {
+ checkedImageCount: readUsageCount(body.checked_image_count, 'checked_image_count'),
+ checkedVideoCount: readUsageCount(body.checked_video_count, 'checked_video_count'),
+ documents: body.documents.map((document, index) => ({
+ ...mapGalleryMediaUsageNames(document, `documents[${index}]`),
+ id: String(document.id),
+ // A kind added after this build still uses the media: it is listed, not dropped.
+ kind: GALLERY_MEDIA_USAGE_DOCUMENT_KINDS[document.kind] ?? 'other',
+ name: typeof document.name === 'string' && document.name.trim() !== '' ? document.name : null,
+ revision: readUsageRevision(document.revision),
+ workspaceRevision: readUsageRevision(document.workspace_revision),
+ })),
+ documentsTotal: readUsageCount(body.documents_total, 'documents_total'),
+ inUseImageCount: readUsageCount(body.in_use_image_count, 'in_use_image_count'),
+ inUseVideoCount: readUsageCount(body.in_use_video_count, 'in_use_video_count'),
+ otherAccounts: {
+ documentCount: readUsageCount(body.other_accounts.document_count, 'other_accounts.document_count'),
+ imageCount: readUsageCount(body.other_accounts.image_count, 'other_accounts.image_count'),
+ queueItemCount: readUsageCount(body.other_accounts.queue_item_count, 'other_accounts.queue_item_count'),
+ videoCount: readUsageCount(body.other_accounts.video_count, 'other_accounts.video_count'),
+ },
+ queue: {
+ ...mapGalleryMediaUsageNames(body.queue, 'queue'),
+ itemCount: readUsageCount(body.queue.item_count, 'queue.item_count'),
+ },
+ };
+};
+
+/**
+ * What still uses these items, or a board's items, per the server: the caller's projects, workflows and legacy editor
+ * state, their waiting or running queue work, and other accounts' use without identities. Names the caller may not
+ * delete are left out, as the delete endpoints skip them.
+ */
+export const checkGalleryMediaUsage = async (
+ request: GalleryMediaUsageRequest,
+ signal?: AbortSignal
+): Promise<GalleryMediaUsage> => {
+ const owner = captureAccountScope();
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
+ const payload: GalleryMediaUsageRequestWire =
+ request.kind === 'board'
+ ? { board_id: request.boardId }
+ : {
+ image_names: request.refs.filter((ref) => ref.kind === 'image').map((ref) => ref.name),
+ video_names: request.refs.filter((ref) => ref.kind === 'video').map((ref) => ref.name),
+ };
+ const body = await apiFetchJson<GalleryMediaUsageWire>('/api/v1/gallery/usage', {
+ body: JSON.stringify(payload),
+ method: 'POST',
+ signal: requestSignal,
+ });
+
+ assertAccountScopeCurrent(owner);
+
+ return mapGalleryMediaUsage(body);
+};
+
export interface GalleryItemOrganizationTransportResult {
affectedBoardIds: string[];
succeededNames: string[];
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index 85f740b04a..928733d3e1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -1,4 +1,5 @@
import type { GalleryItem, GalleryItemKind, GalleryItemRef, GalleryItemsPage } from '@features/gallery/core/items';
+import type { GalleryMediaUsageReport } from '@features/gallery/core/mediaUsage';
import type { GallerySemanticQuery, GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';
import type { GallerySettings } from '@features/gallery/core/settings';
import type {
@@ -178,6 +179,33 @@ const getAccountKey = (owner: AccountScope): GalleryAccountKey => ({
epoch: owner.epoch,
});
+/**
+ * Where a board's media is still used, for one opening of its deletion dialog: a reopened dialog asks again, and
+ * nothing refetches it while open. `opening` is null while the dialog is closed, so a closing dialog leaves its
+ * opening's key, which stops a check still running there. Kept outside the `gallery` root so gallery invalidations
+ * never re-run a check the user is reading.
+ */
+export const galleryBoardMediaUsageQueryOptions = ({
+ boardId,
+ load,
+ opening,
+ owner,
+}: {
+ boardId: string;
+ load: (boardId: string, signal: AbortSignal) => Promise<GalleryMediaUsageReport>;
+ opening: number | null;
+ owner: AccountScope;
+}) =>
+ queryOptions({
+ gcTime: 0,
+ queryFn: ({ signal }) => load(boardId, signal),
+ queryKey: ['galleryMediaUsage', 'board', getAccountKey(owner), boardId, opening] as const,
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
+ retry: false,
+ staleTime: Number.POSITIVE_INFINITY,
+ });
+
const normalizePageOffset = (offset: number): number =>
Math.max(0, Math.floor(offset / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE);
diff --git a/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts b/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts
new file mode 100644
index 0000000000..bec08cdf33
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts
@@ -0,0 +1,14 @@
+/** Where media about to be deleted is still used: the server check and the report types. */
+export {
+ isGalleryMediaUnused,
+ type GalleryMediaUsage,
+ type GalleryMediaUsageCheck,
+ type GalleryMediaUsageDocument,
+ type GalleryMediaUsageGroup,
+ type GalleryMediaUsageReport,
+ type GalleryMediaUsageRequest,
+ type GalleryMediaUsageSettledCheck,
+ type GalleryMediaUsageSurface,
+ type GalleryMediaUsageSurfaceRow,
+} from './core/mediaUsage';
+export { checkGalleryMediaUsage } from './data/backend';
diff --git a/invokeai/frontend/webv2/src/features/gallery/react.test.ts b/invokeai/frontend/webv2/src/features/gallery/react.test.ts
index f3f84ac8fe..0284a27522 100644
--- a/invokeai/frontend/webv2/src/features/gallery/react.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/react.test.ts
@@ -1,9 +1,16 @@
import { describe, expect, it } from 'vitest';
-const sources = import.meta.glob('./react.ts', { eager: true, import: 'default', query: '?raw' }) as Record<
- string,
- string
->;
+const sources = import.meta.glob(['./react.ts', './ui/GalleryMediaUsagePanel.tsx'], {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+}) as Record<string, string>;
+
+const staticSpecifiers = (source: string | undefined): Set<string> =>
+ new Set([...(source ?? '').matchAll(/from '([^']+)'/g)].map(([, specifier]) => specifier));
+
+const dynamicSpecifiers = (source: string | undefined): Set<string> =>
+ new Set([...(source ?? '').matchAll(/import\('([^']+)'\)/g)].map(([, specifier]) => specifier));
/**
* The React entry is bundled with the eager gallery-state chunk. A re-export from a lazy gallery module (uploads,
@@ -12,13 +19,25 @@ const sources = import.meta.glob('./react.ts', { eager: true, import: 'default',
* module orders differ, so only the entry's import surface can be checked cheaply.
*/
describe('gallery React entry', () => {
- it('reaches only the eager UI port, the image recovery leaf hook and core types', () => {
+ it('reaches only the eager UI port, the image recovery leaf hook, the media usage panel and core types', () => {
const source = sources['./react.ts'];
- const specifiers = [...(source ?? '').matchAll(/from '([^']+)'/g)].map(([, specifier]) => specifier);
expect(source).toBeDefined();
- expect(new Set(specifiers)).toEqual(
- new Set(['./ui/GalleryUiContext', './ui/useGalleryImageRecovery', './core/types'])
+ expect(staticSpecifiers(source)).toEqual(
+ new Set(['./ui/GalleryUiContext', './ui/useGalleryImageRecovery', './ui/GalleryMediaUsagePanel', './core/types'])
+ );
+ });
+
+ // The panel rides in the eager chunk so the deletion dialogs' live region exists as they open. It stays a leaf:
+ // its report view (Scrollable, tooltips, the report's copy) loads only through its lazy import.
+ it('keeps the media usage panel a leaf whose report view loads lazily', () => {
+ const source = sources['./ui/GalleryMediaUsagePanel.tsx'];
+
+ expect(source).toBeDefined();
+ expect(staticSpecifiers(source)).toEqual(
+ new Set(['@features/gallery/core/mediaUsage', '@chakra-ui/react', 'react', 'react-i18next'])
);
+ expect(dynamicSpecifiers(source)).toEqual(new Set(['./GalleryMediaUsageSection']));
+ expect(source).toMatch(/^import type \{[^}]*\} from '@features\/gallery\/core\/mediaUsage';$/m);
});
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.ts
index cd8d08fec1..1cc72c91ca 100644
--- a/invokeai/frontend/webv2/src/features/gallery/react.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts
@@ -12,6 +12,7 @@ export {
useOptionalGalleryHostProjectContext,
} from './ui/GalleryUiContext';
export { useGalleryImageRecovery } from './ui/useGalleryImageRecovery';
+export { GalleryMediaUsagePanel } from './ui/GalleryMediaUsagePanel';
export type { GalleryProjectRef } from './core/types';
// Only the eager UI port and leaf hooks live here. This entry is bundled with the eager gallery-state chunk;
// reaching a lazy gallery module (uploads, the picker) from it makes that chunk and the picker chunk import each
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
index 83489316ae..2cc2971ec4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
@@ -1,7 +1,9 @@
+import type { GalleryMediaUsageReport } from '@features/gallery/core/mediaUsage';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
import type { GalleryBoard, GalleryBoardAccess, GalleryBoardAction } from '@features/gallery/core/types';
import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act, useCallback, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -19,13 +21,33 @@ vi.mock('react-i18next', () => ({
const messages: Record<string, string> = {
'widgets.gallery.assetCount': `${String(values?.count)} uploads`,
'common.cancel': 'Cancel',
+ 'common.retry': 'Retry',
'widgets.gallery.deleteBoard': 'Delete board',
'widgets.gallery.deleteBoardAndMedia': `Delete board and ${String(values?.count)} items`,
'widgets.gallery.deleteBoardDescription': `Its ${String(values?.media)} move to Uncategorized.`,
'widgets.gallery.deleteBoardEmptyDescription': 'The board is empty.',
+ 'widgets.gallery.deleteBoardWithMediaDescription': `Its ${String(values?.media)} are deleted with it.`,
+ 'widgets.gallery.deleteBoardWithOwnMediaDescription': `Your ${String(
+ values?.media
+ )} on it are deleted with it; the rest move to Uncategorized.`,
+ 'widgets.gallery.deleteBoardWithNoOwnMediaDescription':
+ 'None of its media is yours; all of it moves to Uncategorized.',
+ 'widgets.gallery.deleteBoardIncludeOwnMedia': `Also permanently delete your ${String(values?.count)} items`,
+ 'widgets.gallery.deleteBoardIncludeOwnMediaNone': 'Also permanently delete your items',
+ 'widgets.gallery.deleteBoardAndOwnMedia': `Delete board and your ${String(values?.count)} items`,
'widgets.gallery.deleteBoardIncludeMedia': `Also permanently delete its ${String(values?.count)} items`,
'widgets.gallery.deleteBoardQuestion': `Delete board "${String(values?.name)}"?`,
'widgets.gallery.deleteBoardTypeName': `Type "${String(values?.name)}" to confirm`,
+ 'widgets.gallery.deleteInUse.checking': 'Checking where this media is used…',
+ 'widgets.gallery.deleteInUse.none': 'Nothing uses this media.',
+ 'widgets.gallery.deleteInUse.failed': 'Couldn’t check where this media is used.',
+ 'widgets.gallery.deleteInUse.group.project': `Project “${String(values?.name)}”`,
+ 'widgets.gallery.deleteInUse.itemCount': `${String(values?.count)} items`,
+ 'widgets.gallery.deleteInUse.summaryBoard': `${String(values?.count)} of the ${String(
+ values?.media
+ )} this deletes are still in use:`,
+ 'widgets.gallery.deleteInUse.summaryOne': 'Still in use:',
+ 'widgets.gallery.deleteInUse.surface.canvasRaster': 'Canvas raster layers',
'widgets.gallery.downloadBoard': 'Download board',
'widgets.gallery.downloadBoardWithOmission': `Download board (${String(values?.count)} video omitted)`,
'widgets.gallery.imageCount': `${String(values?.count)} images`,
@@ -63,6 +85,7 @@ const context = {
archiveBoard: vi.fn(),
deleteBoard: vi.fn(),
downloadBoard: vi.fn(),
+ getBoardMediaUsage: vi.fn<(boardId: string, signal: AbortSignal) => Promise<GalleryMediaUsageReport>>(),
moveBoard: vi.fn(),
renameBoard: vi.fn(),
setBoardGeneralAccess: vi.fn(),
@@ -87,10 +110,12 @@ const targetContext = {
} as unknown as GalleryWidgetContextValue;
let host: HTMLDivElement | null = null;
+let queryClient = new QueryClient();
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
beforeEach(async () => {
+ queryClient = new QueryClient();
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -98,9 +123,11 @@ beforeEach(async () => {
await act(async () => {
root?.render(
<ChakraProvider value={system}>
- <GalleryWidgetContext value={context}>
- <GalleryBoardMenu target={target} onClose={noop} />
- </GalleryWidgetContext>
+ <QueryClientProvider client={queryClient}>
+ <GalleryWidgetContext value={context}>
+ <GalleryBoardMenu target={target} onClose={noop} />
+ </GalleryWidgetContext>
+ </QueryClientProvider>
</ChakraProvider>
);
await Promise.resolve();
@@ -158,6 +185,9 @@ it('deletes the media too only behind its checkbox, naming how many items go', a
await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[data-part="label"]')!));
expect(dialog.textContent).toContain('Also permanently delete its 3 items');
+ // The description follows the choice: the media no longer moves anywhere.
+ expect(dialog.textContent).toContain('Its 2 images and 1 videos are deleted with it.');
+ expect(dialog.textContent).not.toContain('move to Uncategorized');
await act(() => userEvent.click(dialogButton('Delete board and 3 items')!));
expect(context.actions.deleteBoard).toHaveBeenLastCalledWith('board-1', true);
@@ -201,6 +231,308 @@ it('starts each opening of the delete dialog over, for the same board too', asyn
expect(dialogButton('Delete board and 61 items')!.disabled).toBe(true);
});
+const boardUsageReport: GalleryMediaUsageReport = {
+ checkedCount: 3,
+ groups: [{ count: 2, kind: 'project', name: 'Harbor Tower', surfaces: [{ count: 2, surface: 'canvasRaster' }] }],
+ inUseCount: 2,
+ onlyImages: false,
+ scope: 'board',
+ serverCheck: 'complete',
+};
+
+/** The report's code loads lazily on the first settled check; a cold transform under a busy run can take a while. */
+const REPORT_WAIT = { timeout: 5000 };
+
+const tickDeleteMedia = (dialog: HTMLElement) =>
+ act(() => userEvent.click(dialog.querySelector<HTMLElement>('[data-part="label"]')!));
+
+it('checks where the media is used once deleting it is asked for, and shows the report beside the choice', async () => {
+ const getBoardMediaUsage = vi.mocked(context.actions.getBoardMediaUsage);
+ let settle: (report: GalleryMediaUsageReport) => void = () => {};
+ getBoardMediaUsage.mockReset().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settle = resolve;
+ })
+ );
+ const dialog = await openDeleteDialog();
+
+ // Keeping the media breaks nothing, so nothing is checked for it.
+ expect(getBoardMediaUsage).not.toHaveBeenCalled();
+ await tickDeleteMedia(dialog);
+
+ expect(getBoardMediaUsage).toHaveBeenCalledExactlyOnceWith('board-1', expect.any(AbortSignal));
+ expect(dialog.textContent).toContain('Checking where this media is used…');
+ expect(dialogButton('Delete board and 3 items')!.disabled).toBe(false);
+
+ await act(() => settle(boardUsageReport));
+
+ await vi.waitFor(
+ () => expect(dialog.textContent).toContain('2 of the 3 items this deletes are still in use:'),
+ REPORT_WAIT
+ );
+ expect(dialog.textContent).toContain('Project “Harbor Tower”2 items');
+ expect(dialog.textContent).toContain('Canvas raster layers2 items');
+ await act(() => userEvent.click(dialogButton('Delete board and 3 items')!));
+ expect(context.actions.deleteBoard).toHaveBeenLastCalledWith('board-1', true);
+});
+
+it('warns when the check failed, still lets the board and its media go, and checks again on Retry', async () => {
+ const getBoardMediaUsage = vi.mocked(context.actions.getBoardMediaUsage);
+ let settleRetry: (report: GalleryMediaUsageReport) => void = () => {};
+ getBoardMediaUsage
+ .mockReset()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ settleRetry = resolve;
+ })
+ );
+ const dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Couldn’t check where this media is used.'), REPORT_WAIT);
+ expect(dialogButton('Delete board and 3 items')!.disabled).toBe(false);
+
+ await act(() => userEvent.click(dialogButton('Retry')!));
+
+ // Retry gives way to the checking state; focus stays in the dialog, on the panel that reads the outcome.
+ const panel = dialog.querySelector<HTMLElement>('[aria-live="polite"]');
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Checking where this media is used…'));
+ expect(document.activeElement).toBe(panel);
+
+ await act(() => settleRetry({ ...boardUsageReport, checkedCount: 1, inUseCount: 1, onlyImages: true }));
+
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Still in use:'), REPORT_WAIT);
+ expect(document.activeElement).toBe(panel);
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ expect(getBoardMediaUsage).toHaveBeenCalledTimes(2);
+});
+
+it('asks once per opening: not again when ticked twice, but again when the dialog reopens', async () => {
+ const getBoardMediaUsage = vi.mocked(context.actions.getBoardMediaUsage);
+ getBoardMediaUsage.mockReset().mockResolvedValue(boardUsageReport);
+ let dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+ await vi.waitFor(() => expect(dialog.textContent).toContain('still in use'), REPORT_WAIT);
+ await tickDeleteMedia(dialog);
+ expect(dialog.textContent).not.toContain('still in use');
+ await tickDeleteMedia(dialog);
+ expect(dialog.textContent).toContain('still in use');
+ expect(getBoardMediaUsage).toHaveBeenCalledOnce();
+
+ await act(() => userEvent.click(dialogButton('Cancel')!));
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ dialog = await openDeleteDialog();
+ await tickDeleteMedia(dialog);
+
+ await vi.waitFor(() => expect(getBoardMediaUsage).toHaveBeenCalledTimes(2));
+});
+
+/** A check that never answers, recording the signal of each call. */
+const hangingChecks = () => {
+ const signals: AbortSignal[] = [];
+ vi.mocked(context.actions.getBoardMediaUsage)
+ .mockReset()
+ .mockImplementation((_boardId, signal) => {
+ signals.push(signal);
+ return new Promise(() => {});
+ });
+
+ return signals;
+};
+
+const closeDialog = {
+ cancel: () => act(() => userEvent.click(dialogButton('Cancel')!)),
+ escape: () => act(() => userEvent.keyboard('{Escape}')),
+ // A refetch finds the board gone (deleted elsewhere, or access revoked): the menu closes the dialog on its own.
+ external: () => renderMenuFor(board as GalleryBoard, { gallery: { ...context.gallery, boards: [] } } as never),
+};
+
+it.each(Object.keys(closeDialog) as (keyof typeof closeDialog)[])(
+ 'stops a running check when the dialog closes (%s)',
+ async (how) => {
+ const signals = hangingChecks();
+ const dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+ await vi.waitFor(() => expect(signals).toHaveLength(1));
+ expect(signals[0]!.aborted).toBe(false);
+
+ await closeDialog[how]();
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ expect(signals[0]!.aborted).toBe(true);
+ }
+);
+
+it('stops a running check when the media is unticked, and asks again when it is ticked once more', async () => {
+ const signals = hangingChecks();
+ const dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+ await vi.waitFor(() => expect(signals).toHaveLength(1));
+ await tickDeleteMedia(dialog);
+ expect(signals[0]!.aborted).toBe(true);
+
+ // The stopped check left no answer behind: ticking again within the same opening asks again.
+ await tickDeleteMedia(dialog);
+ await vi.waitFor(() => expect(signals).toHaveLength(2));
+ expect(signals[1]!.aborted).toBe(false);
+ expect(dialog.textContent).toContain('Checking where this media is used…');
+});
+
+/** Opens the dialog for `menuBoard`, ticks the media and answers the check with `checkedCount` items to delete. */
+const answerWithCheckedCount = async (menuBoard: GalleryBoard, checkedCount: number, onlyImages = true) => {
+ let settle: (report: GalleryMediaUsageReport) => void = () => {};
+ vi.mocked(context.actions.getBoardMediaUsage)
+ .mockReset()
+ .mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settle = resolve;
+ })
+ );
+ await renderMenuFor(menuBoard);
+ const dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+ const before = dialog.textContent;
+ const regionBefore = dialog.querySelector<HTMLElement>('[aria-live="polite"]');
+ const regionBeforePosition = regionBefore ? getComputedStyle(regionBefore).position : null;
+ await act(() =>
+ settle({
+ ...boardUsageReport,
+ checkedCount,
+ groups: checkedCount === 0 ? [] : boardUsageReport.groups,
+ inUseCount: Math.min(1, checkedCount),
+ onlyImages,
+ })
+ );
+ await vi.waitFor(() => expect(dialog.textContent).not.toContain('Checking where this media is used…'), REPORT_WAIT);
+
+ return { before, dialog, regionBefore, regionBeforePosition };
+};
+
+it('names only the caller’s own items once the check says only those go, and keeps saying so when unticked', async () => {
+ // A shared board of 61 items; the caller added two of them.
+ const shared = { ...board, assetCount: 40, imageCount: 20 } as GalleryBoard;
+ const { before, dialog } = await answerWithCheckedCount(shared, 2);
+
+ // Until the check answers, the board's own counts are all there is, and so many items need the name typed.
+ expect(before).toContain('Its 20 images, 1 videos and 40 uploads are deleted with it.');
+ expect(before).toContain('Type "Board 1" to confirm');
+
+ expect(dialog.textContent).toContain('Your 2 images on it are deleted with it; the rest move to Uncategorized.');
+ expect(dialog.textContent).toContain('Also permanently delete your 2 items');
+ expect(dialog.textContent).toContain('1 of the 2 images this deletes are still in use:');
+ // Two items are not many: no name to type.
+ expect(dialog.textContent).not.toContain('to confirm');
+ expect(dialogButton('Delete board and your 2 items')!.disabled).toBe(false);
+
+ await tickDeleteMedia(dialog);
+ expect(dialog.textContent).toContain('Also permanently delete your 2 items');
+ await tickDeleteMedia(dialog);
+ await act(() => userEvent.click(dialogButton('Delete board and your 2 items')!));
+ expect(context.actions.deleteBoard).toHaveBeenLastCalledWith('board-1', true);
+});
+
+it('keeps the name field, and what was typed, once typing started, however the answer lowers the count', async () => {
+ let settle: (report: GalleryMediaUsageReport) => void = () => {};
+ vi.mocked(context.actions.getBoardMediaUsage)
+ .mockReset()
+ .mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settle = resolve;
+ })
+ );
+ await renderMenuFor({ ...board, assetCount: 40, imageCount: 20 } as GalleryBoard);
+ let dialog = await openDeleteDialog();
+ const nameField = () => dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])');
+
+ await tickDeleteMedia(dialog);
+ await act(() => userEvent.type(nameField()!, 'Boa'));
+ await act(() => settle({ ...boardUsageReport, checkedCount: 2, inUseCount: 1, onlyImages: true }));
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Also permanently delete your 2 items'), REPORT_WAIT);
+
+ // Two items would not ask for the name, but the user had started: the field and its requirement stay.
+ expect(nameField()?.value).toBe('Boa');
+ expect(dialogButton('Delete board and your 2 items')!.disabled).toBe(true);
+ await act(() => userEvent.type(nameField()!, 'rd 1'));
+ expect(dialogButton('Delete board and your 2 items')!.disabled).toBe(false);
+
+ // A new opening starts over: the answer again decides.
+ await act(() => userEvent.click(dialogButton('Cancel')!));
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ dialog = await openDeleteDialog();
+ await tickDeleteMedia(dialog);
+ await act(() => settle({ ...boardUsageReport, checkedCount: 2, inUseCount: 1, onlyImages: true }));
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Also permanently delete your 2 items'), REPORT_WAIT);
+ expect(nameField()).toBeNull();
+});
+
+it('leaves Retry in place but disabled as the dialog closes', async () => {
+ vi.mocked(context.actions.getBoardMediaUsage).mockReset().mockRejectedValue(new Error('offline'));
+ const dialog = await openDeleteDialog();
+
+ await tickDeleteMedia(dialog);
+ await vi.waitFor(() => expect(dialogButton('Retry')?.disabled).toBe(false), REPORT_WAIT);
+
+ await act(() => userEvent.click(dialogButton('Cancel')!));
+ // Still on screen while it animates out, Retry can no longer run.
+ expect(dialogButton('Retry')?.disabled).toBe(true);
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ expect(context.actions.getBoardMediaUsage).toHaveBeenCalledOnce();
+});
+
+it('says none of the media goes when the caller added none of it, with no count to delete', async () => {
+ const { before, dialog, regionBefore, regionBeforePosition } = await answerWithCheckedCount(board as GalleryBoard, 0);
+
+ // Until the check answers, it shows as running.
+ expect(before).toContain('Checking where this media is used…');
+
+ expect(dialog.textContent).toContain('None of its media is yours; all of it moves to Uncategorized.');
+ expect(dialog.textContent).toContain('Also permanently delete your items');
+ expect(dialog.textContent).not.toMatch(/\b0 (items|images)\b/);
+ // Nothing is deleted, so there is no use to report: no "unused" verdict about the board's media. The live region
+ // that said it was checking reads out the outcome instead, the description, not shown a second time.
+ expect(dialog.textContent).not.toContain('Nothing uses this media.');
+ const liveRegion = dialog.querySelector<HTMLElement>('[aria-live="polite"]');
+ // The very region that showed the check running, visibly, then.
+ expect(liveRegion).toBe(regionBefore);
+ expect(regionBeforePosition).not.toBe('absolute');
+ expect(liveRegion?.getAttribute('aria-busy')).toBe('false');
+ expect(liveRegion?.textContent).toBe('None of its media is yours; all of it moves to Uncategorized.');
+ // Hidden as a whole, out of the layout: no gap where it stands.
+ expect(getComputedStyle(liveRegion!).position).toBe('absolute');
+ expect(liveRegion!.getBoundingClientRect().width).toBeLessThanOrEqual(1);
+ await act(() => userEvent.click(dialogButton('Delete board')!));
+ // Nothing of the caller's to delete: the board goes without asking for its media.
+ expect(context.actions.deleteBoard).toHaveBeenLastCalledWith('board-1', false);
+});
+
+it('keeps counting every item for an administrator overriding, who deletes them all', async () => {
+ const overridden = {
+ ...board,
+ access: {
+ actions: ['read', 'rename', 'archive', 'delete'],
+ adminOverride: true,
+ generalAccess: 'restricted',
+ role: null,
+ },
+ } as GalleryBoard;
+ // The board's counts went stale: one item left since they were read.
+ const { dialog } = await answerWithCheckedCount(overridden, 2, false);
+
+ expect(dialog.textContent).toContain('Its 2 items are deleted with it.');
+ expect(dialog.textContent).toContain('Also permanently delete its 2 items');
+ expect(dialog.textContent).not.toContain('your');
+ expect(dialogButton('Delete board and 2 items')).toBeDefined();
+});
+
/** The panel's part: the menu target clears when the menu closes. */
const ControlledMenu = ({ initialTarget }: { initialTarget: typeof target }) => {
const [menuTarget, setMenuTarget] = useState<typeof target | null>(initialTarget);
@@ -217,9 +549,11 @@ it.each(['cancel', 'delete'] as const)(
await act(async () => {
root?.render(
<ChakraProvider value={system}>
- <GalleryWidgetContext value={context}>
- <ControlledMenu initialTarget={target} />
- </GalleryWidgetContext>
+ <QueryClientProvider client={queryClient}>
+ <GalleryWidgetContext value={context}>
+ <ControlledMenu initialTarget={target} />
+ </GalleryWidgetContext>
+ </QueryClientProvider>
</ChakraProvider>
);
await Promise.resolve();
@@ -261,9 +595,11 @@ it('hands results back to the default destination from the auto-add board itself
await act(async () => {
root?.render(
<ChakraProvider value={system}>
- <GalleryWidgetContext value={targetContext}>
- <GalleryBoardMenu target={target} onClose={noop} />
- </GalleryWidgetContext>
+ <QueryClientProvider client={queryClient}>
+ <GalleryWidgetContext value={targetContext}>
+ <GalleryBoardMenu target={target} onClose={noop} />
+ </GalleryWidgetContext>
+ </QueryClientProvider>
</ChakraProvider>
);
await Promise.resolve();
@@ -294,9 +630,11 @@ const renderMenuFor = async (menuBoard: GalleryBoard, overrides: Partial<Gallery
await act(async () => {
root?.render(
<ChakraProvider value={system}>
- <GalleryWidgetContext value={value}>
- <GalleryBoardMenu target={{ board: menuBoard, x: 20, y: 20 }} onClose={noop} />
- </GalleryWidgetContext>
+ <QueryClientProvider client={queryClient}>
+ <GalleryWidgetContext value={value}>
+ <GalleryBoardMenu target={{ board: menuBoard, x: 20, y: 20 }} onClose={noop} />
+ </GalleryWidgetContext>
+ </QueryClientProvider>
</ChakraProvider>
);
await Promise.resolve();
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 32c5732bbf..2b6cb47d04 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -1,14 +1,22 @@
+import type {
+ GalleryMediaUsageCheck,
+ GalleryMediaUsageReport,
+ GalleryMediaUsageSettledCheck,
+} from '@features/gallery/core/mediaUsage';
import type { GalleryBoard, GalleryBoardAction, GalleryGeneralAccess } from '@features/gallery/core/types';
import { chakra, Checkbox, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';
import { canOnBoard, isOwnGalleryBoard } from '@features/gallery/core/boardAccess';
import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
import { formatGalleryMediaCounts } from '@features/gallery/core/mediaCounts';
+import { galleryBoardMediaUsageQueryOptions } from '@features/gallery/data/queries';
+import { captureAccountScope } from '@platform/state/accountLifecycle';
import { Button } from '@platform/ui/Button';
import { Dialog } from '@platform/ui/Dialog';
import { MenuContent } from '@platform/ui/Menu';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { ScrollableMenuContent } from '@platform/ui/ScrollableMenuContent';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
ArchiveIcon,
ChevronRightIcon,
@@ -25,6 +33,7 @@ import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { isManagedGalleryBoard, isMovableGalleryBoard } from './galleryBoardGroups';
+import { GalleryMediaUsagePanel } from './GalleryMediaUsagePanel';
import { getBoardCounts, getGalleryIntendedDestinationId } from './galleryStateView';
import { useGalleryWidget } from './GalleryWidgetContext';
@@ -238,6 +247,7 @@ export const GalleryBoardMenu = ({
</Dialog.Root>
<BoardDeleteDialog
board={deleteTarget}
+ getMediaUsage={actions.getBoardMediaUsage}
onCancel={handleCancelDelete}
onDelete={handleDelete}
onOpenChange={handleDeleteDialogOpenChange}
@@ -255,31 +265,91 @@ export const BOARD_DELETE_TYPED_CONFIRMATION_MIN_ITEMS = 50;
*/
const BoardDeleteDialog = ({
board,
+ getMediaUsage,
onCancel,
onDelete,
onOpenChange,
}: {
board: GalleryBoard | null;
+ /** Where the board's media is still used, checked once deleting it is ticked. */
+ getMediaUsage: (boardId: string, signal: AbortSignal) => Promise<GalleryMediaUsageReport>;
onCancel: () => void;
onDelete: (includeMedia: boolean) => void;
onOpenChange: (event: { open: boolean }) => void;
}) => {
const { t } = useTranslation();
+ const queryClient = useQueryClient();
// The board and the choices stay shown while the dialog animates out; the choices belong to one opening and start
// over with the next one, for the same board too. The dialog is not remounted, which would cut the exit animation.
const [shownBoard, setShownBoard] = useState(board);
const [openedBoardId, setOpenedBoardId] = useState(board?.id ?? null);
- const [choices, setChoices] = useState({ includeMedia: false, typedName: '' });
+ // `hasTyped`: the user has typed into the name field this opening, which then stays (see `needsTypedName`).
+ const [choices, setChoices] = useState({ hasTyped: false, includeMedia: false, typedName: '' });
+ // Each opening asks where the media is used afresh; ticking and unticking within one opening does not.
+ const [opening, setOpening] = useState(0);
if (board !== null && board !== shownBoard) {
setShownBoard(board);
}
if ((board?.id ?? null) !== openedBoardId) {
setOpenedBoardId(board?.id ?? null);
if (board !== null) {
- setChoices({ includeMedia: false, typedName: '' });
+ setChoices({ hasTyped: false, includeMedia: false, typedName: '' });
+ setOpening((current) => current + 1);
}
}
- const { includeMedia, typedName } = choices;
+ const { hasTyped, includeMedia, typedName } = choices;
+ const isOpen = board !== null;
+ const checksUsage = includeMedia && shownBoard !== null;
+ const boardId = shownBoard?.id ?? '';
+ const owner = captureAccountScope();
+ // An opening's check lives under its own key while the dialog is open. However the dialog closes (Cancel, Escape,
+ // Delete, or the board revoked or deleted elsewhere), the observer leaves that key, and Query stops a check still
+ // running there (its server call and project reads) and drops it.
+ const usageOptions = useMemo(
+ () => galleryBoardMediaUsageQueryOptions({ boardId, load: getMediaUsage, opening: isOpen ? opening : null, owner }),
+ [boardId, getMediaUsage, isOpen, opening, owner]
+ );
+ const { queryKey: usageQueryKey } = usageOptions;
+ const usageQuery = useQuery({ ...usageOptions, enabled: isOpen && checksUsage });
+ const { data: usageReport, isFetching: isCheckingUsage, refetch: refetchUsage, status: usageStatus } = usageQuery;
+ // The opening's last answer, kept while the box is unticked and as the dialog closes, so neither the report nor the
+ // counts it gives come and go.
+ const [keptAnswer, setKeptAnswer] = useState<{ check: GalleryMediaUsageSettledCheck; opening: number } | null>(null);
+ const answer: GalleryMediaUsageSettledCheck | null =
+ usageStatus === 'success' && usageReport
+ ? { report: usageReport, status: 'ready' }
+ : usageStatus === 'error'
+ ? { status: 'failed' }
+ : null;
+ const keptCheck = keptAnswer?.opening === opening ? keptAnswer.check : null;
+ if (
+ isOpen &&
+ answer &&
+ (answer.status === 'ready'
+ ? keptCheck?.status !== 'ready' || keptCheck.report !== answer.report
+ : keptCheck?.status !== 'failed')
+ ) {
+ setKeptAnswer({ check: answer, opening });
+ }
+ // Unticking stops a check still running too; it reverts, so ticking again asks again. An answer stays for the opening.
+ const cancelUsageCheck = useCallback(
+ () => void queryClient.cancelQueries({ exact: true, queryKey: usageQueryKey }),
+ [queryClient, usageQueryKey]
+ );
+ const usageCheck = useMemo<GalleryMediaUsageCheck | null>(() => {
+ if (!checksUsage) {
+ return null;
+ }
+
+ // A retry keeps the last answer on screen while it runs.
+ return isCheckingUsage || !keptCheck ? { previous: keptCheck ?? undefined, status: 'checking' } : keptCheck;
+ }, [checksUsage, isCheckingUsage, keptCheck]);
+ // A closing dialog's Retry stays in place, disabled: running it would ask on the closed key, which nothing stops.
+ const handleRetryUsage = useCallback(() => {
+ if (isOpen) {
+ void refetchUsage();
+ }
+ }, [isOpen, refetchUsage]);
const cancelRef = useRef<HTMLButtonElement | null>(null);
const mediaHintId = useId();
const nameInputId = useId();
@@ -291,24 +361,71 @@ const BoardDeleteDialog = ({
uploads: counts?.uploads ?? 0,
videos: counts?.videos ?? 0,
});
- const needsTypedName = includeMedia && itemCount >= BOARD_DELETE_TYPED_CONFIRMATION_MIN_ITEMS;
+ // Deleting the media takes what the check counted, once it has: on a shared board only the caller's own items, while
+ // the board's counts include everyone's; the rest moves to Uncategorized, as when the media is kept. An administrator
+ // overriding takes everything, so a lower count there is only a board count gone stale.
+ const keptReport = keptCheck?.status === 'ready' ? keptCheck.report : undefined;
+ const deletedCount = keptReport?.checkedCount ?? itemCount;
+ const deletesOwnMedia = deletedCount < itemCount && shownBoard?.access?.adminOverride !== true;
+ const deletesNoMedia = deletesOwnMedia && deletedCount === 0;
+ const deletedMedia =
+ deletedCount === itemCount || !keptReport
+ ? media
+ : t(keptReport.onlyImages ? 'widgets.gallery.imageCount' : 'widgets.gallery.deleteInUse.itemCount', {
+ count: deletedCount,
+ });
+ const includeMediaLabel = deletesNoMedia
+ ? t('widgets.gallery.deleteBoardIncludeOwnMediaNone')
+ : t(deletesOwnMedia ? 'widgets.gallery.deleteBoardIncludeOwnMedia' : 'widgets.gallery.deleteBoardIncludeMedia', {
+ count: deletedCount,
+ });
+ const withMediaDescription = deletesNoMedia
+ ? t('widgets.gallery.deleteBoardWithNoOwnMediaDescription')
+ : t(
+ deletesOwnMedia
+ ? 'widgets.gallery.deleteBoardWithOwnMediaDescription'
+ : 'widgets.gallery.deleteBoardWithMediaDescription',
+ { count: deletedCount, media: deletedMedia }
+ );
+ const deleteLabel =
+ !includeMedia || deletesNoMedia
+ ? t('widgets.gallery.deleteBoard')
+ : t(deletesOwnMedia ? 'widgets.gallery.deleteBoardAndOwnMedia' : 'widgets.gallery.deleteBoardAndMedia', {
+ count: deletedCount,
+ });
+ // The board's count until the check answers, then what deleting the media actually takes. Once the user has typed
+ // into the field this opening it stays, with its requirement: an answer arriving mid-typing never takes their text.
+ const needsTypedName = includeMedia && (hasTyped || deletedCount >= BOARD_DELETE_TYPED_CONFIRMATION_MIN_ITEMS);
const canDelete = !needsTypedName || typedName.trim() === boardName.trim();
const handleIncludeMediaChange = useCallback(
- (details: { checked: boolean | 'indeterminate' }) =>
- setChoices((current) => ({ ...current, includeMedia: details.checked === true })),
- []
+ (details: { checked: boolean | 'indeterminate' }) => {
+ if (details.checked !== true) {
+ cancelUsageCheck();
+ }
+ setChoices((current) => ({ ...current, includeMedia: details.checked === true }));
+ },
+ [cancelUsageCheck]
);
const handleTypedNameChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const typed = event.currentTarget.value;
- setChoices((current) => ({ ...current, typedName: typed }));
+ setChoices((current) => ({ ...current, hasTyped: current.hasTyped || typed !== '', typedName: typed }));
}, []);
const getInitialFocus = useCallback(() => cancelRef.current, []);
- const handleConfirm = useCallback(() => onDelete(includeMedia), [includeMedia, onDelete]);
+ // With none of the media the caller's, nothing is asked to be deleted: the board goes, and its notices say only that.
+ const deletesMedia = includeMedia && !deletesNoMedia;
+ const handleConfirm = useCallback(() => onDelete(deletesMedia), [deletesMedia, onDelete]);
return (
// Cancel takes focus, not the checkbox that would delete the media.
- <Dialog.Root initialFocusEl={getInitialFocus} open={board !== null} role="alertdialog" onOpenChange={onOpenChange}>
+ // Top-anchored: the usage report arrives after the dialog opens, and grows it downward instead of moving it.
+ <Dialog.Root
+ initialFocusEl={getInitialFocus}
+ open={board !== null}
+ placement="top"
+ role="alertdialog"
+ onOpenChange={onOpenChange}
+ >
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
@@ -318,11 +435,13 @@ const BoardDeleteDialog = ({
</Dialog.Header>
<Dialog.Body>
<Stack gap="3">
- <Text fontSize="md">
+ <Dialog.Description color="fg" fontSize="md" lineHeight="inherit">
{itemCount === 0
? t('widgets.gallery.deleteBoardEmptyDescription')
- : t('widgets.gallery.deleteBoardDescription', { count: itemCount, media })}
- </Text>
+ : includeMedia
+ ? withMediaDescription
+ : t('widgets.gallery.deleteBoardDescription', { count: itemCount, media })}
+ </Dialog.Description>
{itemCount > 0 ? (
<Stack gap="1">
<Checkbox.Root
@@ -335,15 +454,23 @@ const BoardDeleteDialog = ({
<Checkbox.Control>
<Checkbox.Indicator />
</Checkbox.Control>
- <Checkbox.Label fontSize="md">
- {t('widgets.gallery.deleteBoardIncludeMedia', { count: itemCount })}
- </Checkbox.Label>
+ <Checkbox.Label fontSize="md">{includeMediaLabel}</Checkbox.Label>
</Checkbox.Root>
<Text color="fg.muted" fontSize="sm" id={mediaHintId} ps="5">
{t('widgets.gallery.deleteBoardIncludeMediaHint')}
</Text>
</Stack>
) : null}
+ {itemCount > 0 && usageCheck ? (
+ <GalleryMediaUsagePanel
+ // Once the answer says none of the media is the caller's, nothing goes and there is no use to
+ // report: the panel only reads out the description that changed with it.
+ announcement={deletesNoMedia ? withMediaDescription : undefined}
+ check={usageCheck}
+ isRetryDisabled={!isOpen}
+ onRetry={handleRetryUsage}
+ />
+ ) : null}
{needsTypedName ? (
<Stack gap="1">
<chakra.label fontSize="md" htmlFor={nameInputId}>
@@ -365,9 +492,7 @@ const BoardDeleteDialog = ({
{t('common.cancel')}
</Button>
<Button colorPalette="red" disabled={!canDelete} onClick={handleConfirm}>
- {includeMedia
- ? t('widgets.gallery.deleteBoardAndMedia', { count: itemCount })
- : t('widgets.gallery.deleteBoard')}
+ {deleteLabel}
</Button>
</Dialog.Footer>
</Dialog.Content>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index b69c11ced5..d5a7744a1b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -424,21 +424,28 @@ type CanonicalContextTarget = {
allStarred?: boolean;
itemRefs?: GalleryItemRef[];
items: GalleryItem[];
+ returnFocus?: () => HTMLElement | null;
x: number;
y: number;
} | null;
const ContextMenuProbe = ({ target }: { target: CanonicalContextTarget }) => (
- <output data-testid="context-target">
- {JSON.stringify(
- target
- ? {
- itemRefs: target.itemRefs ?? null,
- items: target.items.map(({ kind, name }) => ({ kind, name })),
- ...(target.allStarred === undefined ? {} : { allStarred: target.allStarred }),
- }
- : null
- )}
- </output>
+ <>
+ <output data-testid="context-target">
+ {JSON.stringify(
+ target
+ ? {
+ itemRefs: target.itemRefs ?? null,
+ items: target.items.map(({ kind, name }) => ({ kind, name })),
+ ...(target.allStarred === undefined ? {} : { allStarred: target.allStarred }),
+ }
+ : null
+ )}
+ </output>
+ {/* Stands in for a dialog the menu opened, closing: focus goes where the target says. */}
+ <button data-testid="context-return-focus" type="button" onClick={() => target?.returnFocus?.()?.focus()}>
+ Close dialog
+ </button>
+ </>
);
const NoopProvider = ({ children }: { children: ReactNode }) => children;
@@ -1411,6 +1418,34 @@ describe('GalleryImageGrid mixed item cells', () => {
);
});
+ it('returns focus from a dialog its context menu opens to the right-clicked thumbnail, or the grid once it is gone', async () => {
+ const first = createItem('image', 'first.png');
+ const second = createItem('image', 'second.png');
+ await renderGallery(createGallery({ items: [first, second], selectedItemKey: null, selectedItemKeys: [] }));
+ const secondButton = getButton('Select second.png for preview');
+
+ await interact(() =>
+ secondButton.dispatchEvent(
+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 23, clientY: 41 })
+ )
+ );
+
+ const closeDialog = host!.querySelector<HTMLButtonElement>('[data-testid="context-return-focus"]')!;
+
+ await interact(() => closeDialog.click());
+ expect(document.activeElement).toBe(secondButton);
+
+ // Resolved as the dialog closes: a deletion that removed the thumbnail leaves focus in the grid, not on the page.
+ secondButton.remove();
+ await interact(() => closeDialog.click());
+ // The removed thumbnail held the tab stop, so focus lands on the grid's scroll viewport, which keeps it in the grid.
+ const gridViewport = getButton('Select first.png for preview').closest<HTMLElement>(
+ '[data-scope="scroll-area"][data-part="viewport"]'
+ );
+ expect(gridViewport).not.toBeNull();
+ expect(document.activeElement).toBe(gridViewport);
+ });
+
it('retains an unloaded video ref when opening the context menu inside a mixed selection', async () => {
const image = createItem('image', 'loaded.png');
await renderGallery(
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 840cd042c6..f22ce4d625 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -465,6 +465,21 @@ export const GalleryImageGrid = ({
(item: GalleryItem) => sparseSelectionPages.get(toGalleryItemKey(item)),
[sparseSelectionPages]
);
+ // The right-clicked thumbnail, or, once a deletion removed it, the grid's tab stop.
+ const getItemReturnFocus = useCallback(
+ (item: GalleryItem) => () => {
+ const viewport = viewportRef.current;
+ const selector = `button[data-gallery-item-key="${CSS.escape(toGalleryItemKey(item))}"]`;
+
+ return (
+ viewport?.querySelector<HTMLElement>(selector) ??
+ viewport?.querySelector<HTMLElement>(GALLERY_TAB_STOP_SELECTOR) ??
+ viewport ??
+ null
+ );
+ },
+ []
+ );
const {
actionSelectionRefs,
@@ -479,7 +494,7 @@ export const GalleryImageGrid = ({
shouldStarSelection,
syncRangeInteractionContext,
toggleItem,
- } = useGalleryGridSelection({ getSelectionPage });
+ } = useGalleryGridSelection({ getItemReturnFocus, getSelectionPage });
const columnCount = getGalleryColumnCount({ imageDensityPercent, widthPx: viewportWidth });
const sparseRecentItems = usesSparseListing ? sparseListing.recentItems : EMPTY_GALLERY_ITEMS;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx
index 7713a4f48b..bad8c95325 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx
@@ -48,6 +48,7 @@ const adapter: GalleryUiAdapter = {
ImageContextMenu: () => null,
antialiasProgressImages: false,
exportProject: noop,
+ getBoardMediaUsage: vi.fn(),
gallery: {
clearSelection: noop,
reconcileDeletedBoardOutcome: noop,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
index d28bd732e3..72299d254d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
@@ -148,6 +148,7 @@ const Harness = ({
ImageContextMenu: () => null,
antialiasProgressImages: false,
exportProject: noop,
+ getBoardMediaUsage: vi.fn(),
followProgressSession: noop,
followedProgressSessionId: null,
gallery: {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsagePanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsagePanel.tsx
new file mode 100644
index 0000000000..0104618101
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsagePanel.tsx
@@ -0,0 +1,92 @@
+import type { GalleryMediaUsageCheck } from '@features/gallery/core/mediaUsage';
+
+import { HStack, Spinner, Stack, Text } from '@chakra-ui/react';
+import { lazy, Suspense, useCallback, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+// The report renders only once a check settles, so its code loads then (the check itself has usually loaded it).
+const GalleryMediaUsageOutcome = lazy(() =>
+ import('./GalleryMediaUsageSection').then((module) => ({ default: module.GalleryMediaUsageOutcome }))
+);
+
+/**
+ * Where the media a deletion takes is still used, for the item and board deletion dialogs alike. Kept small and eager
+ * on purpose: the live region exists as the dialog opens, so the report is announced when it arrives, and the checking
+ * state shows at once, before any of the report's code has loaded.
+ */
+export const GalleryMediaUsagePanel = ({
+ announcement,
+ check,
+ isRetryDisabled = false,
+ onRetry,
+}: {
+ /**
+ * Read out in place of a settled answer the dialog does not show, because what it says is already on screen
+ * elsewhere: the live region still announces how the check came out, without showing the text twice.
+ */
+ announcement?: string;
+ check: GalleryMediaUsageCheck;
+ /** Keeps Retry in place, disabled: the deletion is already under way, or the dialog closing. */
+ isRetryDisabled?: boolean;
+ /** Runs the check again after it failed or could not reach the server. */
+ onRetry?: () => void;
+}) => {
+ const panelRef = useRef<HTMLDivElement | null>(null);
+ // Retry is replaced by the checking state, and its control may not come back. Focus moves first to the panel itself,
+ // which stays mounted through every state: it never falls out of the dialog, and the live region reads the new state.
+ const handleRetry = useCallback(() => {
+ panelRef.current?.focus();
+ onRetry?.();
+ }, [onRetry]);
+
+ const settled = check.status === 'checking' ? check.previous : check;
+ // The same live region throughout, hidden as a whole once it only reads out `announcement`: out of the layout, so it
+ // takes no spacing slot beside the text it repeats.
+ const isAnnouncementOnly = settled !== undefined && announcement !== undefined;
+
+ return (
+ <Stack
+ ref={panelRef}
+ aria-busy={check.status === 'checking'}
+ aria-live="polite"
+ focusVisibleRing="outside"
+ gap="1"
+ // Room between the ring and the text, given back by the margin so focus moves nothing.
+ m="-1.5"
+ p="1.5"
+ rounded="l2"
+ srOnly={isAnnouncementOnly}
+ // Focusable only by script, as Retry's stand-in: no tab stop of its own.
+ tabIndex={-1}
+ >
+ {isAnnouncementOnly ? (
+ announcement
+ ) : settled ? (
+ // A settled answer never shows as "checking" while its code loads: nothing, for a frame, then the answer. A
+ // retry keeps it on screen, the checking state standing where its warning and Retry were.
+ <Suspense fallback={null}>
+ <GalleryMediaUsageOutcome
+ check={settled}
+ isRechecking={check.status === 'checking'}
+ isRetryDisabled={isRetryDisabled}
+ onRetry={onRetry ? handleRetry : undefined}
+ />
+ </Suspense>
+ ) : (
+ <GalleryMediaUsageChecking />
+ )}
+ </Stack>
+ );
+};
+
+/** The check running: shared by the first check and a retry, which shows it in place of the warning it answers. */
+export const GalleryMediaUsageChecking = () => {
+ const { t } = useTranslation();
+
+ return (
+ <HStack color="fg.muted" gap="2">
+ <Spinner aria-hidden="true" boxSize="3" />
+ <Text fontSize="md">{t('widgets.gallery.deleteInUse.checking')}</Text>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx
new file mode 100644
index 0000000000..7c21dc185d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx
@@ -0,0 +1,277 @@
+import type {
+ GalleryMediaUsageGroup,
+ GalleryMediaUsageReport,
+ GalleryMediaUsageSettledCheck,
+ GalleryMediaUsageSurfaceRow,
+} from '@features/gallery/core/mediaUsage';
+import type { TFunction } from 'i18next';
+
+import { Flex, HStack, Icon, List, Stack, Text } from '@chakra-ui/react';
+import { Button } from '@platform/ui/Button';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { ClippedTooltip } from '@platform/ui/Tooltip';
+import { TriangleAlertIcon } from 'lucide-react';
+import { useCallback, useId, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GalleryMediaUsageChecking } from './GalleryMediaUsagePanel';
+
+const KEY = 'widgets.gallery.deleteInUse';
+
+/**
+ * The summary line. It counts what the check counted: the requested items, or for a board the items deleting it
+ * takes, which can be fewer than the board shows when it holds media of other accounts. One checked item needs no
+ * count.
+ */
+const getSummary = (t: TFunction, report: GalleryMediaUsageReport): string => {
+ const { checkedCount: total, inUseCount: count, onlyImages, scope } = report;
+
+ if (total === 1) {
+ return t(`${KEY}.summaryOne`);
+ }
+
+ const media = t(onlyImages ? 'widgets.gallery.imageCount' : `${KEY}.itemCount`, { count: total });
+ const key = scope === 'board' ? `${KEY}.summaryBoard` : `${KEY}.summary`;
+
+ return count === total ? t(`${key}All`, { media }) : t(key, { count, media });
+};
+
+const named = (t: TFunction, key: string, unnamedKey: string, name: string | null): string =>
+ name === null ? t(unnamedKey) : t(key, { name });
+
+const getGroupLabel = (t: TFunction, group: GalleryMediaUsageGroup): string => {
+ switch (group.kind) {
+ case 'openProject':
+ return t(`${KEY}.group.openProject`);
+ case 'project':
+ case 'projectUnchecked':
+ return named(t, `${KEY}.group.project`, `${KEY}.group.projectUnnamed`, group.name);
+ case 'quarantinedProject':
+ return named(t, `${KEY}.group.quarantinedProject`, `${KEY}.group.quarantinedProjectUnnamed`, group.name);
+ case 'workflow':
+ return named(t, `${KEY}.group.workflow`, `${KEY}.group.workflowUnnamed`, group.name);
+ case 'legacyEditor':
+ return t(`${KEY}.group.legacyEditor`);
+ case 'otherDocument':
+ return named(t, `${KEY}.group.otherDocument`, `${KEY}.group.otherDocumentUnnamed`, group.name);
+ case 'moreDocuments':
+ return t(`${KEY}.group.moreDocuments`, { count: group.documentCount });
+ case 'queue':
+ return t(`${KEY}.group.queue`, { count: group.jobCount });
+ case 'otherAccounts':
+ return t(`${KEY}.group.otherAccounts`);
+ }
+};
+
+/**
+ * One line: the source's name, clamped to two lines so a long one cannot push its count out of view, and how many it
+ * uses. A clamped name shows in full in a tooltip; assistive technology reads the whole text either way.
+ */
+const UsageLine = ({ count, label, muted = false }: { count: string | null; label: string; muted?: boolean }) => {
+ const labelRef = useRef<HTMLParagraphElement | null>(null);
+ const isClipped = useCallback(() => {
+ const element = labelRef.current;
+
+ return element !== null && element.scrollHeight > element.clientHeight + 1;
+ }, []);
+
+ return (
+ <Flex align="baseline" fontSize="md" gap="2" minW="0">
+ <ClippedTooltip content={label} isClipped={isClipped}>
+ <Text
+ ref={labelRef}
+ color={muted ? 'fg.muted' : undefined}
+ flex="1"
+ lineClamp={2}
+ minW="0"
+ overflowWrap="anywhere"
+ >
+ {label}
+ </Text>
+ </ClippedTooltip>
+ {count === null ? null : (
+ <Text color="fg.muted" flexShrink={0} fontVariantNumeric="tabular-nums" whiteSpace="nowrap">
+ {count}
+ </Text>
+ )}
+ </Flex>
+ );
+};
+
+/** Rows leave out their counts when one item is checked: every row would say "1 item". */
+const SurfaceRows = ({
+ showCounts,
+ surfaces,
+}: {
+ showCounts: boolean;
+ surfaces: readonly GalleryMediaUsageSurfaceRow[];
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <List.Root gap="0.5" listStyleType="none" ps="3">
+ {surfaces.map((row, index) => (
+ // Built once per report and never reordered; labels such as workflow names can repeat.
+ <List.Item key={index}>
+ <UsageLine
+ count={showCounts ? t(`${KEY}.itemCount`, { count: row.count }) : null}
+ label={t(`${KEY}.surface.${row.surface}`, { name: row.label })}
+ muted
+ />
+ </List.Item>
+ ))}
+ </List.Root>
+ );
+};
+
+const UsageGroup = ({ group, showCounts }: { group: GalleryMediaUsageGroup; showCounts: boolean }) => {
+ const { t } = useTranslation();
+ const count = showCounts && group.kind !== 'moreDocuments' ? t(`${KEY}.itemCount`, { count: group.count }) : null;
+
+ return (
+ <List.Item>
+ <UsageLine count={count} label={getGroupLabel(t, group)} />
+ {group.kind === 'openProject' || group.kind === 'project' ? (
+ <SurfaceRows showCounts={showCounts} surfaces={group.surfaces} />
+ ) : null}
+ {(group.kind === 'openProject' || group.kind === 'project') && group.savedCopyUnchecked ? (
+ <Text color="fg.muted" fontSize="sm" ps="3">
+ {t(`${KEY}.savedCopyUncheckedHint`)}
+ </Text>
+ ) : null}
+ {group.kind === 'projectUnchecked' ? (
+ <Text color="fg.muted" fontSize="sm" ps="3">
+ {t(`${KEY}.projectUncheckedHint`)}
+ </Text>
+ ) : null}
+ </List.Item>
+ );
+};
+
+/** A check that did not (fully) run: a warning, distinct from the muted notes, with a way to run it again. */
+const UsageWarning = ({
+ isRetryDisabled = false,
+ message,
+ onRetry,
+}: {
+ isRetryDisabled?: boolean;
+ message: string;
+ onRetry?: () => void;
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <HStack align="start" color="fg.warning" fontSize="sm" gap="2">
+ <Icon aria-hidden="true" as={TriangleAlertIcon} boxSize="3.5" flexShrink={0} mt="0.5" />
+ <Text flex="1">{message}</Text>
+ {onRetry ? (
+ <Button disabled={isRetryDisabled} flexShrink={0} size="xs" variant="outline" onClick={onRetry}>
+ {t('common.retry')}
+ </Button>
+ ) : null}
+ </HStack>
+ );
+};
+
+const UsageReport = ({
+ isRechecking,
+ isRetryDisabled,
+ onRetry,
+ report,
+}: {
+ isRechecking: boolean;
+ isRetryDisabled: boolean;
+ onRetry?: () => void;
+ report: GalleryMediaUsageReport;
+}) => {
+ const { t } = useTranslation();
+ const headingId = useId();
+ // While a retry runs, the check stands where the warning it answers was; the rest of the report stays.
+ const unchecked = isRechecking ? (
+ <GalleryMediaUsageChecking />
+ ) : report.serverCheck === 'complete' ? null : (
+ <UsageWarning
+ isRetryDisabled={isRetryDisabled}
+ message={t(
+ report.serverCheck === 'tooManyItems'
+ ? `${KEY}.tooManyItems`
+ : report.groups.length === 0
+ ? `${KEY}.uncheckedNone`
+ : `${KEY}.unchecked`,
+ { count: report.checkedCount }
+ )}
+ // Retrying cannot shrink a selection past the limit.
+ onRetry={report.serverCheck === 'unavailable' ? onRetry : undefined}
+ />
+ );
+
+ if (report.groups.length === 0) {
+ return (
+ unchecked ?? (
+ <Text color="fg.muted" fontSize="sm">
+ {t(`${KEY}.none`)}
+ </Text>
+ )
+ );
+ }
+
+ const showCounts = report.checkedCount > 1;
+ const hasQueue = report.groups.some((group) => group.kind === 'queue');
+
+ return (
+ <Stack aria-labelledby={headingId} as="section" gap="1.5" role="group">
+ <Text fontSize="md" fontWeight="semibold" id={headingId}>
+ {getSummary(t, report)}
+ </Text>
+ <Scrollable label={t(`${KEY}.listLabel`)} maxH="14rem">
+ <List.Root gap="1" listStyleType="none">
+ {report.groups.map((group, index) => (
+ <UsageGroup key={index} group={group} showCounts={showCounts} />
+ ))}
+ </List.Root>
+ </Scrollable>
+ <Text color="fg.muted" fontSize="sm">
+ {t(`${KEY}.warning`, { count: report.inUseCount })}
+ {hasQueue ? ` ${t(`${KEY}.queueWarning`, { count: report.inUseCount })}` : ''}
+ </Text>
+ {unchecked}
+ </Stack>
+ );
+};
+
+/**
+ * The settled half of the usage check, loaded once a dialog shows one: the report, or a warning that the check failed.
+ * `GalleryMediaUsagePanel` owns the live region and the checking state around it.
+ */
+export const GalleryMediaUsageOutcome = ({
+ check,
+ isRechecking = false,
+ isRetryDisabled = false,
+ onRetry,
+}: {
+ check: GalleryMediaUsageSettledCheck;
+ /** A retry runs: the answer stays, the checking state in place of its warning. */
+ isRechecking?: boolean;
+ /** Retry stays in place but cannot run, such as while the deletion it would inform is already under way. */
+ isRetryDisabled?: boolean;
+ onRetry?: () => void;
+}) => {
+ const { t } = useTranslation();
+
+ if (check.status === 'ready') {
+ return (
+ <UsageReport
+ isRechecking={isRechecking}
+ isRetryDisabled={isRetryDisabled}
+ report={check.report}
+ onRetry={onRetry}
+ />
+ );
+ }
+
+ return isRechecking ? (
+ <GalleryMediaUsageChecking />
+ ) : (
+ <UsageWarning isRetryDisabled={isRetryDisabled} message={t(`${KEY}.failed`)} onRetry={onRetry} />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
index 15aaf43c91..a8c7ee4406 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
@@ -1,4 +1,5 @@
import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsageReport } from '@features/gallery/core/mediaUsage';
import type { GallerySettings } from '@features/gallery/core/settings';
import type {
GalleryBoard,
@@ -56,6 +57,11 @@ export interface GalleryItemContextMenuTarget {
items: GalleryItem[];
/** The board the listing the targets were selected in reads, where targets `items` omits sit. */
listingBoardId?: string;
+ /**
+ * Where focus goes when a dialog the menu opens (a deletion's confirmation) closes, resolved then: the menu, which
+ * had focus as the dialog opened, is gone by then.
+ */
+ returnFocus?: () => HTMLElement | null;
x: number;
y: number;
}
@@ -128,6 +134,11 @@ export interface GalleryUiAdapter {
gallery: GalleryCommandsPort;
galleryValues: Record<string, unknown>;
generateValues: Record<string, unknown>;
+ /**
+ * Where a board's media is still used, for deleting the board with its media: the host narrows the server's check
+ * with its projects' own scans. Rejects when the check cannot run at all.
+ */
+ getBoardMediaUsage(boardId: string, signal: AbortSignal): Promise<GalleryMediaUsageReport>;
/** A project's gallery values as they are now, or null once it is closed; absent for hosts without projects. */
getProjectGalleryValues?(projectId: string): Record<string, unknown> | null;
/** The user picked a board in the board list to look at it: the host may explain where new results still go. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
index ca6cd3ae8e..a155042b89 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
@@ -1,4 +1,5 @@
import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsageReport } from '@features/gallery/core/mediaUsage';
import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';
import type { GallerySearchScope, GallerySettings } from '@features/gallery/core/settings';
import type { GalleryGeneralAccess, GalleryView } from '@features/gallery/core/types';
@@ -28,6 +29,8 @@ export interface GalleryActions {
createBoard: (boardName: string, projectId: string | null) => Promise<boolean>;
deleteBoard: (boardId: string, includeImages: boolean) => Promise<void>;
downloadBoard: (boardId: string) => Promise<void>;
+ /** Where the board's media is still used; see `GalleryUiAdapter.getBoardMediaUsage`. */
+ getBoardMediaUsage: (boardId: string, signal: AbortSignal) => Promise<GalleryMediaUsageReport>;
/** Export the project that owns this board as a complete `.invk` archive. */
exportProject: (projectId: string, projectName: string) => void;
loadMore: () => void;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx
index 70848140d7..8962cf6e37 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx
@@ -103,6 +103,7 @@ const adapter: GalleryUiAdapter = {
ImageContextMenu: () => null,
antialiasProgressImages: false,
exportProject: noop,
+ getBoardMediaUsage: vi.fn(),
followedProgressSessionId: null,
followProgressSession: noop,
gallery: {
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.tsx
index 98e697aef5..07805da480 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
@@ -183,6 +183,7 @@ const adapter: GalleryUiAdapter = {
ImageContextMenu: NoopContextMenu,
antialiasProgressImages: false,
exportProject: vi.fn(),
+ getBoardMediaUsage: vi.fn(),
gallery: {
clearSelection: noop,
reconcileDeletedBoardOutcome,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 7ca221b524..372b9efbfb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -52,6 +52,7 @@ export const useGalleryActions = ({
exportProject,
gallery,
galleryValues,
+ getBoardMediaUsage,
getProjectGalleryValues,
notifications,
projectId,
@@ -314,6 +315,7 @@ export const useGalleryActions = ({
}
},
exportProject,
+ getBoardMediaUsage,
loadMore,
moveBoard: async (boardId, destinationProjectId, destinationLabel) => {
const owner = captureAccountScope();
@@ -445,6 +447,7 @@ export const useGalleryActions = ({
ensureProjectOnServer,
exportProject,
gallery,
+ getBoardMediaUsage,
getCurrentGalleryLocation,
getProjectGalleryValues,
loadMore,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts
index 210aa351a2..ced48a10a6 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts
@@ -40,8 +40,11 @@ const getGalleryItemRange = (
* the captured context.
*/
export const useGalleryGridSelection = ({
+ getItemReturnFocus,
getSelectionPage,
}: {
+ /** Where focus returns from a dialog the item's context menu opens; see `GalleryItemContextMenuTarget`. */
+ getItemReturnFocus?: (item: GalleryItem) => () => HTMLElement | null;
/** The sparse page stamp for a loaded listing item; selections without one stamp the grid's page. */
getSelectionPage?: (item: GalleryItem) => number | undefined;
} = {}) => {
@@ -297,6 +300,7 @@ export const useGalleryGridSelection = ({
const handleThumbnailContextMenu = useCallback(
(item: GalleryItem, x: number, y: number) => {
const itemKey = toGalleryItemKey(item);
+ const returnFocus = getItemReturnFocus?.(item);
if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {
const selectionItems = [
@@ -312,15 +316,16 @@ export const useGalleryGridSelection = ({
itemRefs: selectedItemRefs,
items: selectionItems,
listingBoardId: gallery.listingBoardId,
+ returnFocus,
x,
y,
});
return;
}
- setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y });
+ setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], returnFocus, x, y });
},
- [gallery.listingBoardId, loadedItems, selectedItemKeys, selectedItemRefs, shouldStarSelection]
+ [getItemReturnFocus, gallery.listingBoardId, loadedItems, selectedItemKeys, selectedItemRefs, shouldStarSelection]
);
const getDragItems = useCallback(
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
index 0a15192f37..799f324bb1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
@@ -76,6 +76,7 @@ const adapter: GalleryUiAdapter = {
ImageContextMenu: () => null,
antialiasProgressImages: false,
exportProject: vi.fn(),
+ getBoardMediaUsage: vi.fn(),
gallery: {
clearSelection: noop,
reconcileDeletedBoardOutcome: noop,
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
index b83a709724..008593e393 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
@@ -19,6 +19,7 @@ export const ConfirmDialog = ({
onClose,
onConfirm,
onExitComplete,
+ placement = 'center',
title,
}: {
body: ReactNode;
@@ -43,6 +44,11 @@ export const ConfirmDialog = ({
onConfirm: () => Promise<void> | void;
/** After the close animation; hosts that retain the dialog's subject release it here. */
onExitComplete?: () => void;
+ /**
+ * `top` anchors the dialog's top edge, for a body that grows after it opens (an answer still loading): a centered
+ * dialog would move up by half of every change.
+ */
+ placement?: 'center' | 'top';
title: string;
}) => {
const { t } = useTranslation();
@@ -125,6 +131,7 @@ export const ConfirmDialog = ({
finalFocusEl={finalFocusEl}
initialFocusEl={initialFocusEl ?? (text.isDestructive ? getInitialFocus : undefined)}
open={isOpen}
+ placement={placement}
role="alertdialog"
size="sm"
onExitComplete={handleExitComplete}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
index 9ec994ae59..0a9191d153 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
@@ -317,9 +317,30 @@ describe('ImageContextMenu deletion delegation', () => {
await interact(() => getMenuItem('widgets.gallery.itemMenu.deleteImage').click());
- expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'single.png' }]);
+ expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'single.png' }], {
+ returnFocus: undefined,
+ });
expect(getOpenAlertDialog()).toBeNull();
});
+
+ it('hands the deletion the place its host says focus returns to, since the menu is gone by then', async () => {
+ const deleteItems = vi.fn(() => Promise.resolve());
+ const target = item('image', 'right-clicked.png');
+ const returnFocus = () => null;
+ await renderItemMenu(createActions(deleteItems), {
+ itemRefs: [{ kind: 'image', name: target.name }],
+ items: [target],
+ returnFocus,
+ x: 20,
+ y: 20,
+ });
+
+ await interact(() => getMenuItem('widgets.gallery.itemMenu.deleteImage').click());
+
+ expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'right-clicked.png' }], {
+ returnFocus,
+ });
+ });
});
describe('ImageContextMenu find in gallery', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 90eaeb7172..ff993b267e 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -143,7 +143,11 @@ export const ImageContextMenu = ({
() => (itemTarget && isCompleteImageTarget ? { images, x: itemTarget.x, y: itemTarget.y } : null),
[images, isCompleteImageTarget, itemTarget]
);
- const requestDeletion = useCallback((itemRefs: GalleryItemRef[]) => void actions.deleteItems(itemRefs), [actions]);
+ const returnFocus = itemTarget?.returnFocus;
+ const requestDeletion = useCallback(
+ (itemRefs: GalleryItemRef[]) => void actions.deleteItems(itemRefs, { returnFocus }),
+ [actions, returnFocus]
+ );
const requestImageDeletion = useCallback(
(imageNames: string[]) => requestDeletion(imageNames.map((name) => ({ kind: 'image', name }))),
[requestDeletion]
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.test.ts
index f7e2f94902..4e36091c09 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.test.ts
@@ -1,9 +1,10 @@
import type { GalleryItemRef } from '@features/gallery/contracts';
import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { describe, expect, it } from 'vitest';
-import { collectMediaUsage } from './mediaUsage';
+import { collectMediaUsage, mergeMediaUsage } from './mediaUsage';
const widget = (typeId: string, values: Record<string, unknown>) => ({
createdAt: '2026-01-01T00:00:00.000Z',
@@ -23,12 +24,22 @@ const rasterLayer = (id: string, imageName: string) =>
}) as unknown as CanvasNodeContract;
const project = ({
+ fields = {},
+ snapshots = [],
stacks = {},
+ staged = [],
widgets = {},
+ workflow = {},
workflowNodes = [],
}: {
+ /** Other project fields, at the root. */
+ fields?: Record<string, unknown>;
+ snapshots?: unknown[];
stacks?: Partial<Record<'raster' | 'control' | 'regional_guidance' | 'inpaint_mask', CanvasNodeContract[]>>;
+ staged?: unknown[];
widgets?: Record<string, Record<string, unknown>>;
+ /** Other fields of the workflow entry, beside its document. */
+ workflow?: Record<string, unknown>;
workflowNodes?: unknown[];
} = {}) =>
({
@@ -36,16 +47,17 @@ const project = ({
document: {
stacks: { control: [], inpaint_mask: [], raster: [], regional_guidance: [], ...stacks },
},
- // Snapshots are history: a deleted name here must not count as in use.
- snapshots: [{ document: { stacks: { raster: [rasterLayer('old', 'snapshot-only.png')] } } }],
+ snapshots,
+ stagingArea: { pendingImages: staged },
},
widgetInstances: Object.fromEntries(
Object.entries(widgets).map(([typeId, values]) => [typeId, widget(typeId, values)])
),
workflows: {
activeWorkflowId: 'wf',
- entries: [{ document: { edges: [], name: 'Upscale pass', nodes: workflowNodes } }],
+ entries: [{ document: { edges: [], name: 'Upscale pass', nodes: workflowNodes }, ...workflow }],
},
+ ...fields,
}) as unknown as Parameters<typeof collectMediaUsage>[0];
const image = (name: string): GalleryItemRef => ({ kind: 'image', name });
@@ -93,14 +105,14 @@ describe('collectMediaUsage', () => {
];
expect(collectMediaUsage(doc, selected)).toEqual([
- { names: ['ref.png'], surface: 'generateReferenceImages' },
- { names: ['raster.png'], surface: 'canvasRaster' },
- { names: ['control.png'], surface: 'canvasControl' },
- { names: ['regional-ref.png'], surface: 'canvasRegionalGuidance' },
- { names: ['mask.png'], surface: 'canvasInpaintMask' },
- { names: ['upscale.png'], surface: 'upscale' },
- { names: ['frame.png'], surface: 'video' },
- { label: 'Upscale pass', names: ['wf.png'], surface: 'workflow' },
+ { refs: [image('ref.png')], surface: 'generateReferenceImages' },
+ { refs: [image('raster.png')], surface: 'canvasRaster' },
+ { refs: [image('control.png')], surface: 'canvasControl' },
+ { refs: [image('regional-ref.png')], surface: 'canvasRegionalGuidance' },
+ { refs: [image('mask.png')], surface: 'canvasInpaintMask' },
+ { refs: [image('upscale.png')], surface: 'upscale' },
+ { refs: [image('frame.png')], surface: 'video' },
+ { label: 'Upscale pass', refs: [image('wf.png')], surface: 'workflow' },
]);
});
@@ -116,14 +128,192 @@ describe('collectMediaUsage', () => {
});
expect(collectMediaUsage(doc, [video('clip.mp4'), video('same-name'), image('same-name')])).toEqual([
- { names: ['clip.mp4', 'same-name'], surface: 'video' },
- { label: 'Upscale pass', names: ['same-name'], surface: 'workflow' },
+ { refs: [video('clip.mp4'), video('same-name')], surface: 'video' },
+ { label: 'Upscale pass', refs: [image('same-name')], surface: 'workflow' },
]);
});
- it('ignores canvas snapshots and media the gallery merely selects', () => {
- const doc = project({ widgets: { gallery: { selectedImageName: 'snapshot-only.png' } } });
+ it('counts staged results and each canvas snapshot, the live document and its staged results alike', () => {
+ const doc = project({
+ snapshots: [
+ { document: { stacks: { raster: [rasterLayer('old', 'cleared.png')] } }, name: 'Before clear' },
+ {
+ document: { stacks: { raster: [] } },
+ name: 'Discarded results',
+ stagedImages: [{ imageName: 'discarded.png', placement: {} }],
+ },
+ ],
+ staged: [{ imageName: 'staged.png', placement: {} }],
+ });
+
+ expect(collectMediaUsage(doc, [image('cleared.png'), image('discarded.png'), image('staged.png')])).toEqual([
+ { refs: [image('staged.png')], surface: 'canvasStaging' },
+ { label: 'Before clear', refs: [image('cleared.png')], surface: 'canvasSnapshot' },
+ { label: 'Discarded results', refs: [image('discarded.png')], surface: 'canvasSnapshot' },
+ ]);
+ });
+
+ it('ignores what the gallery merely shows: its selection, recents and compare image', () => {
+ const doc = project({
+ widgets: {
+ gallery: {
+ compareImageName: 'shown.png',
+ recentImages: [{ imageName: 'shown.png' }],
+ selectedImageName: 'shown.png',
+ },
+ },
+ });
+
+ expect(collectMediaUsage(doc, [image('shown.png')])).toEqual([]);
+ });
+
+ it('reports a name anywhere else in the project as used elsewhere, once, so a field with no surface still warns', () => {
+ const doc = project({
+ fields: { futureField: { nested: [{ image_name: 'future.png' }] } },
+ widgets: {
+ // A widget the panel has no surface for, and a Generate value beside its reference images.
+ 'image-notes': { pinned: { imageName: 'pinned.png' } },
+ generate: {
+ referenceImages: [{ config: { image: { image_name: 'ref.png' } } }],
+ recalled: { image_name: 'ref.png' },
+ },
+ },
+ workflow: { lastRun: { imageName: 'last-run.png' } },
+ workflowNodes: [],
+ });
+
+ expect(
+ collectMediaUsage(doc, [image('pinned.png'), image('ref.png'), image('future.png'), image('last-run.png')])
+ ).toEqual([
+ { refs: [image('ref.png')], surface: 'generateReferenceImages' },
+ { refs: [image('pinned.png'), image('future.png')], surface: 'otherProjectState' },
+ ]);
+
+ // An image sharing a video's name is its own item: the video surface does not account for it.
+ const sameName = project({
+ widgets: {
+ 'image-notes': { pinned: { imageName: 'same-name' } },
+ video: { sourceVideo: { video_name: 'same-name' } },
+ },
+ });
- expect(collectMediaUsage(doc, [image('snapshot-only.png')])).toEqual([]);
+ expect(collectMediaUsage(sameName, [video('same-name'), image('same-name')])).toEqual([
+ { refs: [video('same-name')], surface: 'video' },
+ { refs: [image('same-name')], surface: 'otherProjectState' },
+ ]);
+ });
+
+ it('still reports a canvas stack kind or snapshot field that no surface reads', () => {
+ const doc = project({
+ snapshots: [{ document: { stacks: {} }, name: 'Before clear', preview: { imageName: 'snapshot-preview.png' } }],
+ stacks: { future_stack: [rasterLayer('f', 'future-stack.png')] } as Record<string, CanvasNodeContract[]>,
+ });
+
+ expect(collectMediaUsage(doc, [image('future-stack.png'), image('snapshot-preview.png')])).toEqual([
+ { refs: [image('future-stack.png'), image('snapshot-preview.png')], surface: 'otherProjectState' },
+ ]);
+ });
+
+ it('leaves out what only shows or records media, and session state that is never saved', () => {
+ const shown = { imageName: 'shown.png' };
+ const doc = project({
+ fields: {
+ events: [{ payload: shown }],
+ queue: { items: [{ results: [shown] }] },
+ undoRedo: { future: [], past: [{ project: { widgetInstances: { a: shown } } }] },
+ widgetGraphs: { generate: { nodes: [{ inputs: { image: { image_name: 'shown.png' } } }] } },
+ workflowHistories: { wf: { future: [], past: [{ document: { nodes: [shown] } }] } },
+ },
+ widgets: { gallery: { semanticImageQuery: { imageName: 'shown.png', kind: 'image' } } },
+ workflow: { lastRun: shown },
+ });
+
+ expect(collectMediaUsage(doc, [image('shown.png')])).toEqual([]);
+ });
+
+ it('finds no use in a fresh project that just generated the image and shows it everywhere it records runs', () => {
+ const initial = createInitialWorkbenchState();
+ const activeProjectId = initial.activeProjectId;
+ const atGallery = {
+ ...initial,
+ projects: initial.projects.map((candidate) =>
+ candidate.id === activeProjectId
+ ? { ...candidate, invocation: { ...candidate.invocation, destination: 'gallery' as const } }
+ : candidate
+ ),
+ };
+ const generated = {
+ height: 768,
+ imageName: 'generated.png',
+ imageUrl: '/api/v1/images/i/generated.png/full',
+ queuedAt: '2026-11-03T00:00:00.000Z',
+ sourceQueueItemId: 'run-1',
+ thumbnailUrl: '/api/v1/images/i/generated.png/thumbnail',
+ width: 512,
+ };
+ // The real result routing: the Gallery's recents and selection, as a finished run leaves them.
+ const routed = workbenchReducer(atGallery, {
+ images: [generated],
+ projectId: activeProjectId,
+ queueItemId: 'run-1',
+ type: 'routeQueueItemResults',
+ });
+ const project = routed.projects.find((candidate) => candidate.id === activeProjectId)!;
+ // What a run records beside that: its queue entry and results, the event log, the submitted graph, and a workflow
+ // run preview.
+ const ran = {
+ ...project,
+ events: [...project.events, { createdAt: generated.queuedAt, id: 'e', image: generated, type: 'run-completed' }],
+ invocation: { ...project.invocation, lastSubmittedRunId: 'run-1' },
+ queue: { items: [{ id: 'run-1', resultImages: [generated], status: 'completed' }] },
+ widgetGraphs: {
+ generate: {
+ edges: [],
+ id: 'g',
+ label: 'Generate',
+ nodes: [{ id: 'n', inputs: { image: { image_name: 'generated.png' } }, type: 'i2l' }],
+ updatedAt: '',
+ version: 1,
+ },
+ },
+ workflows: {
+ ...project.workflows,
+ entries: project.workflows.entries.map((entry) => ({
+ ...entry,
+ lastRun: { completedAt: '', imageName: 'generated.png', submittedAt: '' },
+ })),
+ },
+ } as unknown as typeof project;
+
+ expect(JSON.stringify(ran.widgetInstances)).toContain('generated.png');
+ expect(collectMediaUsage(ran, [image('generated.png')])).toEqual([]);
+ });
+});
+
+describe('mergeMediaUsage', () => {
+ it('joins two copies of a project by surface, workflows and snapshots by id, in panel order', () => {
+ const merged = mergeMediaUsage(
+ [
+ { refs: [image('a.png')], surface: 'canvasRaster' },
+ { label: 'Same name', refs: [image('b.png')], sourceId: 'wf-1', surface: 'workflow' },
+ ],
+ [
+ { label: 'Same name', refs: [image('b.png')], sourceId: 'wf-2', surface: 'workflow' },
+ // wf-1, renamed in the other copy.
+ { label: 'Renamed', refs: [image('d.png')], sourceId: 'wf-1', surface: 'workflow' },
+ { refs: [image('c.png')], surface: 'canvasRaster' },
+ { refs: [image('f.png')], surface: 'generateReferenceImages' },
+ // a.png is on a layer in the other copy: listed there, not also elsewhere.
+ { refs: [image('a.png'), image('e.png')], surface: 'otherProjectState' },
+ ]
+ );
+
+ expect(merged).toEqual([
+ { refs: [image('f.png')], surface: 'generateReferenceImages' },
+ { refs: [image('a.png'), image('c.png')], surface: 'canvasRaster' },
+ { label: 'Same name', refs: [image('b.png'), image('d.png')], sourceId: 'wf-1', surface: 'workflow' },
+ { label: 'Same name', refs: [image('b.png')], sourceId: 'wf-2', surface: 'workflow' },
+ { refs: [image('e.png')], surface: 'otherProjectState' },
+ ]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
index d4cc72ba90..3630430055 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsage.ts
@@ -1,71 +1,223 @@
/**
* Where a project still uses gallery media the user is about to delete. Deleting such media removes the backing
* file under authored work, so the deletion flow must warn even when ordinary confirmations are turned off.
+ *
+ * The scan fails safe. The surfaces the panel names are listed below; whatever else in the project names a selected
+ * item counts too, as `otherProjectState`, unless an exclusion below says it only shows or records media. A field this
+ * build hydrates into `Project` that stores a media name therefore warns until it is given a surface or an exclusion.
+ * The scan sees only what loading kept, though: a field only a newer build writes is dropped when this build loads the
+ * project (the document allowlist, and the workspace canvas, of which only the selected layer and staging area are
+ * kept), so it is not scanned here.
*/
import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsageSurface } from '@features/gallery/mediaUsage';
import type { Project } from '@workbench/projectContracts';
+import { toGalleryItemKey } from '@features/gallery/contracts';
import { collectMediaNames, MAX_HELD_NAME_LENGTH, type MediaNameRefs } from '@workbench/mediaReferences';
import { getProjectWidgetValues } from '@workbench/widgetState';
-export type MediaUsageSurface =
- | 'generateReferenceImages'
- | 'canvasRaster'
- | 'canvasControl'
- | 'canvasRegionalGuidance'
- | 'canvasInpaintMask'
- | 'upscale'
- | 'video'
- | 'workflow';
-
export interface MediaUsage {
- surface: MediaUsageSurface;
- /** The workflow's name, for the `workflow` surface. */
+ surface: GalleryMediaUsageSurface;
+ /** The workflow's or snapshot's name, for the `workflow` and `canvasSnapshot` surfaces. */
label?: string;
- /** Selected names this surface uses, in selection order. */
- names: string[];
+ /** The workflow document's or snapshot's id: what identifies it across copies of the project, as names need not. */
+ sourceId?: string;
+ /** Selected items this surface uses, in selection order as `collectMediaUsage` lists them. */
+ refs: GalleryItemRef[];
}
-type UsageProject = Pick<Project, 'canvas' | 'widgetInstances' | 'workflows'>;
+type StackKind = keyof Project['canvas']['document']['stacks'];
+
+/** The canvas layer stacks, each its own surface; a new stack kind fails to compile until it has one. */
+const STACK_SURFACES = {
+ raster: 'canvasRaster',
+ control: 'canvasControl',
+ regional_guidance: 'canvasRegionalGuidance',
+ inpaint_mask: 'canvasInpaintMask',
+} as const satisfies Record<StackKind, GalleryMediaUsageSurface>;
+
+const STACK_KINDS = Object.keys(STACK_SURFACES) as StackKind[];
+
+/**
+ * How the remainder treats each project field: `scanned`, or `excluded` because it only shows or records media, or is
+ * session state that is never saved. Typed against `Project`, so a new field fails to compile until it is placed here.
+ */
+const PROJECT_FIELDS = {
+ // The listed surfaces read its layer stacks, staged results and each snapshot's document and staged results; the
+ // rest of it, a stack kind or snapshot field added later included, is scanned here.
+ canvas: 'scanned',
+ // Session-only run log; it names every generated image.
+ events: 'excluded',
+ floatingWidgets: 'scanned',
+ id: 'scanned',
+ invocation: 'scanned',
+ lastFloatingGeometry: 'scanned',
+ layout: 'scanned',
+ name: 'scanned',
+ presetWorkingLayouts: 'scanned',
+ promptHistory: 'scanned',
+ // Session-only queue runs and their results; they name every generated image.
+ queue: 'excluded',
+ settings: 'scanned',
+ // Session-only undo history, never saved; restoring it is not work the deletion breaks.
+ undoRedo: 'excluded',
+ // The last submitted graph per source widget, a record of a past run: the next run compiles from the widget's values.
+ widgetGraphs: 'excluded',
+ // Scanned without Gallery instances (below).
+ widgetInstances: 'scanned',
+ widgetRegions: 'scanned',
+ // Session-only workflow edit histories, never saved.
+ workflowHistories: 'excluded',
+ // Scanned without each workflow's last run (below).
+ workflows: 'scanned',
+} as const satisfies Record<keyof Project, 'excluded' | 'scanned'>;
+
+const isExcludedField = (key: string): boolean =>
+ Object.hasOwn(PROJECT_FIELDS, key) && PROJECT_FIELDS[key as keyof Project] === 'excluded';
const scan = (roots: readonly unknown[]): MediaNameRefs => collectMediaNames(roots, () => false, MAX_HELD_NAME_LENGTH);
-const selectedNamesIn = (refs: MediaNameRefs, selected: readonly GalleryItemRef[]): string[] =>
- selected.filter((ref) => (ref.kind === 'image' ? refs.images : refs.videos).has(ref.name)).map((ref) => ref.name);
+const selectedIn = (refs: MediaNameRefs, selected: readonly GalleryItemRef[]): GalleryItemRef[] =>
+ selected.filter((ref) => (ref.kind === 'image' ? refs.images : refs.videos).has(ref.name));
+
+/** `record` without `keys`: what a listed surface leaves of a container it reads only part of. */
+const without = <Value extends object>(record: Value, keys: readonly PropertyKey[]): Partial<Value> =>
+ Object.fromEntries(Object.entries(record).filter(([key]) => !keys.includes(key))) as Partial<Value>;
/**
- * The project's live surfaces that use any of `selected`, in panel order. History (undo, snapshots, queue) does
- * not count: deleting what only history could restore is a loss, not a hole in current work.
+ * The project without its excluded fields and without exactly what the listed surfaces scan (most of its bulk), so
+ * anything they do not read, a stack kind or snapshot field added later included, is still scanned. Excluded within
+ * scanned fields: Gallery instances (selection, recents, compare image, searches: they show media) and workflows'
+ * last runs (a record of a run's output).
*/
-export const collectMediaUsage = (project: UsageProject, selected: readonly GalleryItemRef[]): MediaUsage[] => {
+const remainderRoots = (project: Project): unknown[] => {
+ const { canvas, widgetInstances, workflows } = project;
+ const rest: Record<string, unknown> = {
+ ...project,
+ canvas: {
+ ...canvas,
+ document: { ...canvas.document, stacks: without(canvas.document.stacks, STACK_KINDS) },
+ snapshots: canvas.snapshots.map((snapshot) => without(snapshot, ['document', 'stagedImages'])),
+ stagingArea: without(canvas.stagingArea, ['pendingImages']),
+ },
+ widgetInstances: Object.values(widgetInstances).filter((instance) => instance.typeId !== 'gallery'),
+ workflows: {
+ ...workflows,
+ entries: workflows.entries.map(({ document, lastRun: _lastRun, ...entry }) => ({
+ ...entry,
+ document: without(document, ['nodes']),
+ })),
+ },
+ };
+
+ return Object.entries(rest).flatMap(([key, value]) => (isExcludedField(key) ? [] : [value]));
+};
+
+/**
+ * The project's surfaces that use any of `selected`, in panel order: live work, staged canvas results and canvas
+ * snapshots, which the user can still accept or restore; then `otherProjectState` for selected items that only the rest
+ * of the project names (see `PROJECT_FIELDS` for what that leaves out).
+ */
+export const collectMediaUsage = (project: Project, selected: readonly GalleryItemRef[]): MediaUsage[] => {
if (selected.length === 0) {
return [];
}
const usage: MediaUsage[] = [];
- const add = (surface: MediaUsageSurface, roots: readonly unknown[], label?: string): void => {
- const names = selectedNamesIn(scan(roots), selected);
+ const reported = new Set<string>();
+ const add = (
+ surface: GalleryMediaUsageSurface,
+ roots: readonly unknown[],
+ source?: { id: string; label: string }
+ ): void => {
+ const refs = selectedIn(scan(roots), selected);
- if (names.length > 0) {
- usage.push(label === undefined ? { names, surface } : { label, names, surface });
+ if (refs.length > 0) {
+ refs.forEach((ref) => reported.add(toGalleryItemKey(ref)));
+ usage.push(source ? { label: source.label, refs, sourceId: source.id, surface } : { refs, surface });
}
};
add('generateReferenceImages', [getProjectWidgetValues(project, 'generate').referenceImages]);
- const { stacks } = project.canvas.document;
- add('canvasRaster', [stacks.raster]);
- add('canvasControl', [stacks.control]);
- add('canvasRegionalGuidance', [stacks.regional_guidance]);
- add('canvasInpaintMask', [stacks.inpaint_mask]);
+ for (const kind of STACK_KINDS) {
+ add(STACK_SURFACES[kind], [project.canvas.document.stacks[kind]]);
+ }
+ add('canvasStaging', [project.canvas.stagingArea.pendingImages]);
+
+ for (const snapshot of project.canvas.snapshots) {
+ add('canvasSnapshot', [snapshot.document, snapshot.stagedImages], { id: snapshot.id, label: snapshot.name });
+ }
add('upscale', [getProjectWidgetValues(project, 'upscale').inputImage]);
add('video', [getProjectWidgetValues(project, 'video')]);
for (const entry of project.workflows.entries) {
- add('workflow', [entry.document.nodes], entry.document.name);
+ add('workflow', [entry.document.nodes], { id: entry.document.id, label: entry.document.name });
+ }
+
+ const elsewhere = selectedIn(scan(remainderRoots(project)), selected).filter(
+ (ref) => !reported.has(toGalleryItemKey(ref))
+ );
+
+ if (elsewhere.length > 0) {
+ usage.push({ refs: elsewhere, surface: 'otherProjectState' });
}
return usage;
};
+
+/** Panel order, as `collectMediaUsage` lists the surfaces. */
+const SURFACE_ORDER = {
+ generateReferenceImages: 0,
+ canvasRaster: 1,
+ canvasControl: 2,
+ canvasRegionalGuidance: 3,
+ canvasInpaintMask: 4,
+ canvasStaging: 5,
+ canvasSnapshot: 6,
+ upscale: 7,
+ video: 8,
+ workflow: 9,
+ otherProjectState: 10,
+} as const satisfies Record<GalleryMediaUsageSurface, number>;
+
+/**
+ * Two scans of one project (two copies of it) as one, in panel order: a surface either uses keeps the refs of both (a
+ * workflow or snapshot matched by id, named as in `first`), and `otherProjectState` keeps only refs no listed surface
+ * of either reports.
+ */
+export const mergeMediaUsage = (first: readonly MediaUsage[], second: readonly MediaUsage[]): MediaUsage[] => {
+ const merged = new Map<string, MediaUsage>();
+
+ for (const entry of [...first, ...second]) {
+ const key = JSON.stringify([entry.surface, entry.sourceId ?? entry.label ?? null]);
+ const existing = merged.get(key);
+
+ if (!existing) {
+ merged.set(key, { ...entry, refs: [...entry.refs] });
+ continue;
+ }
+
+ const held = new Set(existing.refs.map(toGalleryItemKey));
+
+ existing.refs.push(...entry.refs.filter((ref) => !held.has(toGalleryItemKey(ref))));
+ }
+
+ const listed = new Set(
+ [...merged.values()]
+ .filter((entry) => entry.surface !== 'otherProjectState')
+ .flatMap((entry) => entry.refs.map(toGalleryItemKey))
+ );
+
+ return [...merged.values()]
+ .map((entry) =>
+ entry.surface === 'otherProjectState'
+ ? { ...entry, refs: entry.refs.filter((ref) => !listed.has(toGalleryItemKey(ref))) }
+ : entry
+ )
+ .filter((entry) => entry.refs.length > 0)
+ .sort((a, b) => SURFACE_ORDER[a.surface] - SURFACE_ORDER[b.surface]);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts
new file mode 100644
index 0000000000..d263c6df4c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts
@@ -0,0 +1,615 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsage, GalleryMediaUsageDocument } from '@features/gallery/mediaUsage';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+
+import {
+ MEDIA_USAGE_MAX_NAMES_PER_KIND,
+ MEDIA_USAGE_MAX_PROJECT_READ_BYTES,
+ MEDIA_USAGE_MAX_PROJECT_READS,
+ resolveMediaUsage,
+ type MediaUsageHost,
+ type MediaUsageSyncBase,
+} from './mediaUsageReport';
+
+// The server and project reads are the external systems; the narrowing scan (`collectMediaUsage`) runs for real.
+const mocks = vi.hoisted(() => ({
+ check: vi.fn<(request: unknown, signal: AbortSignal) => Promise<unknown>>(),
+ getProject: vi.fn<(projectId: string, maxBytes: number, signal: AbortSignal) => Promise<unknown>>(),
+}));
+
+vi.mock('@features/gallery/mediaUsage', () => ({
+ checkGalleryMediaUsage: (request: unknown, signal: AbortSignal) => mocks.check(request, signal),
+}));
+vi.mock('@workbench/projects/api', () => ({
+ getProjectWithinSize: (projectId: string, maxBytes: number, signal: AbortSignal) =>
+ mocks.getProject(projectId, maxBytes, signal),
+}));
+vi.mock('@workbench/projects/projectHydration', () => ({
+ deserializeProjectRecord: (record: { project: unknown }) => ({ project: record.project, status: 'loaded' }),
+}));
+
+const image = (name: string): GalleryItemRef => ({ kind: 'image', name });
+
+const widget = (typeId: string, values: Record<string, unknown>) => ({
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id: typeId,
+ state: { id: typeId, label: typeId, values, version: 1 },
+ typeId,
+});
+
+/**
+ * A project whose canvas raster layers hold `raster`; `selected` is only the Gallery's selection, `pinned` a name in a
+ * widget the usage panel has no surface for.
+ */
+const project = (
+ id: string,
+ name: string,
+ { pinned = null as string | null, raster = [] as string[], selected = null as string | null } = {}
+) => ({
+ canvas: {
+ document: {
+ stacks: {
+ control: [],
+ inpaint_mask: [],
+ raster: raster.map((imageName, index) => ({ id: `${id}-${index}`, source: { image: { imageName } } })),
+ regional_guidance: [],
+ },
+ },
+ snapshots: [],
+ stagingArea: { pendingImages: [] },
+ },
+ id,
+ name,
+ widgetInstances: {
+ ...(selected === null ? {} : { gallery: widget('gallery', { selectedImageName: selected }) }),
+ ...(pinned === null ? {} : { 'image-notes': widget('image-notes', { pinned: { imageName: pinned } }) }),
+ },
+ workflows: { activeWorkflowId: null, entries: [] },
+});
+
+type TestProject = ReturnType<typeof project>;
+
+const usageDocument = (
+ kind: GalleryMediaUsageDocument['kind'],
+ id: string,
+ name: string | null,
+ imageNames: string[],
+ imageCount = imageNames.length
+): GalleryMediaUsageDocument => ({
+ id,
+ imageCount,
+ imageNames,
+ kind,
+ name,
+ revision: null,
+ videoCount: 0,
+ videoNames: [],
+ workspaceRevision: null,
+});
+
+const answer = (overrides: Partial<GalleryMediaUsage> = {}): GalleryMediaUsage => {
+ const documents = overrides.documents ?? [];
+ const names = new Set(documents.flatMap((entry) => entry.imageNames));
+
+ return {
+ checkedImageCount: 2,
+ checkedVideoCount: 0,
+ documents,
+ documentsTotal: documents.length,
+ inUseImageCount: names.size,
+ inUseVideoCount: 0,
+ otherAccounts: { documentCount: 0, imageCount: 0, queueItemCount: 0, videoCount: 0 },
+ queue: { imageCount: 0, imageNames: [], itemCount: 0, videoCount: 0, videoNames: [] },
+ ...overrides,
+ };
+};
+
+/** The server's copies of projects, by id, each at revision 4 of its content and 2 of the caller's workspace. */
+const serveProjects = (projects: readonly TestProject[]) => {
+ mocks.getProject.mockImplementation((projectId) => {
+ const found = projects.find((candidate) => candidate.id === projectId);
+
+ return found
+ ? Promise.resolve({ project: found, revision: 4, workspace: { revision: 2 } })
+ : Promise.reject(new ApiError('Project not found', 404));
+ });
+};
+
+/** What the server's copies in `serveProjects` build on. */
+const SERVED: MediaUsageSyncBase = { revision: 4, workspaceRevision: 2 };
+
+/** A project entry as the server reads it at the revisions `serveProjects` serves. */
+const atServed = (entry: GalleryMediaUsageDocument): GalleryMediaUsageDocument => ({
+ ...entry,
+ revision: 4,
+ workspaceRevision: 2,
+});
+
+/** This tab's projects, and by id the server revisions each copy builds on (unknown when absent). */
+const host = (
+ loaded: readonly TestProject[] = [],
+ openProjectId: string | null = null,
+ bases: Readonly<Record<string, MediaUsageSyncBase>> = {}
+): MediaUsageHost => ({
+ getLoadedProjects: () => loaded as unknown as ReturnType<MediaUsageHost['getLoadedProjects']>,
+ getSyncBase: (projectId) => bases[projectId],
+ openProjectId,
+});
+
+const items = (...names: string[]) => ({ kind: 'items' as const, refs: names.map(image) });
+
+beforeEach(() => {
+ accountLifecycle.activate('user-a');
+ mocks.check.mockReset();
+ mocks.getProject.mockReset();
+});
+
+afterEach(() => {
+ accountLifecycle.invalidate();
+});
+
+describe('resolveMediaUsage', () => {
+ it('drops a project the server names only for its gallery selection, and recounts what is in use', async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ usageDocument('project', 'p-a', 'Atlas', ['a.png']),
+ usageDocument('project', 'p-b', 'Birch', ['b.png']),
+ ],
+ })
+ );
+ serveProjects([project('p-a', 'Atlas', { raster: ['a.png'] }), project('p-b', 'Birch', { selected: 'b.png' })]);
+
+ const report = await resolveMediaUsage(items('a.png', 'b.png'), host());
+
+ expect(report).toEqual({
+ checkedCount: 2,
+ groups: [{ count: 1, kind: 'project', name: 'Atlas', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ // The server counted both; only one is used by work.
+ inUseCount: 1,
+ onlyImages: true,
+ scope: 'items',
+ serverCheck: 'complete',
+ });
+ });
+
+ it('keeps a project whose only use of the media is a field the panel has no surface for', async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ usageDocument('project', 'p-a', 'Atlas', ['a.png']),
+ usageDocument('project', 'p-b', 'Birch', ['b.png']),
+ ],
+ })
+ );
+ serveProjects([project('p-a', 'Atlas', { pinned: 'a.png' })]);
+
+ const report = await resolveMediaUsage(
+ items('a.png', 'b.png'),
+ host([project('p-b', 'Birch', { pinned: 'b.png' })])
+ );
+
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'project', name: 'Birch', surfaces: [{ count: 1, surface: 'otherProjectState' }] },
+ { count: 1, kind: 'project', name: 'Atlas', surfaces: [{ count: 1, surface: 'otherProjectState' }] },
+ ]);
+ expect(report.inUseCount).toBe(2);
+ });
+
+ it('counts the items asked about, as the dialog title does, even when the server could check fewer', async () => {
+ // Of three selected items on a shared board the caller owns one: the server checks only that one, without saying
+ // which, so the projects here are scanned for all three.
+ mocks.check.mockResolvedValue(answer({ checkedImageCount: 1 }));
+
+ const report = await resolveMediaUsage(
+ items('mine.png', 'theirs-1.png', 'theirs-2.png'),
+ host([project('open', 'Open', { raster: ['theirs-1.png'] })], 'open')
+ );
+
+ expect(report).toMatchObject({ checkedCount: 3, inUseCount: 1 });
+ });
+
+ it('tells an image from a video of the same name when counting what a project uses', async () => {
+ mocks.check.mockRejectedValue(new ApiError('Not Found', 404));
+ const loaded = {
+ ...project('open', 'Open'),
+ widgetInstances: { video: widget('video', { sourceVideo: { video_name: 'same' } }) },
+ };
+
+ const report = await resolveMediaUsage(
+ { kind: 'items', refs: [image('same'), { kind: 'video', name: 'same' }] },
+ host([loaded as unknown as TestProject], 'open')
+ );
+
+ expect(report.groups).toEqual([{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'video' }] }]);
+ expect(report.inUseCount).toBe(1);
+ });
+
+ it('lists a project as the server counts it when it cannot be read, its names are capped, or past the read cap', async () => {
+ const readable = Array.from({ length: MEDIA_USAGE_MAX_PROJECT_READS }, (_, index) => `p-${index}`);
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ usageDocument('project', 'p-capped', 'Capped', ['a.png'], 1500),
+ ...readable.map((id) => usageDocument('project', id, id, ['a.png'])),
+ usageDocument('project', 'p-late', 'Late', ['b.png']),
+ ],
+ })
+ );
+ // p-0 cannot be read; the others read fine but use nothing.
+ serveProjects(readable.slice(1).map((id) => project(id, id)));
+
+ const report = await resolveMediaUsage(items('a.png', 'b.png'), host());
+
+ expect(mocks.getProject.mock.calls.map(([projectId]) => projectId).sort()).toEqual([...readable].sort());
+ expect(report.groups).toEqual([
+ { count: 1500, kind: 'projectUnchecked', name: 'Capped' },
+ { count: 1, kind: 'projectUnchecked', name: 'p-0' },
+ { count: 1, kind: 'projectUnchecked', name: 'Late' },
+ ]);
+ // The capped list's true count exceeds what was checked; the count never claims more than was asked about.
+ expect(report.inUseCount).toBe(2);
+ });
+
+ it("trusts this tab's copy without reading the server's when the server holds nothing newer", async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ atServed(usageDocument('project', 'open', 'Open', ['a.png'])),
+ // What this copy builds on is unknown, but its scan reports every name the server found.
+ usageDocument('project', 'tab-2', 'Second', ['b.png']),
+ ],
+ })
+ );
+ const loaded = [
+ // Saved with a.png; since then the layer was replaced by an unsaved b.png.
+ project('open', 'Open', { raster: ['b.png'] }),
+ // Saved with b.png; a.png added since, unsaved.
+ project('tab-2', 'Second', { raster: ['a.png', 'b.png'] }),
+ ];
+
+ const report = await resolveMediaUsage(items('a.png', 'b.png'), host(loaded, 'open', { open: SERVED }));
+
+ expect(mocks.getProject).not.toHaveBeenCalled();
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },
+ { count: 2, kind: 'project', name: 'Second', surfaces: [{ count: 2, surface: 'canvasRaster' }] },
+ ]);
+ expect(report.inUseCount).toBe(2);
+ });
+
+ it('drops a loaded project the server names only for its Gallery selection, without reading it', async () => {
+ // The common deletion: the image the user is looking at, saved as the selection and nothing else.
+ mocks.check.mockResolvedValue(
+ answer({ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png']))] })
+ );
+
+ const report = await resolveMediaUsage(
+ items('a.png'),
+ host([project('open', 'Open', { selected: 'a.png' })], 'open', { open: SERVED })
+ );
+
+ expect(mocks.getProject).not.toHaveBeenCalled();
+ expect(report).toMatchObject({ groups: [], inUseCount: 0, serverCheck: 'complete' });
+ });
+
+ it('narrows a board by the names the server found in each project', async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ checkedImageCount: 5,
+ checkedVideoCount: 1,
+ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png', 'b.png']))],
+ })
+ );
+
+ const report = await resolveMediaUsage(
+ { boardId: 'board-1', kind: 'board' },
+ host([project('open', 'Open', { raster: ['b.png'], selected: 'a.png' })], 'open', { open: SERVED })
+ );
+
+ expect(mocks.getProject).not.toHaveBeenCalled();
+ expect(mocks.check).toHaveBeenCalledWith({ boardId: 'board-1', kind: 'board' }, expect.any(AbortSignal));
+ expect(report).toMatchObject({
+ checkedCount: 6,
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ onlyImages: false,
+ scope: 'board',
+ });
+ });
+
+ it("does not keep the server's count for a name a scan dropped, even when the scan found a new one", async () => {
+ // The server saw a.png in the open project's recents; the project now uses c.png, not yet saved. Another account
+ // uses c.png too, so the count cannot be read off the names alone.
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png']))],
+ inUseImageCount: 2,
+ otherAccounts: { documentCount: 1, imageCount: 1, queueItemCount: 0, videoCount: 0 },
+ })
+ );
+
+ const report = await resolveMediaUsage(
+ items('a.png', 'c.png'),
+ host([project('open', 'Open', { raster: ['c.png'], selected: 'a.png' })], 'open', { open: SERVED })
+ );
+
+ expect(report.inUseCount).toBe(1);
+ });
+
+ it.each([
+ ['its content is behind', { revision: 3, workspaceRevision: 2 }],
+ ['its workspace is behind', { revision: 4, workspaceRevision: 1 }],
+ ['what it builds on is unknown', undefined],
+ ] as const)(
+ "reads the server's copy and keeps a use it holds when this tab's copy may be older: %s",
+ async (_case, base) => {
+ // Another tab or device pinned a.png and saved; this tab's copy, unsaved since, uses only b.png.
+ mocks.check.mockResolvedValue(
+ answer({ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png', 'b.png']))] })
+ );
+ serveProjects([project('open', 'Open', { pinned: 'a.png', raster: ['b.png'] })]);
+
+ const report = await resolveMediaUsage(
+ items('a.png', 'b.png'),
+ host([project('open', 'Open', { raster: ['b.png'] })], 'open', base ? { open: base } : {})
+ );
+
+ expect(mocks.getProject.mock.calls.map(([projectId]) => projectId)).toEqual(['open']);
+ expect(report.groups).toEqual([
+ {
+ count: 2,
+ kind: 'openProject',
+ surfaces: [
+ { count: 1, surface: 'canvasRaster' },
+ { count: 1, surface: 'otherProjectState' },
+ ],
+ },
+ ]);
+ expect(report.inUseCount).toBe(2);
+ }
+ );
+
+ it("reads the server's copy when the server did not say which revisions it read, and trusts this tab's if it builds on it", async () => {
+ mocks.check.mockResolvedValue(answer({ documents: [usageDocument('project', 'open', 'Open', ['a.png'])] }));
+ serveProjects([project('open', 'Open', { raster: ['a.png'] })]);
+
+ const report = await resolveMediaUsage(
+ items('a.png', 'b.png'),
+ host([project('open', 'Open', { raster: ['b.png'] })], 'open', { open: SERVED })
+ );
+
+ expect(mocks.getProject.mock.calls.map(([projectId]) => projectId)).toEqual(['open']);
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },
+ ]);
+ });
+
+ it("keeps the server's count for an open project whose saved version cannot be read, beside what its copy uses", async () => {
+ mocks.check.mockResolvedValue(
+ answer({ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png']))] })
+ );
+ mocks.getProject.mockRejectedValue(new ApiError('Service Unavailable', 503));
+
+ const report = await resolveMediaUsage(
+ items('a.png', 'b.png'),
+ host([project('open', 'Open', { raster: ['b.png'] })], 'open', { open: { revision: 3, workspaceRevision: 2 } })
+ );
+
+ // The server's a.png stands beside the b.png found here.
+ expect(report.groups).toEqual([
+ { count: 2, kind: 'openProject', savedCopyUnchecked: true, surfaces: [{ count: 1, surface: 'canvasRaster' }] },
+ ]);
+ expect(report.inUseCount).toBe(2);
+ });
+
+ it.each([
+ ['in conflict', { conflict: { detectedAt: '2026-01-01T00:00:00.000Z', kind: 'revision' as const } }],
+ [
+ 'refused for its schema',
+ { schemaRefusal: { kind: 'canvas' as const, maxCanvasSchemaVersion: 3, minimumCanvasSchemaVersion: 4 } },
+ ],
+ ])(
+ "reads and joins the server's copy of a project %s, whose reported revisions its copy does not build on",
+ async (_case, decision) => {
+ // Saved from another device with a.png at the reported revisions; this tab shows a diverged draft without it.
+ mocks.check.mockResolvedValue(
+ answer({ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png']))] })
+ );
+ serveProjects([project('open', 'Open', { raster: ['a.png'] })]);
+
+ const report = await resolveMediaUsage(
+ items('a.png'),
+ host([project('open', 'Open')], 'open', { open: { ...SERVED, ...decision } })
+ );
+
+ expect(mocks.getProject.mock.calls.map(([projectId]) => projectId)).toEqual(['open']);
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },
+ ]);
+ }
+ );
+
+ it('reads a project open here that needs it before closed projects, within the read cap', async () => {
+ const closed = Array.from({ length: MEDIA_USAGE_MAX_PROJECT_READS }, (_, index) => `p-${index}`);
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ ...closed.map((id) => usageDocument('project', id, id, ['a.png'])),
+ usageDocument('project', 'open', 'Open', ['a.png']),
+ ],
+ })
+ );
+ serveProjects([project('open', 'Open'), ...closed.map((id) => project(id, id))]);
+
+ await resolveMediaUsage(items('a.png'), host([project('open', 'Open')], 'open'));
+
+ expect(mocks.getProject.mock.calls.map(([projectId]) => projectId).sort()).toEqual(
+ ['open', ...closed.slice(0, -1)].sort()
+ );
+ });
+
+ it("keeps a board item the server's newer copy uses, listed once beside the uses found here", async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ checkedImageCount: 3,
+ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png', 'b.png']))],
+ })
+ );
+ // Saved elsewhere: a.png on a layer and pinned. Here, unsaved: the a.png layer replaced by b.png.
+ serveProjects([project('open', 'Open', { pinned: 'a.png', raster: ['a.png'] })]);
+
+ const report = await resolveMediaUsage(
+ { boardId: 'board-1', kind: 'board' },
+ host([project('open', 'Open', { raster: ['b.png'] })], 'open', { open: { revision: 3, workspaceRevision: 2 } })
+ );
+
+ expect(report).toMatchObject({
+ groups: [{ count: 2, kind: 'openProject', surfaces: [{ count: 2, surface: 'canvasRaster' }] }],
+ inUseCount: 2,
+ });
+ });
+
+ it('reads no closed project past the size bound, listing it as the server counts it', async () => {
+ mocks.check.mockResolvedValue(answer({ documents: [usageDocument('project', 'p-big', 'Big', ['a.png'])] }));
+ // What the transport answers for a record over the bound.
+ mocks.getProject.mockResolvedValue(null);
+
+ const report = await resolveMediaUsage(items('a.png'), host());
+
+ expect(mocks.getProject).toHaveBeenCalledWith('p-big', MEDIA_USAGE_MAX_PROJECT_READ_BYTES, expect.any(AbortSignal));
+ expect(report.groups).toEqual([{ count: 1, kind: 'projectUnchecked', name: 'Big' }]);
+ });
+
+ it('says a selection past what one check takes was too large, not that the server failed', async () => {
+ const names = Array.from({ length: MEDIA_USAGE_MAX_NAMES_PER_KIND + 1 }, (_, index) => `${index}.png`);
+
+ const report = await resolveMediaUsage(
+ items(...names),
+ host([project('open', 'Open', { raster: ['7.png'] })], 'open')
+ );
+
+ expect(mocks.check).not.toHaveBeenCalled();
+ expect(report.serverCheck).toBe('tooManyItems');
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },
+ ]);
+ });
+
+ it('takes workflows, the legacy editor, projects kept for repair, unknown documents, queued jobs and other accounts as they are', async () => {
+ mocks.check.mockResolvedValue(
+ answer({
+ documents: [
+ usageDocument('legacyEditor', 'legacy_editor', null, ['a.png']),
+ usageDocument('quarantinedProject', 'q-1', 'Broken', ['b.png']),
+ usageDocument('workflow', 'wf-1', 'Upscale pass', ['a.png', 'b.png']),
+ // A kind of saved document this build does not know.
+ usageDocument('other', 'board-notes-1', 'Board notes', ['b.png']),
+ usageDocument('other', 'unnamed-1', null, ['a.png']),
+ ],
+ documentsTotal: 105,
+ otherAccounts: { documentCount: 1, imageCount: 1, queueItemCount: 1, videoCount: 0 },
+ queue: { imageCount: 1, imageNames: ['a.png'], itemCount: 2, videoCount: 0, videoNames: [] },
+ })
+ );
+
+ const report = await resolveMediaUsage(items('a.png', 'b.png'), host());
+
+ expect(report.groups).toEqual([
+ { count: 1, kind: 'quarantinedProject', name: 'Broken' },
+ { count: 2, kind: 'workflow', name: 'Upscale pass' },
+ { count: 1, kind: 'legacyEditor' },
+ { count: 1, kind: 'otherDocument', name: 'Board notes' },
+ { count: 1, kind: 'otherDocument', name: null },
+ { documentCount: 100, kind: 'moreDocuments' },
+ { count: 1, jobCount: 2, kind: 'queue' },
+ { count: 1, kind: 'otherAccounts' },
+ ]);
+ expect(report.inUseCount).toBe(2);
+ });
+
+ it('still scans the projects this tab holds when the server check fails, and says the rest went unchecked', async () => {
+ mocks.check.mockRejectedValue(new ApiError('Not Found', 404));
+
+ const report = await resolveMediaUsage(
+ items('a.png'),
+ host([project('open', 'Open', { raster: ['a.png'] })], 'open')
+ );
+
+ expect(report).toEqual({
+ checkedCount: 1,
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ onlyImages: true,
+ scope: 'items',
+ serverCheck: 'unavailable',
+ });
+ // A board's items are known only to the server.
+ await expect(resolveMediaUsage({ boardId: 'board-1', kind: 'board' }, host())).rejects.toThrow();
+ });
+
+ it('gives up on a server that does not answer in time', async () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ mocks.check.mockImplementation(
+ (_request, signal) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(signal.reason));
+ })
+ );
+
+ const pending = resolveMediaUsage(items('a.png'), host(), { serverTimeoutMs: 10 });
+ await vi.advanceTimersByTimeAsync(9);
+
+ expect(mocks.check.mock.calls[0]?.[1].aborted).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const report = await pending;
+
+ expect(report.serverCheck).toBe('unavailable');
+ expect(report.groups).toEqual([]);
+ });
+
+ it('lists a closed project as the server counts it when reading it outlasts the deadline', async () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ mocks.check.mockResolvedValue(answer({ documents: [usageDocument('project', 'p-slow', 'Slow', ['a.png'])] }));
+ mocks.getProject.mockImplementation(
+ (_projectId, _maxBytes, signal) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(signal.reason));
+ })
+ );
+
+ const pending = resolveMediaUsage(items('a.png'), host(), { projectReadsTimeoutMs: 50 });
+ await vi.advanceTimersByTimeAsync(50);
+ const report = await pending;
+
+ expect(report.groups).toEqual([{ count: 1, kind: 'projectUnchecked', name: 'Slow' }]);
+ });
+
+ it('stops without reading projects when the account changes during the check', async () => {
+ let settle: (value: GalleryMediaUsage) => void = () => {};
+ mocks.check.mockReturnValue(
+ new Promise((resolve) => {
+ settle = resolve;
+ })
+ );
+
+ const pending = resolveMediaUsage(items('a.png'), host());
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ settle(answer({ documents: [usageDocument('project', 'p-a', 'Atlas', ['a.png'])] }));
+
+ await expect(pending).rejects.toThrow();
+ expect(mocks.getProject).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts
new file mode 100644
index 0000000000..cb70c04c2c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts
@@ -0,0 +1,510 @@
+/**
+ * Where media about to be deleted is still used, across the account: the server's reference check narrowed by the
+ * projects' own scans. The server counts every media name a project document holds, including the Gallery's selection
+ * and recents and workflow last runs, which only show or record media; the deletion breaks the rest. So each project
+ * the server names is scanned here (`collectMediaUsage`), from memory when this tab has it loaded, else read from the
+ * server without opening it in the editor, and is dropped only when the scan finds nothing. The scan fails safe: it
+ * leaves out only fields it knows show or record media, and reports a name anywhere else in the project, so a field it
+ * has no surface for keeps the project in the report. Workflows, the legacy editor, projects kept for repair, queued
+ * jobs and other accounts are taken from the server as they are.
+ *
+ * A project in memory is fresher than the server for edits made here, which autosave after a short debounce, but not
+ * for a save from another tab or device since it loaded. Its scan stands when it reports every name the server found
+ * in it (the server's copy can hold no checked name the server did not list), or when the server read those names at
+ * the very revisions of the content and of the caller's workspace that the copy here builds on: an edit here then
+ * removed what the scan dropped. A copy in conflict or refused for its schema builds on no reported revision: its
+ * revisions count as unknown. Otherwise (the server is ahead, or either side's revisions are unknown) the server's
+ * copy is read as a closed project is, and a ref either copy uses is in use. When that read cannot be made, the project
+ * keeps what its copy uses and the server's count, marked `savedCopyUnchecked`.
+ *
+ * For items, the requested refs are scanned. For a board, only the server knows the board's members, so a project in
+ * memory is scanned for the names the server attributed to it, and a use added here since its last save is missed.
+ */
+
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { Project } from '@workbench/projectContracts';
+import type { ProjectSyncInfo } from '@workbench/projects/syncStore';
+
+import { toGalleryItemKey } from '@features/gallery/contracts';
+import {
+ checkGalleryMediaUsage,
+ type GalleryMediaUsage,
+ type GalleryMediaUsageDocument,
+ type GalleryMediaUsageGroup,
+ type GalleryMediaUsageReport,
+ type GalleryMediaUsageRequest,
+ type GalleryMediaUsageSurfaceRow,
+} from '@features/gallery/mediaUsage';
+import { captureAccountScope, assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { getProjectWithinSize } from '@workbench/projects/api';
+import { deserializeProjectRecord } from '@workbench/projects/projectHydration';
+
+import { collectMediaUsage, mergeMediaUsage, type MediaUsage } from './mediaUsage';
+
+/** The server checks at most this many names of each kind per request. */
+export const MEDIA_USAGE_MAX_NAMES_PER_KIND = 1000;
+/**
+ * Projects read from the server to narrow its answer, at most, a few at a time: first projects in memory whose scan
+ * dropped a name the server found at revisions other than the ones the copy builds on, then closed projects. Each read
+ * transfers a whole project document; past the cap a project is listed as the server counts it.
+ */
+export const MEDIA_USAGE_MAX_PROJECT_READS = 6;
+/**
+ * A project larger than this is not read from the server: fetching, parsing and migrating it would hold the main thread
+ * while the user waits on a dialog. It is listed as the server counts it.
+ */
+export const MEDIA_USAGE_MAX_PROJECT_READ_BYTES = 4 * 1024 * 1024;
+const PROJECT_READ_CONCURRENCY = 2;
+const DEFAULT_SERVER_TIMEOUT_MS = 10_000;
+const DEFAULT_PROJECT_READS_TIMEOUT_MS = 5_000;
+
+/**
+ * The server revisions a copy of a project builds on (its content's, and the caller's workspace's), and whether it
+ * awaits a decision: a copy in conflict or refused holds local work the reported revisions do not describe.
+ */
+export type MediaUsageSyncBase = Pick<ProjectSyncInfo, 'conflict' | 'revision' | 'schemaRefusal' | 'workspaceRevision'>;
+
+export interface MediaUsageHost {
+ /** Projects this tab holds in memory, scanned as they are now. */
+ getLoadedProjects(): readonly Project[];
+ /**
+ * What this tab's copy of a loaded project builds on, as its persistence last learned it; undefined, or a null
+ * revision, when that is not known (never saved, no persistence). Its sync info as reported, conflict included.
+ */
+ getSyncBase(projectId: string): MediaUsageSyncBase | undefined;
+ /** The project the deletion is made from, listed as "This project"; null without one. */
+ openProjectId: string | null;
+}
+
+export interface MediaUsageOptions {
+ /** How long the server check may take before the report says it could not finish. */
+ serverTimeoutMs?: number;
+ /** How long reading projects from the server may take; any not read by then are listed as the server counts them. */
+ projectReadsTimeoutMs?: number;
+ signal?: AbortSignal;
+}
+
+/**
+ * A signal that aborts with `signal` or once `ms` pass; `clear` ends the timer when the stage finishes. A plain timer,
+ * not `AbortSignal.timeout`: a timeout signal reachable only through `AbortSignal.any` can be garbage collected before
+ * it fires (Node does, under memory pressure), and a stage would then wait on it forever.
+ */
+const withDeadline = (signal: AbortSignal, ms: number): { clear: () => void; signal: AbortSignal } => {
+ const controller = new AbortController();
+ const onAbort = () => controller.abort(signal.reason);
+ const timer = setTimeout(() => controller.abort(new DOMException('The usage check timed out.', 'TimeoutError')), ms);
+
+ if (signal.aborted) {
+ onAbort();
+ } else {
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
+
+ return {
+ clear: () => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', onAbort);
+ },
+ signal: controller.signal,
+ };
+};
+
+const isTruncated = (entry: GalleryMediaUsageDocument): boolean =>
+ entry.imageCount > entry.imageNames.length || entry.videoCount > entry.videoNames.length;
+
+const refsOf = (entry: GalleryMediaUsageDocument): GalleryItemRef[] => [
+ ...entry.imageNames.map((name) => ({ kind: 'image' as const, name })),
+ ...entry.videoNames.map((name) => ({ kind: 'video' as const, name })),
+];
+
+const dedupeRefs = (refs: readonly GalleryItemRef[]): GalleryItemRef[] => {
+ const seen = new Set<string>();
+
+ return refs.filter((ref) => {
+ const key = toGalleryItemKey(ref);
+
+ if (seen.has(key)) {
+ return false;
+ }
+ seen.add(key);
+ return true;
+ });
+};
+
+/** Whether a server document lists or counts a ref (by kind and name) that `used` lacks. */
+const dropsServerNames = (entry: GalleryMediaUsageDocument, used: ReadonlySet<string>): boolean =>
+ // A capped list hides names the scan may have dropped; more counted than the scan kept means some were.
+ refsOf(entry).some((ref) => !used.has(toGalleryItemKey(ref))) || entry.imageCount + entry.videoCount > used.size;
+
+interface ServerProject {
+ project: Project;
+ revision: number;
+ workspaceRevision: number | null;
+}
+
+/**
+ * Reads the server's copy of a project the way the editor would load it, without opening it; null when it cannot be
+ * loaded or is past the read bound.
+ */
+const readServerProject = async (projectId: string, signal: AbortSignal): Promise<ServerProject | null> => {
+ const record = await getProjectWithinSize(projectId, MEDIA_USAGE_MAX_PROJECT_READ_BYTES, signal);
+ const loaded = record ? deserializeProjectRecord(record) : null;
+
+ return record && loaded?.status === 'loaded'
+ ? { project: loaded.project, revision: record.revision, workspaceRevision: record.workspace?.revision ?? null }
+ : null;
+};
+
+/**
+ * Whether the server state at these revisions is exactly what `base` builds on: a copy built on it is that state plus
+ * edits here. Unknown on either side is not a match, nor is a copy awaiting a decision: a conflict or refusal keeps
+ * local work beside revisions it does not build on.
+ */
+const isServerCopyOf = (
+ base: MediaUsageSyncBase | undefined,
+ server: { revision: number | null; workspaceRevision: number | null }
+): boolean =>
+ base !== undefined &&
+ base.conflict === undefined &&
+ base.schemaRefusal === undefined &&
+ base.revision !== null &&
+ base.workspaceRevision !== undefined &&
+ server.revision !== null &&
+ base.revision === server.revision &&
+ base.workspaceRevision === server.workspaceRevision;
+
+const runLimited = async <Item>(
+ items: readonly Item[],
+ limit: number,
+ worker: (item: Item) => Promise<void>
+): Promise<void> => {
+ let next = 0;
+
+ await Promise.all(
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (next < items.length) {
+ const item = items[next];
+ next += 1;
+ await worker(item!);
+ }
+ })
+ );
+};
+
+/** The checked refs a project's surfaces use, by kind and name. */
+const usedKeysOf = (usage: readonly MediaUsage[]): Set<string> =>
+ new Set(usage.flatMap((entry) => entry.refs.map(toGalleryItemKey)));
+
+const toSurfaceRows = (usage: readonly MediaUsage[]): GalleryMediaUsageSurfaceRow[] =>
+ usage.map(({ label, refs, surface }) =>
+ label === undefined ? { count: refs.length, surface } : { count: refs.length, label, surface }
+ );
+
+type ProjectOutcome =
+ | { kind: 'scanned'; usage: MediaUsage[] }
+ /** Listed as the server counts it, beside `local`, this tab's scan of its copy, when it has one. */
+ | { kind: 'unchecked'; entry: GalleryMediaUsageDocument; local?: MediaUsage[] };
+
+/** A project to read from the server, scanned for `refs`; `local` is this tab's scan of its copy, when it has one. */
+interface ProjectRead {
+ entry: GalleryMediaUsageDocument;
+ local?: { base: MediaUsageSyncBase | undefined; usage: MediaUsage[] };
+ refs: GalleryItemRef[];
+}
+
+/**
+ * Where the requested media is used. For items, the server check failing (offline, an older server without the check,
+ * a timeout) does not fail the report: the projects this tab holds are still scanned and the report says the rest went
+ * unchecked. A board's members are known only to the server, so for a board that failure rejects. Otherwise rejects
+ * only when `signal` aborts or the account changes.
+ */
+export const resolveMediaUsage = async (
+ request: GalleryMediaUsageRequest,
+ host: MediaUsageHost,
+ {
+ projectReadsTimeoutMs = DEFAULT_PROJECT_READS_TIMEOUT_MS,
+ serverTimeoutMs = DEFAULT_SERVER_TIMEOUT_MS,
+ signal: callerSignal,
+ }: MediaUsageOptions = {}
+): Promise<GalleryMediaUsageReport> => {
+ const owner = captureAccountScope();
+ const signal = callerSignal ? AbortSignal.any([callerSignal, owner.signal]) : owner.signal;
+ const requestedRefs = request.kind === 'items' ? dedupeRefs(request.refs) : [];
+ const overServerLimit =
+ requestedRefs.filter((ref) => ref.kind === 'image').length > MEDIA_USAGE_MAX_NAMES_PER_KIND ||
+ requestedRefs.filter((ref) => ref.kind === 'video').length > MEDIA_USAGE_MAX_NAMES_PER_KIND;
+ let server: GalleryMediaUsage | null = null;
+
+ if (!overServerLimit) {
+ const deadline = withDeadline(signal, serverTimeoutMs);
+
+ try {
+ server = await checkGalleryMediaUsage(
+ request.kind === 'items' ? { kind: 'items', refs: requestedRefs } : request,
+ deadline.signal
+ );
+ } catch {
+ server = null;
+ } finally {
+ deadline.clear();
+ }
+ }
+
+ signal.throwIfAborted();
+ assertAccountScopeCurrent(owner);
+
+ if (server === null && request.kind === 'board') {
+ // Only the server knows a board's members, so nothing here can be scanned for them.
+ throw new Error('The media usage check did not answer for the board.');
+ }
+
+ const documents = server?.documents ?? [];
+ const serverProjects = new Map(
+ documents.filter((entry) => entry.kind === 'project').map((entry) => [entry.id, entry] as const)
+ );
+ const outcomes = new Map<string, ProjectOutcome>();
+ const loadedProjects = host.getLoadedProjects();
+ const reads: ProjectRead[] = [];
+
+ // Projects in memory: the items' own refs, or for a board the names the server found in that project (a board's
+ // members are known only to the server).
+ for (const project of loadedProjects) {
+ const entry = serverProjects.get(project.id);
+
+ if (request.kind === 'board' && entry && isTruncated(entry)) {
+ outcomes.set(project.id, { entry, kind: 'unchecked' });
+ continue;
+ }
+
+ const refs = request.kind === 'items' ? requestedRefs : entry ? refsOf(entry) : [];
+ const usage = collectMediaUsage(project, refs);
+ const localKeys = usedKeysOf(usage);
+
+ const base = host.getSyncBase(project.id);
+
+ if (entry && dropsServerNames(entry, localKeys) && !isServerCopyOf(base, entry)) {
+ // An edit here removed the name, or another tab or device saved a use this copy lacks: the server's copy decides.
+ outcomes.set(project.id, { entry, kind: 'unchecked', local: usage });
+ reads.push({ entry, local: { base, usage }, refs });
+ } else {
+ outcomes.set(project.id, { kind: 'scanned', usage });
+ }
+ }
+
+ const candidates = [...serverProjects.values()].filter((entry) => !outcomes.has(entry.id));
+
+ for (const entry of candidates) {
+ outcomes.set(entry.id, { entry, kind: 'unchecked' });
+ if (!isTruncated(entry)) {
+ reads.push({ entry, refs: refsOf(entry) });
+ }
+ }
+
+ const readsDeadline = withDeadline(signal, projectReadsTimeoutMs);
+ const readsSignal = readsDeadline.signal;
+
+ await runLimited(reads.slice(0, MEDIA_USAGE_MAX_PROJECT_READS), PROJECT_READ_CONCURRENCY, async (read) => {
+ try {
+ readsSignal.throwIfAborted();
+ const server = await readServerProject(read.entry.id, readsSignal);
+
+ if (!server) {
+ return;
+ }
+
+ const { local } = read;
+ const usage = !local
+ ? collectMediaUsage(server.project, read.refs)
+ : isServerCopyOf(local.base, server)
+ ? local.usage
+ : mergeMediaUsage(local.usage, collectMediaUsage(server.project, read.refs));
+
+ outcomes.set(read.entry.id, { kind: 'scanned', usage });
+ } catch {
+ // Unreadable, refused, or past the deadline: listed as the server counts it.
+ }
+ });
+ readsDeadline.clear();
+
+ signal.throwIfAborted();
+ assertAccountScopeCurrent(owner);
+
+ return buildReport({ documents, host, loadedProjects, outcomes, overServerLimit, request, requestedRefs, server });
+};
+
+const buildReport = ({
+ documents,
+ host,
+ loadedProjects,
+ outcomes,
+ overServerLimit,
+ request,
+ requestedRefs,
+ server,
+}: {
+ documents: readonly GalleryMediaUsageDocument[];
+ host: MediaUsageHost;
+ loadedProjects: ReturnType<MediaUsageHost['getLoadedProjects']>;
+ outcomes: ReadonlyMap<string, ProjectOutcome>;
+ overServerLimit: boolean;
+ request: GalleryMediaUsageRequest;
+ requestedRefs: readonly GalleryItemRef[];
+ server: GalleryMediaUsage | null;
+}): GalleryMediaUsageReport => {
+ const groups: GalleryMediaUsageGroup[] = [];
+ const inUse = new Set<string>();
+ // Sources whose names are not all known (capped lists, other accounts) bound the count from below.
+ let lowerBound = 0;
+ let exact = true;
+ // A server project entry replaced by a scan that dropped one of its names: the server's own in-use total, which
+ // counted that name, no longer holds.
+ let narrowed = false;
+ const addNames = (entry: { imageCount: number; imageNames: string[]; videoCount: number; videoNames: string[] }) => {
+ entry.imageNames.forEach((name) => inUse.add(toGalleryItemKey({ kind: 'image', name })));
+ entry.videoNames.forEach((name) => inUse.add(toGalleryItemKey({ kind: 'video', name })));
+ if (entry.imageCount > entry.imageNames.length || entry.videoCount > entry.videoNames.length) {
+ exact = false;
+ lowerBound = Math.max(lowerBound, entry.imageCount + entry.videoCount);
+ }
+ };
+ const serverEntryOf = (projectId: string) =>
+ documents.find((document) => document.kind === 'project' && document.id === projectId);
+ const projectGroup = (projectId: string, name: string | null): GalleryMediaUsageGroup | null => {
+ const outcome = outcomes.get(projectId);
+
+ if (!outcome) {
+ return null;
+ }
+ if (outcome.kind === 'unchecked') {
+ const { entry, local } = outcome;
+
+ addNames(entry);
+ if (!local) {
+ return { count: entry.imageCount + entry.videoCount, kind: 'projectUnchecked', name };
+ }
+
+ // A project open here: what its copy uses, beside the server's names its saved version could not be checked for.
+ const localKeys = usedKeysOf(local);
+ const count = Math.max(
+ entry.imageCount + entry.videoCount,
+ new Set([...refsOf(entry).map(toGalleryItemKey), ...localKeys]).size
+ );
+ const surfaces = toSurfaceRows(local);
+
+ localKeys.forEach((key) => inUse.add(key));
+ return projectId === host.openProjectId
+ ? { count, kind: 'openProject', savedCopyUnchecked: true, surfaces }
+ : { count, kind: 'project', name, savedCopyUnchecked: true, surfaces };
+ }
+
+ const used = usedKeysOf(outcome.usage);
+ const entry = serverEntryOf(projectId);
+
+ if (entry && dropsServerNames(entry, used)) {
+ narrowed = true;
+ }
+ if (used.size === 0) {
+ return null;
+ }
+ used.forEach((key) => inUse.add(key));
+
+ const surfaces = toSurfaceRows(outcome.usage);
+
+ return projectId === host.openProjectId
+ ? { count: used.size, kind: 'openProject', surfaces }
+ : { count: used.size, kind: 'project', name, surfaces };
+ };
+ const loadedIds = new Set(loadedProjects.map((project) => project.id));
+ const openProject = loadedProjects.find((project) => project.id === host.openProjectId);
+ const openGroup = openProject ? projectGroup(openProject.id, openProject.name) : null;
+
+ if (openGroup) {
+ groups.push(openGroup);
+ }
+ for (const project of loadedProjects) {
+ const group = project.id === host.openProjectId ? null : projectGroup(project.id, project.name);
+
+ if (group) {
+ groups.push(group);
+ }
+ }
+ for (const entry of documents) {
+ if (entry.kind === 'project') {
+ const group = loadedIds.has(entry.id) ? null : projectGroup(entry.id, entry.name);
+
+ if (group) {
+ groups.push(group);
+ }
+ }
+ }
+
+ const listed = (
+ kind: GalleryMediaUsageDocument['kind'],
+ toGroup: (entry: GalleryMediaUsageDocument) => GalleryMediaUsageGroup
+ ) => {
+ for (const entry of documents) {
+ if (entry.kind === kind) {
+ addNames(entry);
+ groups.push(toGroup(entry));
+ }
+ }
+ };
+ const countOf = (entry: GalleryMediaUsageDocument) => entry.imageCount + entry.videoCount;
+
+ listed('quarantinedProject', (entry) => ({ count: countOf(entry), kind: 'quarantinedProject', name: entry.name }));
+ listed('workflow', (entry) => ({ count: countOf(entry), kind: 'workflow', name: entry.name }));
+ listed('legacyEditor', (entry) => ({ count: countOf(entry), kind: 'legacyEditor' }));
+ listed('other', (entry) => ({ count: countOf(entry), kind: 'otherDocument', name: entry.name }));
+
+ if (server) {
+ const unlisted = server.documentsTotal - server.documents.length;
+
+ if (unlisted > 0) {
+ exact = false;
+ groups.push({ documentCount: unlisted, kind: 'moreDocuments' });
+ }
+ if (server.queue.itemCount > 0) {
+ addNames(server.queue);
+ groups.push({
+ count: server.queue.imageCount + server.queue.videoCount,
+ jobCount: server.queue.itemCount,
+ kind: 'queue',
+ });
+ }
+
+ const others = server.otherAccounts;
+
+ if (others.documentCount + others.queueItemCount > 0) {
+ exact = false;
+ lowerBound = Math.max(lowerBound, others.imageCount + others.videoCount);
+ groups.push({ count: others.imageCount + others.videoCount, kind: 'otherAccounts' });
+ }
+ }
+
+ // Items: what was asked about, as the dialog's title counts them. The server's checked counts leave out items the
+ // caller may not delete, but not which ones, so this tab's scans could not be held to the same set. A board: the
+ // server's count, the items deleting it removes.
+ const checkedCount =
+ request.kind === 'items' || !server ? requestedRefs.length : server.checkedImageCount + server.checkedVideoCount;
+ const serverInUse = server && !narrowed ? server.inUseImageCount + server.inUseVideoCount : 0;
+ const inUseCount = exact ? inUse.size : Math.max(inUse.size, lowerBound, serverInUse);
+
+ return {
+ checkedCount,
+ groups,
+ inUseCount: Math.min(inUseCount, checkedCount),
+ onlyImages:
+ request.kind === 'items'
+ ? requestedRefs.every((ref) => ref.kind === 'image')
+ : server !== null && server.checkedVideoCount === 0,
+ scope: request.kind,
+ serverCheck: server ? 'complete' : overServerLimit ? 'tooManyItems' : 'unavailable',
+ };
+};
+
+/**
+ * Whether a project this tab holds uses any of `refs` now: a last look before deleting without asking, since a use
+ * added while the check ran is not in its answer.
+ */
+export const isUsedInLoadedProjects = (refs: readonly GalleryItemRef[], host: MediaUsageHost): boolean =>
+ host.getLoadedProjects().some((project) => collectMediaUsage(project, refs).length > 0);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx
index a8004304e3..7bf586fec1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx
@@ -1,9 +1,11 @@
import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsageReport } from '@features/gallery/mediaUsage';
import type * as projectsApi from '@workbench/projects/api';
import type { Ref } from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { toaster } from '@platform/ui/toaster';
import { system } from '@theme/system';
import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/settings/store';
import { act, createRef, useImperativeHandle } from 'react';
@@ -27,6 +29,9 @@ vi.mock('react-i18next', () => ({
const count = Number(values?.count ?? 0);
const messages: Record<string, string> = {
'common.cancel': 'Cancel',
+ 'common.retry': 'Retry',
+ 'widgets.gallery.deleteBlockedByPending': `${String(values?.media)} not deleted: answer the open deletion first.`,
+ 'widgets.gallery.deleteBlockedByRunning': `${String(values?.media)} not deleted: wait for the deletion under way.`,
'widgets.gallery.deleteConfirmLabel': 'Delete',
'widgets.gallery.deleteConfirmSkip': "Don't ask me again",
'widgets.gallery.deleteConfirmSkipHint': 'You can turn this confirmation back on in Settings.',
@@ -36,11 +41,31 @@ vi.mock('react-i18next', () => ({
'widgets.gallery.deleteItemsConfirmBody':
count === 1 ? 'Permanently delete the item.' : 'Permanently delete these items.',
'widgets.gallery.deleteItemsConfirmTitle': count === 1 ? 'Delete item?' : `Delete ${count} items?`,
- 'widgets.gallery.deleteInUse.heading': 'Still used in this project:',
+ 'widgets.gallery.deleteInUse.checking': 'Checking where this media is used…',
+ 'widgets.gallery.deleteInUse.failed': 'Couldn’t check where this media is used.',
+ 'widgets.gallery.deleteInUse.group.openProject': 'This project',
+ 'widgets.gallery.deleteInUse.group.project': `Project “${String(values?.name)}”`,
+ 'widgets.gallery.deleteInUse.group.projectUnnamed': 'Untitled project',
+ 'widgets.gallery.deleteInUse.group.queue':
+ count === 1 ? '1 queued or running job' : `${count} queued or running jobs`,
+ 'widgets.gallery.deleteInUse.group.workflow': `Library workflow “${String(values?.name)}”`,
+ 'widgets.gallery.deleteInUse.listLabel': 'Where the media is used',
+ 'widgets.gallery.deleteInUse.none': 'Nothing uses this media.',
+ 'widgets.gallery.deleteInUse.projectUncheckedHint': 'Couldn’t open it to see where.',
+ 'widgets.gallery.deleteInUse.savedCopyUncheckedHint': 'Its saved version couldn’t be checked.',
+ 'widgets.gallery.deleteInUse.queueWarning':
+ count === 1 ? 'Jobs that use it will fail.' : 'Jobs that use them will fail.',
+ 'widgets.gallery.deleteInUse.summary': `${count} of these ${String(values?.media)} are still in use:`,
+ 'widgets.gallery.deleteInUse.summaryAll': `All ${String(values?.media)} are still in use:`,
+ 'widgets.gallery.deleteInUse.summaryOne': 'Still in use:',
'widgets.gallery.deleteInUse.surface.canvasRaster': 'Canvas raster layers',
'widgets.gallery.deleteInUse.surface.workflow': `Workflow “${String(values?.name)}”`,
- 'widgets.gallery.deleteInUse.usedCount': count === 1 ? '1 selected item' : `${count} selected items`,
- 'widgets.gallery.deleteInUse.warning': 'The affected work keeps pointing at media that will no longer exist.',
+ 'widgets.gallery.deleteInUse.unchecked': 'Other projects couldn’t be checked.',
+ 'widgets.gallery.deleteInUse.itemCount': count === 1 ? '1 item' : `${count} items`,
+ 'widgets.gallery.deleteInUse.warning':
+ count === 1
+ ? 'Work that uses it will point at missing media.'
+ : 'Work that uses them will point at missing media.',
'widgets.gallery.deleteTargetImage': `Image ${String(values?.index)}`,
'widgets.gallery.deleteTargetVideo': `Video ${String(values?.index)}`,
'widgets.gallery.deleteTargetsMore': `+${count}`,
@@ -56,6 +81,9 @@ vi.mock('react-i18next', () => ({
}),
}));
+/** The report's code loads lazily on the first settled check; a cold transform under a busy run can take a while. */
+const REPORT_WAIT = { timeout: 5000 };
+
type ConfirmationHandle = { requestDeletionConfirmation: RequestDeletionConfirmation };
const Probe = ({ ref }: { ref: Ref<ConfirmationHandle> }) => {
@@ -67,6 +95,15 @@ const Probe = ({ ref }: { ref: Ref<ConfirmationHandle> }) => {
};
const imageRefs: GalleryItemRef[] = [{ kind: 'image', name: 'image.png' }];
+const usageReport = (overrides: Partial<GalleryMediaUsageReport>): GalleryMediaUsageReport => ({
+ checkedCount: 1,
+ groups: [],
+ inUseCount: 0,
+ onlyImages: true,
+ scope: 'items',
+ serverCheck: 'complete',
+ ...overrides,
+});
const mixedRefs: GalleryItemRef[] = [
{ kind: 'image', name: 'image.png' },
{ kind: 'video', name: 'video.mp4' },
@@ -155,36 +192,84 @@ describe('useDeletionConfirmation', () => {
expect(getWorkbenchPreferences().confirmImageDeletion).toBe(true);
});
- it('lists where the project still uses the items, with the count each surface loses', async () => {
+ it('opens at once while it checks where the items are used, then lists each place grouped by owner', async () => {
const executeDeletion = vi.fn(async () => {});
const consoleError = vi.spyOn(console, 'error');
+ let settleCheck: (report: GalleryMediaUsageReport) => void = () => {};
+ const checkUsage = vi.fn(
+ () =>
+ new Promise<GalleryMediaUsageReport>((resolve) => {
+ settleCheck = resolve;
+ })
+ );
await act(() => {
void confirmationRef.current!.requestDeletionConfirmation(mixedRefs, executeDeletion, {
canSkipFutureConfirmations: true,
- usage: [
- { names: ['image.png'], surface: 'canvasRaster' },
- { label: 'Upscale pass', names: ['image.png', 'video.mp4'], surface: 'workflow' },
- // Workflow names are not unique.
- { label: 'Upscale pass', names: ['video.mp4'], surface: 'workflow' },
- ],
+ checkUsage,
});
});
+ expect(openDialog()?.textContent).toContain('Checking where this media is used…');
+ // Deleting anyway does not wait for the check.
+ expect(buttonNamed('Delete')?.disabled).toBe(false);
+
+ await act(() =>
+ settleCheck(
+ usageReport({
+ checkedCount: 2,
+ groups: [
+ {
+ count: 2,
+ kind: 'openProject',
+ surfaces: [
+ { count: 1, surface: 'canvasRaster' },
+ { count: 2, label: 'Upscale pass', surface: 'workflow' },
+ // Workflow names are not unique.
+ { count: 1, label: 'Upscale pass', surface: 'workflow' },
+ ],
+ },
+ { count: 1, kind: 'projectUnchecked', name: 'Harbor Tower' },
+ // Open in this tab, its saved version unread: what it uses here, and a note.
+ { count: 1, kind: 'project', name: 'Atlas', savedCopyUnchecked: true, surfaces: [] },
+ { count: 1, kind: 'workflow', name: 'Portraits' },
+ { count: 1, jobCount: 2, kind: 'queue' },
+ ],
+ inUseCount: 2,
+ onlyImages: false,
+ })
+ )
+ );
+
+ // The section loads with the first check a dialog shows.
+ await vi.waitFor(() => expect(openDialog()?.querySelector('[role="group"]')).not.toBeNull(), REPORT_WAIT);
const dialog = openDialog();
const group = dialog?.querySelector('[role="group"]');
- expect(group?.getAttribute('aria-labelledby')).toBeTruthy();
expect(dialog?.querySelector(`#${group?.getAttribute('aria-labelledby')}`)?.textContent).toBe(
- 'Still used in this project:'
+ 'All 2 items are still in use:'
+ );
+ const rows = Array.from(group?.querySelectorAll('li') ?? []).map((row) =>
+ Array.from(row.querySelectorAll(':scope > div > p'))
+ .map((cell) => cell.textContent)
+ .join(' · ')
);
- const rows = Array.from(group?.querySelectorAll('li') ?? []).map((row) => row.textContent);
expect(rows).toEqual([
- 'Canvas raster layers · 1 selected item',
- 'Workflow “Upscale pass” · 2 selected items',
- 'Workflow “Upscale pass” · 1 selected item',
+ 'This project · 2 items',
+ 'Canvas raster layers · 1 item',
+ 'Workflow “Upscale pass” · 2 items',
+ 'Workflow “Upscale pass” · 1 item',
+ 'Project “Harbor Tower” · 1 item',
+ 'Project “Atlas” · 1 item',
+ 'Library workflow “Portraits” · 1 item',
+ '2 queued or running jobs · 1 item',
]);
+ expect(dialog?.textContent).toContain('Couldn’t open it to see where.');
+ expect(dialog?.textContent).toContain('Its saved version couldn’t be checked.');
+ expect(dialog?.textContent).toContain(
+ // Two items in use: the warnings speak of them, not it.
+ 'Work that uses them will point at missing media. Jobs that use them will fail.'
+ );
expect(consoleError).not.toHaveBeenCalledWith(expect.stringContaining('same key'), expect.anything());
- expect(dialog?.textContent).toContain('The affected work keeps pointing at media that will no longer exist.');
// With routine confirmations on, the opt-out still means something for later deletions.
expect(skipCheckbox()).not.toBeNull();
@@ -193,6 +278,285 @@ describe('useDeletionConfirmation', () => {
consoleError.mockRestore();
});
+ it('warns when the check failed, offers Retry, and still offers the deletion', async () => {
+ let settleRetry: (report: GalleryMediaUsageReport) => void = () => {};
+ const checkUsage = vi
+ .fn<(signal: AbortSignal) => Promise<GalleryMediaUsageReport>>()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ settleRetry = resolve;
+ })
+ );
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ { checkUsage }
+ );
+ });
+ await vi.waitFor(
+ () => expect(openDialog()?.textContent).toContain('Couldn’t check where this media is used.'),
+ REPORT_WAIT
+ );
+ expect(buttonNamed('Delete')?.disabled).toBe(false);
+
+ // From the keyboard: Retry holds focus as Enter runs it. The dialog first settles its own opening focus on Cancel,
+ // which would otherwise take focus back from Retry and receive the Enter.
+ await vi.waitFor(() => expect(document.activeElement).toBe(buttonNamed('Cancel')));
+ buttonNamed('Retry')!.focus();
+ expect(document.activeElement).toBe(buttonNamed('Retry'));
+ await act(() => userEvent.keyboard('{Enter}'));
+
+ // Retry gives way to the checking state; focus stays in the dialog, on the panel that reads the outcome, and shows
+ // the ring keyboard focus does.
+ const panel = openDialog()?.querySelector<HTMLElement>('[aria-live="polite"]');
+ expect(openDialog()?.textContent).toContain('Checking where this media is used…');
+ expect(document.activeElement).toBe(panel);
+ expect(panel?.matches(':focus-visible')).toBe(true);
+ expect(getComputedStyle(panel!).outlineStyle).not.toBe('none');
+
+ await act(() => settleRetry(usageReport({ inUseCount: 0 })));
+
+ await vi.waitFor(() => expect(openDialog()?.textContent).toContain('Nothing uses this media.'), REPORT_WAIT);
+ expect(document.activeElement).toBe(panel);
+ expect(openDialog()?.contains(document.activeElement)).toBe(true);
+ expect(checkUsage).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps what it already knows on screen while a retry runs, checking where the warning and Retry were', async () => {
+ let settleRetry: (report: GalleryMediaUsageReport) => void = () => {};
+ const known = usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ serverCheck: 'unavailable',
+ });
+ const checkUsage = vi.fn<(signal: AbortSignal) => Promise<GalleryMediaUsageReport>>().mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ settleRetry = resolve;
+ })
+ );
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ {
+ checkUsage,
+ usage: known,
+ }
+ );
+ });
+ await vi.waitFor(
+ () => expect(openDialog()?.textContent).toContain('Other projects couldn’t be checked.'),
+ REPORT_WAIT
+ );
+
+ await act(() => userEvent.click(buttonNamed('Retry')!));
+
+ const panel = openDialog()?.querySelector<HTMLElement>('[aria-live="polite"]');
+ expect(panel?.getAttribute('aria-busy')).toBe('true');
+ expect(panel?.textContent).toContain('This project');
+ expect(panel?.textContent).toContain('Checking where this media is used…');
+ expect(panel?.textContent).not.toContain('Other projects couldn’t be checked.');
+ expect(buttonNamed('Retry')).toBeNull();
+ expect(document.activeElement).toBe(panel);
+
+ await act(() => settleRetry({ ...known, serverCheck: 'complete' }));
+
+ await vi.waitFor(() => expect(panel?.textContent).not.toContain('Checking'), REPORT_WAIT);
+ expect(panel?.textContent).toContain('This project');
+ expect(panel?.getAttribute('aria-busy')).toBe('false');
+ expect(document.activeElement).toBe(panel);
+ });
+
+ it('keeps the earlier answer, not the checking state, when deleted anyway during a retry', async () => {
+ let resolveDeletion!: () => void;
+ const executeDeletion = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDeletion = resolve;
+ })
+ );
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, executeDeletion, {
+ checkUsage: () => new Promise(() => {}),
+ usage: usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ serverCheck: 'unavailable',
+ }),
+ });
+ });
+ await vi.waitFor(() => expect(buttonNamed('Retry')).not.toBeNull(), REPORT_WAIT);
+ await act(() => userEvent.click(buttonNamed('Retry')!));
+ expect(openDialog()?.textContent).toContain('Checking where this media is used…');
+
+ await clickButton('Delete');
+
+ // The deletion runs, the dialog with it: the answer the retry was replacing is back, with no spinner, and its Retry
+ // stays in place but cannot run.
+ expect(executeDeletion).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(openDialog()?.textContent).toContain('Other projects couldn’t be checked.'));
+ expect(openDialog()?.textContent).toContain('This project');
+ expect(openDialog()?.textContent).not.toContain('Checking where this media is used…');
+ expect(buttonNamed('Retry')?.disabled).toBe(true);
+
+ await act(async () => {
+ resolveDeletion();
+ await request;
+ });
+ });
+
+ it('shows a known report at once, without a checking state, and says what went unchecked', async () => {
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ {
+ checkUsage: () => new Promise(() => {}),
+ usage: usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ serverCheck: 'unavailable',
+ }),
+ }
+ );
+ });
+
+ expect(openDialog()?.textContent).not.toContain('Checking');
+ await vi.waitFor(() => expect(openDialog()?.textContent).toContain('Still in use:'), REPORT_WAIT);
+ expect(openDialog()?.textContent).toContain('Other projects couldn’t be checked.');
+ // Deleting one item, every row would say "1 item": the rows name places only.
+ expect(Array.from(openDialog()?.querySelectorAll('[role="group"] li') ?? []).map((row) => row.textContent)).toEqual(
+ ['This projectCanvas raster layers', 'Canvas raster layers']
+ );
+ });
+
+ it('announces the outcome in a region present from the moment the dialog opens, beside its description', async () => {
+ let settle: (report: GalleryMediaUsageReport) => void = () => {};
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ {
+ checkUsage: () =>
+ new Promise((resolve) => {
+ settle = resolve;
+ }),
+ }
+ );
+ });
+
+ const region = openDialog()?.querySelector('[aria-live="polite"]');
+ expect(region?.getAttribute('aria-busy')).toBe('true');
+ expect(region?.textContent).toBe('Checking where this media is used…');
+ const describedBy = openDialog()?.getAttribute('aria-describedby');
+ expect(describedBy && document.getElementById(describedBy)?.textContent).toBe('Permanently delete the image.');
+
+ await act(() => settle(usageReport({ inUseCount: 0 })));
+
+ // The same element, so assistive technology reads the change in it.
+ await vi.waitFor(() => expect(region?.textContent).toBe('Nothing uses this media.'), REPORT_WAIT);
+ expect(region?.isConnected).toBe(true);
+ expect(region?.getAttribute('aria-busy')).toBe('false');
+ });
+
+ it("keeps an earlier request's late answer out of a later dialog", async () => {
+ const settles: Array<(report: GalleryMediaUsageReport) => void> = [];
+ const checkUsage = () =>
+ new Promise<GalleryMediaUsageReport>((resolve) => {
+ settles.push(resolve);
+ });
+ const inUse = usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ });
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ { checkUsage }
+ );
+ });
+ await clickButton('Cancel');
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ { checkUsage }
+ );
+ });
+
+ await act(() => settles[0]?.(inUse));
+ expect(openDialog()?.textContent).toContain('Checking where this media is used…');
+ expect(openDialog()?.textContent).not.toContain('still in use');
+
+ await act(() => settles[1]?.(usageReport({ inUseCount: 0 })));
+ await vi.waitFor(() => expect(openDialog()?.textContent).toContain('Nothing uses this media.'), REPORT_WAIT);
+ });
+
+ it('deletes at once when confirmed while the check runs, and stops the check', async () => {
+ let resolveDeletion!: () => void;
+ const executeDeletion = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDeletion = resolve;
+ })
+ );
+ const captured: { signal?: AbortSignal } = {};
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, executeDeletion, {
+ checkUsage: (signal) => {
+ captured.signal = signal;
+ return new Promise(() => {});
+ },
+ });
+ });
+ expect(openDialog()?.textContent).toContain('Checking where this media is used…');
+ await clickButton('Delete');
+
+ expect(executeDeletion).toHaveBeenCalledOnce();
+ expect(captured.signal?.aborted).toBe(true);
+ // The deletion is still running, the dialog with it; the stopped check no longer says it is checking.
+ expect(openDialog()).not.toBeNull();
+ expect(openDialog()?.textContent).not.toContain('Checking where this media is used…');
+
+ await act(async () => {
+ resolveDeletion();
+ await request;
+ });
+ });
+
+ it('stops the check when the dialog is cancelled', async () => {
+ const captured: { signal?: AbortSignal } = {};
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ imageRefs,
+ vi.fn(async () => {}),
+ {
+ checkUsage: (signal) => {
+ captured.signal = signal;
+ return new Promise(() => {});
+ },
+ }
+ );
+ });
+ await clickButton('Cancel');
+
+ expect(captured.signal?.aborted).toBe(true);
+ });
+
it('offers no opt-out when routine confirmations are already off and the media is in use', async () => {
await patchWorkbenchPreferences({ confirmImageDeletion: false });
@@ -200,11 +564,17 @@ describe('useDeletionConfirmation', () => {
void confirmationRef.current!.requestDeletionConfirmation(
imageRefs,
vi.fn(async () => {}),
- { canSkipFutureConfirmations: true, usage: [{ names: ['image.png'], surface: 'canvasRaster' }] }
+ {
+ canSkipFutureConfirmations: true,
+ usage: usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] }],
+ inUseCount: 1,
+ }),
+ }
);
});
- expect(openDialog()?.textContent).toContain('Still used in this project:');
+ await vi.waitFor(() => expect(openDialog()?.textContent).toContain('Still in use:'), REPORT_WAIT);
expect(skipCheckbox()).toBeNull();
expect(openDialog()?.textContent).not.toContain('You can turn this confirmation back on in Settings.');
});
@@ -245,7 +615,7 @@ describe('useDeletionConfirmation', () => {
expect(targets?.lastElementChild?.textContent).toBe('+3');
});
- it('shows no usage section for a deletion nothing depends on', async () => {
+ it('shows no usage section when the request asks for no check', async () => {
await act(() => {
void confirmationRef.current!.requestDeletionConfirmation(
imageRefs,
@@ -292,20 +662,67 @@ describe('useDeletionConfirmation', () => {
expect(document.querySelector('[role="alertdialog"][data-state="open"]')).toBeNull();
});
- it('ignores a second request while confirmation is pending', async () => {
+ it('refuses a second request while confirmation is pending, and says it did not delete', async () => {
+ const createToast = vi.spyOn(toaster, 'create');
const firstDeletion = vi.fn(async () => {});
const secondDeletion = vi.fn(async () => {});
- await act(() => {
- void confirmationRef.current!.requestDeletionConfirmation(imageRefs, firstDeletion);
- void confirmationRef.current!.requestDeletionConfirmation(mixedRefs, secondDeletion);
- });
+ try {
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(imageRefs, firstDeletion);
+ // With routine confirmations off, a second item whose check found it in use arrives on its own, much later.
+ void confirmationRef.current!.requestDeletionConfirmation(mixedRefs, secondDeletion);
+ });
- expect(document.querySelector('[role="alertdialog"][data-state="open"]')?.textContent).toContain('Delete image?');
- await clickButton('Delete');
+ expect(createToast).toHaveBeenCalledExactlyOnceWith({
+ title: '1 image and 1 video not deleted: answer the open deletion first.',
+ type: 'warning',
+ });
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')?.textContent).toContain('Delete image?');
+ await clickButton('Delete');
+
+ expect(firstDeletion).toHaveBeenCalledOnce();
+ expect(secondDeletion).not.toHaveBeenCalled();
+ } finally {
+ createToast.mockRestore();
+ }
+ });
+
+ it('says a second request waits for a confirmed deletion still running, not for an answer', async () => {
+ const createToast = vi.spyOn(toaster, 'create');
+ let resolveDeletion!: () => void;
+ const firstDeletion = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDeletion = resolve;
+ })
+ );
+ let request!: Promise<void>;
- expect(firstDeletion).toHaveBeenCalledOnce();
- expect(secondDeletion).not.toHaveBeenCalled();
+ try {
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, firstDeletion);
+ });
+ await clickButton('Delete');
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(
+ mixedRefs,
+ vi.fn(async () => {})
+ );
+ });
+
+ expect(createToast).toHaveBeenCalledExactlyOnceWith({
+ title: '1 image and 1 video not deleted: wait for the deletion under way.',
+ type: 'warning',
+ });
+
+ await act(async () => {
+ resolveDeletion();
+ await request;
+ });
+ } finally {
+ createToast.mockRestore();
+ }
});
it('settles a pending request safely when the host unmounts', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx
index 34726172a7..6a361a41a3 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx
@@ -1,17 +1,19 @@
import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryMediaUsageCheck, GalleryMediaUsageReport } from '@features/gallery/mediaUsage';
import type { ReactNode } from 'react';
-import { Box, Checkbox, Flex, Image, List, Stack, Text } from '@chakra-ui/react';
+import { Box, Checkbox, Flex, Image, Stack, Text } from '@chakra-ui/react';
import { formatGalleryMediaCounts, toGalleryItemKey } from '@features/gallery/contracts';
+import { GalleryMediaUsagePanel } from '@features/gallery/react';
import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { Dialog } from '@platform/ui/Dialog';
+import { toaster } from '@platform/ui/toaster';
import { patchWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useCallback, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { MediaUsage } from './mediaUsage';
-
export interface DeletionConfirmationOptions {
/**
* The request may offer "Don't ask me again": only for one item the user can see. A batch, or an item off screen,
@@ -20,8 +22,13 @@ export interface DeletionConfirmationOptions {
canSkipFutureConfirmations?: boolean;
/** Where focus goes when the dialog closes; without it, back to the control that opened it. */
returnFocus?: () => HTMLElement | null;
- /** Project surfaces that still use some of the items; listed so the user sees what the deletion breaks. */
- usage?: readonly MediaUsage[];
+ /**
+ * Where the items are still used, checked as the dialog opens: it shows the check running, then its report, so the
+ * user sees what the deletion breaks. Aborted when the dialog closes. The dialog's Retry runs it again.
+ */
+ checkUsage?: (signal: AbortSignal) => Promise<GalleryMediaUsageReport>;
+ /** A report the caller already has, shown at once instead of first running `checkUsage`. */
+ usage?: GalleryMediaUsageReport;
}
export type RequestDeletionConfirmation = (
@@ -32,17 +39,30 @@ export type RequestDeletionConfirmation = (
interface PendingDeletion {
canSkipFutureConfirmations: boolean;
+ checkUsage?: (signal: AbortSignal) => Promise<GalleryMediaUsageReport>;
executeDeletion: () => Promise<void>;
itemRefs: readonly GalleryItemRef[];
resolve: () => void;
- usage: readonly MediaUsage[];
+ /** Stops the running usage check: replaced by a retry, aborted once the request settles. */
+ usageCheckController: AbortController;
+}
+
+/** The usage check of one request: a later request's check never shows in an earlier one's dialog, or the reverse. */
+interface PendingUsageCheck {
+ check: GalleryMediaUsageCheck;
+ pending: PendingDeletion;
}
-const NO_USAGE: readonly MediaUsage[] = [];
const NO_ITEMS: readonly GalleryItemRef[] = [];
/** Tiles in the dialog's one row of thumbnails: all of a small deletion, else one fewer and a count of the rest. */
export const DELETION_PREVIEW_SLOTS = 8;
+const countMedia = (t: Parameters<typeof formatGalleryMediaCounts>[0], itemRefs: readonly GalleryItemRef[]): string =>
+ formatGalleryMediaCounts(t, {
+ images: itemRefs.filter((ref) => ref.kind === 'image').length,
+ videos: itemRefs.filter((ref) => ref.kind === 'video').length,
+ });
+
const getThumbnailUrl = (ref: GalleryItemRef): string =>
ref.kind === 'video' ? galleryVideoUrls.thumbnail(ref.name) : galleryImageUrls.thumbnail(ref.name);
@@ -102,17 +122,53 @@ export const useDeletionConfirmation = (): {
} => {
const { t } = useTranslation();
const [pendingDeletion, setPendingDeletion] = useState<PendingDeletion | null>(null);
+ const [usageCheck, setUsageCheck] = useState<PendingUsageCheck | null>(null);
// Kept past the request: the dialog closes after the pending deletion clears, and resolves focus as it does.
const [returnFocus, setReturnFocus] = useState<(() => HTMLElement | null) | null>(null);
const pendingDeletionRef = useRef<PendingDeletion | null>(null);
const deletionInFlightRef = useRef(false);
+ // The same, for rendering: Retry stays in place but disabled while the confirmed deletion runs.
+ const [isDeleting, setIsDeleting] = useState(false);
// Read only when deletion is confirmed, so ticking it and then cancelling changes nothing.
const [skipFutureConfirmations, setSkipFutureConfirmations] = useState(false);
// With routine confirmations already off, the dialog only appears because the media is in use or the request
// cannot skip it, which the opt-out does not cover.
const confirmsRoutineDeletions = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);
const skipHintId = useId();
- const usageHeadingId = useId();
+
+ /** Runs the request's check; its answer lands only in that request's dialog, and only from its latest run. */
+ const runUsageCheck = useCallback((pending: PendingDeletion) => {
+ const { checkUsage } = pending;
+
+ if (!checkUsage) {
+ return;
+ }
+
+ const controller = new AbortController();
+ const settleCheck = (check: GalleryMediaUsageCheck) => {
+ if (!controller.signal.aborted) {
+ setUsageCheck((current) => (current?.pending === pending ? { check, pending } : current));
+ }
+ };
+
+ pending.usageCheckController.abort();
+ pending.usageCheckController = controller;
+ // A retry keeps this request's last answer on screen while it runs; a first check has none.
+ setUsageCheck((current) => {
+ const previous =
+ current?.pending !== pending
+ ? undefined
+ : current.check.status === 'checking'
+ ? current.check.previous
+ : current.check;
+
+ return { check: previous ? { previous, status: 'checking' } : { status: 'checking' }, pending };
+ });
+ checkUsage(controller.signal).then(
+ (report) => settleCheck({ report, status: 'ready' }),
+ () => settleCheck({ status: 'failed' })
+ );
+ }, []);
const settlePendingDeletion = useCallback(() => {
const pending = pendingDeletionRef.current;
@@ -123,34 +179,72 @@ export const useDeletionConfirmation = (): {
pendingDeletionRef.current = null;
deletionInFlightRef.current = false;
+ setIsDeleting(false);
+ pending.usageCheckController.abort();
setPendingDeletion(null);
pending.resolve();
}, []);
const requestDeletionConfirmation = useCallback<RequestDeletionConfirmation>(
- (itemRefs, executeDeletion, { canSkipFutureConfirmations = false, returnFocus: getReturnFocus, usage } = {}) => {
+ (
+ itemRefs,
+ executeDeletion,
+ { canSkipFutureConfirmations = false, checkUsage, returnFocus: getReturnFocus, usage } = {}
+ ) => {
if (pendingDeletionRef.current) {
+ // One dialog at a time. A second request is refused, and says so: with routine confirmations off it comes from
+ // a check that found its media in use while another dialog waited, or while a confirmed deletion still runs,
+ // long after the press, and would otherwise vanish without a word.
+ toaster.create({
+ title: t(
+ deletionInFlightRef.current
+ ? 'widgets.gallery.deleteBlockedByRunning'
+ : 'widgets.gallery.deleteBlockedByPending',
+ {
+ count: itemRefs.length,
+ media: countMedia(t, itemRefs),
+ }
+ ),
+ type: 'warning',
+ });
return Promise.resolve();
}
return new Promise<void>((resolve) => {
- const pending = {
+ const pending: PendingDeletion = {
canSkipFutureConfirmations,
+ checkUsage,
executeDeletion,
itemRefs: [...itemRefs],
resolve,
- usage: usage ?? NO_USAGE,
+ usageCheckController: new AbortController(),
};
pendingDeletionRef.current = pending;
setSkipFutureConfirmations(false);
setPendingDeletion(pending);
setReturnFocus(() => getReturnFocus ?? null);
+
+ if (usage) {
+ setUsageCheck({ check: { report: usage, status: 'ready' }, pending });
+ } else if (checkUsage) {
+ runUsageCheck(pending);
+ } else {
+ setUsageCheck(null);
+ }
});
},
- []
+ [runUsageCheck, t]
);
+ const handleRetryUsageCheck = useCallback(() => {
+ const pending = pendingDeletionRef.current;
+
+ if (pending && !deletionInFlightRef.current) {
+ runUsageCheck(pending);
+ }
+ }, [runUsageCheck]);
+
const handleConfirm = useCallback(async () => {
const pending = pendingDeletionRef.current;
@@ -159,17 +253,30 @@ export const useDeletionConfirmation = (): {
}
deletionInFlightRef.current = true;
+ setIsDeleting(true);
if (skipFutureConfirmations && pending.canSkipFutureConfirmations) {
void patchWorkbenchPreferences({ confirmImageDeletion: false });
}
+ // Deleting anyway while the check runs: its answer no longer matters, and the panel stops saying it is checking.
+ // A retry's earlier answer stays; a first check leaves nothing to show.
+ pending.usageCheckController.abort();
+ setUsageCheck((current) =>
+ current?.pending !== pending || current.check.status !== 'checking'
+ ? current
+ : current.check.previous
+ ? { check: current.check.previous, pending }
+ : null
+ );
+
try {
await pending.executeDeletion();
} finally {
if (pendingDeletionRef.current === pending) {
pendingDeletionRef.current = null;
deletionInFlightRef.current = false;
+ setIsDeleting(false);
setPendingDeletion(null);
pending.resolve();
}
@@ -186,12 +293,11 @@ export const useDeletionConfirmation = (): {
const isImageOnly = pendingDeletion?.itemRefs.every((item) => item.kind === 'image') ?? false;
const titleKey = isImageOnly ? 'widgets.gallery.deleteImagesConfirmTitle' : 'widgets.gallery.deleteItemsConfirmTitle';
const bodyKey = isImageOnly ? 'widgets.gallery.deleteImagesConfirmBody' : 'widgets.gallery.deleteItemsConfirmBody';
- const usage = pendingDeletion?.usage ?? NO_USAGE;
+ // Kept past the request like the rest of the body, so the closing dialog does not drop its report mid-animation.
+ const shownUsageCheck = usageCheck?.check ?? null;
+ const canRetryUsageCheck = usageCheck !== null && usageCheck.pending.checkUsage !== undefined;
const itemRefs = pendingDeletion?.itemRefs ?? NO_ITEMS;
- const countSummary = formatGalleryMediaCounts(t, {
- images: itemRefs.filter((ref) => ref.kind === 'image').length,
- videos: itemRefs.filter((ref) => ref.kind === 'video').length,
- });
+ const countSummary = countMedia(t, itemRefs);
const canSkipFutureConfirmations = confirmsRoutineDeletions && pendingDeletion?.canSkipFutureConfirmations === true;
return {
@@ -199,34 +305,22 @@ export const useDeletionConfirmation = (): {
<ConfirmDialog
body={
<>
- <Text fontSize="md">{t(bodyKey, { count: itemCount })}</Text>
+ <Dialog.Description color="fg" fontSize="md" lineHeight="inherit">
+ {t(bodyKey, { count: itemCount })}
+ </Dialog.Description>
<Stack gap="1.5">
<Text fontSize="md" fontWeight="semibold">
{t('widgets.gallery.deleteTargetsSummary', { media: countSummary })}
</Text>
<DeletionTargets itemRefs={itemRefs} />
</Stack>
- {usage.length > 0 ? (
- <Stack aria-labelledby={usageHeadingId} as="section" gap="1" role="group">
- <Text fontWeight="semibold" id={usageHeadingId}>
- {t('widgets.gallery.deleteInUse.heading')}
- </Text>
- <List.Root gap="0.5" ps="4">
- {usage.map((entry, index) => (
- // Captured when the dialog opens and never reordered; labels such as workflow names can repeat.
- <List.Item key={index}>
- {t(`widgets.gallery.deleteInUse.surface.${entry.surface}`, { name: entry.label })}
- <Text as="span" color="fg.muted">
- {' · '}
- {t('widgets.gallery.deleteInUse.usedCount', { count: entry.names.length })}
- </Text>
- </List.Item>
- ))}
- </List.Root>
- <Text color="fg.muted" fontSize="sm">
- {t('widgets.gallery.deleteInUse.warning')}
- </Text>
- </Stack>
+ {shownUsageCheck ? (
+ <GalleryMediaUsagePanel
+ check={shownUsageCheck}
+ // Also while the dialog closes: the request it would inform is settled.
+ isRetryDisabled={isDeleting || pendingDeletion === null}
+ onRetry={canRetryUsageCheck ? handleRetryUsageCheck : undefined}
+ />
) : null}
{canSkipFutureConfirmations ? (
<Stack gap="1" pt="1">
@@ -247,6 +341,8 @@ export const useDeletionConfirmation = (): {
confirmLabel={t('widgets.gallery.deleteConfirmLabel')}
finalFocusEl={returnFocus ?? undefined}
isOpen={pendingDeletion !== null}
+ // The usage report arrives after the dialog opens; anchored at the top, it grows the dialog downward.
+ placement="top"
title={t(titleKey, { count: itemCount })}
onClose={settlePendingDeletion}
onConfirm={handleConfirm}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index bae2bfba59..ec4e0ef167 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -1,8 +1,11 @@
import type { GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
+import type * as GalleryMediaUsageModule from '@features/gallery/mediaUsage';
+import type { GalleryMediaUsageReport } from '@features/gallery/mediaUsage';
import type * as QueueUtilityModule from '@features/queue/utility';
import type { InvocationTemplatesSnapshot } from '@features/workflow/contracts';
import type * as WorkflowReact from '@features/workflow/react';
import type { CreateCanvasFromImagesResult } from '@workbench/canvas-operations/api';
+import type * as SettingsStoreModule from '@workbench/settings/store';
import {
resetArchitectureCapabilities,
@@ -16,11 +19,13 @@ import { parseOpenApiToTemplates } from '@features/workflow/react';
import { clearLogs, getLogSnapshot } from '@platform/logging/logger';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { toaster } from '@platform/ui/toaster';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, createRef, type Ref, useImperativeHandle } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+import type * as MediaUsageReportModule from './mediaUsageReport';
import type { ImageActions } from './useImageActions';
import { EMPTY_IMAGE_RECALL_CAPABILITIES } from './imageRecall';
@@ -85,6 +90,8 @@ const mocks = vi.hoisted(() => ({
sendGalleryImageAsControl: vi.fn(),
requestDeletionConfirmation: vi.fn(),
resolveItem: vi.fn(),
+ resolveMediaUsage: vi.fn<(...args: unknown[]) => Promise<GalleryMediaUsageReport>>(),
+ checkGalleryMediaUsage: vi.fn(),
setStarred: vi.fn(),
}));
const preferences = vi.hoisted(() => ({ confirmImageDeletion: false }));
@@ -175,6 +182,18 @@ vi.mock('@features/models', () => ({
}),
}));
+// The resolver's own behaviour is covered beside it; here mostly what deletion does with its answer. One test runs the
+// real resolver over this tab's projects, with the server's answer doubled. The last look at this tab's projects before
+// a silent deletion runs for real.
+vi.mock('./mediaUsageReport', async (importOriginal) => ({
+ ...(await importOriginal<typeof MediaUsageReportModule>()),
+ resolveMediaUsage: (...args: unknown[]) => mocks.resolveMediaUsage(...args),
+}));
+vi.mock('@features/gallery/mediaUsage', async (importOriginal) => ({
+ ...(await importOriginal<typeof GalleryMediaUsageModule>()),
+ checkGalleryMediaUsage: (...args: unknown[]) => mocks.checkGalleryMediaUsage(...args),
+}));
+
vi.mock('@workbench/useNotify', () => ({
useNotify: () => ({ undoable: (...args: unknown[]) => mocks.notifyUndoable(...args) }),
}));
@@ -183,7 +202,8 @@ vi.mock('@workbench/useOpenWorkbenchWidget', () => ({
useOpenWorkbenchWidget: () => mocks.openWorkbenchWidget,
}));
-vi.mock('@workbench/settings/store', () => ({
+vi.mock('@workbench/settings/store', async (importOriginal) => ({
+ ...(await importOriginal<typeof SettingsStoreModule>()),
useWorkbenchPreferenceSelector: (selector: (value: typeof preferences) => boolean) => selector(preferences),
}));
@@ -286,8 +306,13 @@ const makeMockProject = (
galleryValues: Record<string, unknown> = {},
upscaleValues: Record<string, unknown> = {}
) => ({
- canvas: { document: { stacks: { control: [], inpaint_mask: [], raster: [], regional_guidance: [] } } },
+ canvas: {
+ document: { stacks: { control: [], inpaint_mask: [], raster: [], regional_guidance: [] } },
+ snapshots: [],
+ stagingArea: { pendingImages: [] },
+ },
id,
+ name: id,
workflows: { activeWorkflowId: 'wf', entries: [] },
widgetInstances: {
gallery: {
@@ -305,6 +330,31 @@ const makeMockProject = (
},
});
+/**
+ * Serves `initial` as the store until the optimistic removal applies, then `removed`: each read sees the state of its
+ * moment, however many reads there are. `set` moves the store on, as a concurrent change would.
+ */
+const serveProjectStates = (
+ initial: ReturnType<typeof makeMockProject>,
+ removed: ReturnType<typeof makeMockProject>
+) => {
+ let current = initial;
+
+ mocks.getSnapshot.mockImplementation(() => ({ activeProject: current, projects: [current] }));
+ mocks.galleryRemoveItems.mockImplementation(() => {
+ current = removed;
+ });
+ onTestFinished(() => {
+ mocks.galleryRemoveItems.mockReset();
+ });
+
+ return {
+ set: (project: ReturnType<typeof makeMockProject>) => {
+ current = project;
+ },
+ };
+};
+
const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<ImageActions> }) => {
const actions = useImageActions({
boards: [
@@ -333,9 +383,20 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<I
return null;
};
+const usageReport = (overrides: Partial<GalleryMediaUsageReport> = {}): GalleryMediaUsageReport => ({
+ checkedCount: 1,
+ groups: [],
+ inUseCount: 0,
+ onlyImages: true,
+ scope: 'items',
+ serverCheck: 'complete',
+ ...overrides,
+});
+
beforeEach(() => {
vi.clearAllMocks();
preferences.confirmImageDeletion = false;
+ mocks.resolveMediaUsage.mockResolvedValue(usageReport());
mocks.requestDeletionConfirmation.mockImplementation(
(_itemRefs: readonly GalleryItemRef[], executeDeletion: () => Promise<void>) => executeDeletion()
);
@@ -1265,13 +1326,15 @@ type ExpectedItemActions = {
const getItemActions = (): ExpectedItemActions => actionsRef.current as unknown as ExpectedItemActions;
describe('mixed item mutation outcomes', () => {
- it('gates deletion through confirmation when the preference is enabled', async () => {
+ it('gates deletion through confirmation when the preference is enabled, checking usage as the dialog opens', async () => {
const refs = [{ kind: 'image' as const, name: 'image.png' }];
const result = { affectedBoardIds: ['none'], failed: [], succeeded: refs };
let executeDeletion: (() => Promise<void>) | null = null;
+ const captured: { checkUsage?: (signal: AbortSignal) => Promise<GalleryMediaUsageReport> } = {};
preferences.confirmImageDeletion = true;
- mocks.requestDeletionConfirmation.mockImplementation((_itemRefs, execute) => {
+ mocks.requestDeletionConfirmation.mockImplementation((_itemRefs, execute, options) => {
executeDeletion = execute;
+ captured.checkUsage = options.checkUsage;
return Promise.resolve();
});
mocks.itemDelete.mockResolvedValue(result);
@@ -1291,9 +1354,12 @@ describe('mixed item mutation outcomes', () => {
// The dialog learns where focus goes once the deletion has removed the control that asked for it.
expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(refs, expect.any(Function), {
canSkipFutureConfirmations: true,
+ checkUsage: expect.any(Function),
returnFocus,
- usage: [],
});
+ // The dialog, not the caller, runs the check: it opens without waiting for one.
+ expect(mocks.resolveMediaUsage).not.toHaveBeenCalled();
+ expect(captured.checkUsage).toBeDefined();
expect(mocks.itemDelete).not.toHaveBeenCalled();
await act(async () => {
@@ -1302,7 +1368,7 @@ describe('mixed item mutation outcomes', () => {
expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
});
- it('deletes immediately without opening confirmation when the preference is disabled', async () => {
+ it('deletes one visible item without asking once the check finds nothing using it', async () => {
const refs = [{ kind: 'image' as const, name: 'image.png' }];
mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
@@ -1310,65 +1376,276 @@ describe('mixed item mutation outcomes', () => {
await getItemActions().deleteItems(refs);
});
+ // A click is waiting: the check gets a few seconds per stage, not the dialog's longer allowance.
+ expect(mocks.resolveMediaUsage).toHaveBeenCalledWith({ kind: 'items', refs }, expect.anything(), {
+ projectReadsTimeoutMs: 3000,
+ serverTimeoutMs: 3000,
+ });
expect(mocks.requestDeletionConfirmation).not.toHaveBeenCalled();
expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
});
it.each([
[
- 'more than one item',
- [
- { kind: 'image' as const, name: 'a.png' },
- { kind: 'video' as const, name: 'b.mp4' },
- ],
- false,
+ 'something uses it',
+ usageReport({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'upscale' }] }],
+ inUseCount: 1,
+ }),
],
- ['an item off screen', [{ kind: 'image' as const, name: 'a.png' }], true],
- ])('asks before deleting %s even with routine confirmations off', async (_case, refs, targetsOffScreen) => {
- mocks.requestDeletionConfirmation.mockImplementation(() => Promise.resolve());
+ ['the check could not reach the server', usageReport({ serverCheck: 'unavailable' })],
+ ])('still asks with routine confirmations off when %s, showing the report', async (_case, usage) => {
+ const refs = [{ kind: 'image' as const, name: 'source.png' }];
+ let executeDeletion: (() => Promise<void>) | null = null;
+ mocks.resolveMediaUsage.mockResolvedValue(usage);
+ mocks.requestDeletionConfirmation.mockImplementation((_itemRefs, execute) => {
+ executeDeletion = execute;
+ return Promise.resolve();
+ });
+ mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
await act(async () => {
- await getItemActions().deleteItems(refs, { targetsOffScreen });
+ await getItemActions().deleteItems(refs);
});
+ // The dialog shows the report it was handed and can run the check again from it.
expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(refs, expect.any(Function), {
- canSkipFutureConfirmations: false,
+ canSkipFutureConfirmations: true,
+ checkUsage: expect.any(Function),
returnFocus: undefined,
- usage: [],
+ usage,
});
expect(mocks.itemDelete).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await executeDeletion?.();
+ });
+ expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
});
- it('still confirms, naming the surfaces, when the project uses an item and confirmation is off', async () => {
- const refs = [
- { kind: 'image' as const, name: 'source.png' },
- { kind: 'image' as const, name: 'unused.png' },
- ];
- let executeDeletion: (() => Promise<void>) | null = null;
- mocks.requestDeletionConfirmation.mockImplementation((_itemRefs, execute) => {
- executeDeletion = execute;
- return Promise.resolve();
+ it('blocks the silent deletion of an item a project in this tab uses but has not saved yet', async () => {
+ const { resolveMediaUsage } = await vi.importActual<typeof MediaUsageReportModule>('./mediaUsageReport');
+ const refs = [{ kind: 'image' as const, name: 'source.png' }];
+ mocks.resolveMediaUsage.mockImplementation(resolveMediaUsage as (...args: unknown[]) => Promise<never>);
+ // The server has not seen the edit: it knows of no use.
+ mocks.checkGalleryMediaUsage.mockResolvedValue({
+ checkedImageCount: 1,
+ checkedVideoCount: 0,
+ documents: [],
+ documentsTotal: 0,
+ inUseImageCount: 0,
+ inUseVideoCount: 0,
+ otherAccounts: { documentCount: 0, imageCount: 0, queueItemCount: 0, videoCount: 0 },
+ queue: { imageCount: 0, imageNames: [], itemCount: 0, videoCount: 0, videoNames: [] },
});
- mocks.getProject.mockReturnValue(
- makeMockProject('project-1', {}, { inputImage: { height: 1, image_name: 'source.png', width: 1 } })
+ mocks.getSnapshot.mockImplementation(() => {
+ const project = makeMockProject(
+ 'project-1',
+ {},
+ { inputImage: { height: 1, image_name: 'source.png', width: 1 } }
+ );
+
+ return { activeProject: project, projects: [project] };
+ });
+ mocks.requestDeletionConfirmation.mockImplementation(() => Promise.resolve());
+
+ await act(async () => {
+ await getItemActions().deleteItems(refs);
+ });
+
+ expect(mocks.itemDelete).not.toHaveBeenCalled();
+ expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(
+ refs,
+ expect.any(Function),
+ expect.objectContaining({
+ usage: expect.objectContaining({
+ groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'upscale' }] }],
+ serverCheck: 'complete',
+ }),
+ })
);
- mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
+ });
+
+ it('asks instead when this tab starts using the item while the check runs, and has the dialog check again', async () => {
+ const refs = [{ kind: 'image' as const, name: 'source.png' }];
+ mocks.resolveMediaUsage.mockImplementation(() => {
+ // The upscale source is set to the item while the server is asked; its answer cannot know.
+ mocks.getSnapshot.mockImplementation(() => {
+ const project = makeMockProject(
+ 'project-1',
+ {},
+ { inputImage: { height: 1, image_name: 'source.png', width: 1 } }
+ );
+
+ return { activeProject: project, projects: [project] };
+ });
+ return Promise.resolve(usageReport());
+ });
+ mocks.requestDeletionConfirmation.mockImplementation(() => Promise.resolve());
await act(async () => {
await getItemActions().deleteItems(refs);
});
+ expect(mocks.itemDelete).not.toHaveBeenCalled();
+ // No report: the one in hand says nothing uses the item, so the dialog runs the check again.
expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(refs, expect.any(Function), {
- canSkipFutureConfirmations: false,
+ canSkipFutureConfirmations: true,
+ checkUsage: expect.any(Function),
returnFocus: undefined,
- usage: [{ names: ['source.png'], surface: 'upscale' }],
});
+ });
+
+ it('runs one check and one deletion for repeated presses, saying so while a slow check runs', async () => {
+ const refs = [{ kind: 'image' as const, name: 'image.png' }];
+ let settle: (report: GalleryMediaUsageReport) => void = () => {};
+ const createToast = vi.spyOn(toaster, 'create');
+ const dismissToast = vi.spyOn(toaster, 'dismiss');
+ mocks.resolveMediaUsage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settle = resolve;
+ })
+ );
+ mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
+
+ let first!: Promise<void>;
+ await act(() => {
+ first = getItemActions().deleteItems(refs);
+ // Key repeat, and the same item from another surface.
+ void getItemActions().deleteItems(refs);
+ void getItemActions().deleteItems([...refs]);
+ });
+ await vi.waitFor(() => expect(createToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'loading' })));
+
+ await act(async () => {
+ settle(usageReport());
+ await first;
+ });
+
+ expect(mocks.resolveMediaUsage).toHaveBeenCalledOnce();
+ expect(mocks.itemDelete).toHaveBeenCalledOnce();
+ expect(dismissToast).toHaveBeenCalledWith(createToast.mock.results[0]?.value);
+ expect(mocks.reportError).not.toHaveBeenCalled();
+
+ // Once settled, the item may be asked about again.
+ mocks.resolveMediaUsage.mockResolvedValue(usageReport());
+ await act(async () => {
+ await getItemActions().deleteItems(refs);
+ });
+ expect(mocks.resolveMediaUsage).toHaveBeenCalledTimes(2);
+ createToast.mockRestore();
+ dismissToast.mockRestore();
+ });
+
+ it('shows one checking notice for checks running at once, until the last one ends, a failed one included', async () => {
+ const settles: Array<(report: GalleryMediaUsageReport) => void> = [];
+ const rejects: Array<(error: Error) => void> = [];
+ const createToast = vi.spyOn(toaster, 'create');
+ const dismissToast = vi.spyOn(toaster, 'dismiss');
+ mocks.resolveMediaUsage.mockImplementation(
+ () =>
+ new Promise((resolve, reject) => {
+ settles.push(resolve);
+ rejects.push(reject);
+ })
+ );
+ let dismissedBeforeDialog = false;
+ mocks.requestDeletionConfirmation.mockImplementation(() => {
+ dismissedBeforeDialog = dismissToast.mock.calls.length > 0;
+ return Promise.resolve();
+ });
+ mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: [] });
+
+ try {
+ let first!: Promise<void>;
+ let second!: Promise<void>;
+ await act(() => {
+ first = getItemActions().deleteItems([{ kind: 'image', name: 'a.png' }]);
+ second = getItemActions().deleteItems([{ kind: 'image', name: 'b.png' }]);
+ });
+ await vi.waitFor(() => expect(createToast).toHaveBeenCalledTimes(2));
+
+ // Both checks raised the notice; it is one notice, under one id.
+ const ids = new Set(createToast.mock.calls.map(([options]) => options.id));
+ expect(ids.size).toBe(1);
+ expect(createToast.mock.calls[0]?.[0]).toMatchObject({ type: 'loading' });
+
+ await act(async () => {
+ settles[0]?.(usageReport());
+ await first;
+ });
+ // The other check still runs: its notice stays.
+ expect(dismissToast).not.toHaveBeenCalled();
+
+ // A check that fails ends too, and takes the notice with it before its dialog opens.
+ await act(async () => {
+ rejects[1]?.(new Error('Failed to fetch dynamically imported module'));
+ await second;
+ });
+ expect(dismissToast).toHaveBeenCalledExactlyOnceWith([...ids][0]);
+ expect(mocks.requestDeletionConfirmation).toHaveBeenCalledOnce();
+ expect(dismissedBeforeDialog).toBe(true);
+ } finally {
+ createToast.mockRestore();
+ dismissToast.mockRestore();
+ }
+ });
+
+ it('neither deletes nor asks when the account changes during the check', async () => {
+ mocks.resolveMediaUsage.mockImplementation(() => {
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ return Promise.reject(new Error('Account scope is no longer active.'));
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: 'image.png' }]);
+ });
+
+ expect(mocks.requestDeletionConfirmation).not.toHaveBeenCalled();
expect(mocks.itemDelete).not.toHaveBeenCalled();
+ });
+
+ it('asks, with the check failed, when the check cannot run at all (its code did not load)', async () => {
+ const failure = new Error('Failed to fetch dynamically imported module');
+ mocks.resolveMediaUsage.mockRejectedValue(failure);
+ mocks.requestDeletionConfirmation.mockImplementation(() => Promise.resolve());
await act(async () => {
- await executeDeletion?.();
+ await getItemActions().deleteItems([{ kind: 'image', name: 'image.png' }]);
});
- expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
+
+ const options = mocks.requestDeletionConfirmation.mock.calls[0]?.[2] as {
+ checkUsage: (signal: AbortSignal) => Promise<unknown>;
+ };
+ await expect(options.checkUsage(new AbortController().signal)).rejects.toBe(failure);
+ expect(mocks.itemDelete).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ 'more than one item',
+ [
+ { kind: 'image' as const, name: 'a.png' },
+ { kind: 'video' as const, name: 'b.mp4' },
+ ],
+ false,
+ ],
+ ['an item off screen', [{ kind: 'image' as const, name: 'a.png' }], true],
+ ])('asks before deleting %s even with routine confirmations off', async (_case, refs, targetsOffScreen) => {
+ mocks.requestDeletionConfirmation.mockImplementation(() => Promise.resolve());
+
+ await act(async () => {
+ await getItemActions().deleteItems(refs, { targetsOffScreen });
+ });
+
+ expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(refs, expect.any(Function), {
+ canSkipFutureConfirmations: false,
+ checkUsage: expect.any(Function),
+ returnFocus: undefined,
+ });
+ expect(mocks.itemDelete).not.toHaveBeenCalled();
});
it('uses the localized Uncategorized label in move notifications', async () => {
@@ -1716,12 +1993,8 @@ describe('total transport failure rollback', () => {
const before = makeMockProject('project-1', { recentImages: [recentImageFixture] });
const afterRemoval = makeMockProject('project-1', { recentImages: [] });
- // First call is the pre-removal capture; every call after simulates the
- // store having actually applied the optimistic removal.
- mocks.getSnapshot.mockReturnValueOnce({ activeProject: before, projects: [before] }).mockReturnValue({
- activeProject: afterRemoval,
- projects: [afterRemoval],
- });
+ // The store holds `before` until the optimistic removal applies.
+ serveProjectStates(before, afterRemoval);
mocks.itemDelete.mockRejectedValue(new Error('network down'));
mocks.invalidateGallery.mockRejectedValue(new Error('network down'));
@@ -1751,10 +2024,7 @@ describe('total transport failure rollback', () => {
selectedImageNames: [],
});
- mocks.getSnapshot.mockReturnValueOnce({ activeProject: before, projects: [before] }).mockReturnValue({
- activeProject: afterRemoval,
- projects: [afterRemoval],
- });
+ serveProjectStates(before, afterRemoval);
// A rejected request is reported as a result whose items all failed.
mocks.itemDelete.mockResolvedValue({ affectedBoardIds: [], failed: refs, succeeded: [] });
@@ -1778,11 +2048,12 @@ describe('total transport failure rollback', () => {
recentImages: [{ ...recentImageFixture, imageName: 'new-generation.png' }],
});
- mocks.getSnapshot
- .mockReturnValueOnce({ activeProject: before, projects: [before] }) // capture, pre-removal
- .mockReturnValueOnce({ activeProject: afterRemoval, projects: [afterRemoval] }) // diff, post-removal
- .mockReturnValue({ activeProject: concurrentlyChanged, projects: [concurrentlyChanged] }); // restore-time read
- mocks.itemDelete.mockRejectedValue(new Error('network down'));
+ const store = serveProjectStates(before, afterRemoval);
+ // A generation lands while the request is out.
+ mocks.itemDelete.mockImplementation(() => {
+ store.set(concurrentlyChanged);
+ return Promise.reject(new Error('network down'));
+ });
mocks.invalidateGallery.mockRejectedValue(new Error('network down'));
await act(async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 032b58d1c9..35ca14fc45 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -1,3 +1,4 @@
+import type { GalleryMediaUsageReport } from '@features/gallery/mediaUsage';
import type { GalleryItemActionContext, GalleryItemActions } from '@features/gallery/react';
import type { VaeModelConfig } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
@@ -48,10 +49,12 @@ import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
+ type AccountScope,
} from '@platform/state/accountLifecycle';
import { useExternalStoreSelector } from '@platform/state/selectors';
import { getApiErrorMessage } from '@platform/transport/http';
import { socketHub } from '@platform/transport/socketHub';
+import { toaster } from '@platform/ui/toaster';
import { useQueryClient } from '@tanstack/react-query';
import {
createCanvasFromImages,
@@ -62,6 +65,7 @@ import {
sendGalleryImageAsControl,
type GalleryCanvasImportDestination,
} from '@workbench/canvas-operations/api';
+import { getProjectSyncSnapshot } from '@workbench/projects/syncStore';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useNotify } from '@workbench/useNotify';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
@@ -71,6 +75,7 @@ import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSelector } from
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import type { MediaUsageHost } from './mediaUsageReport';
import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
import type { VideoRecallKind } from './videoRecall';
@@ -100,7 +105,6 @@ import {
type ImageRecallCapabilities,
type ImageRecallKind,
} from './imageRecall';
-import { collectMediaUsage } from './mediaUsage';
import { buildPbrMapsGraph } from './pbrMapsGraph';
/**
@@ -152,6 +156,64 @@ export interface ImageActions extends GalleryItemActions {
}
const EMPTY_WIDGET_VALUES: Record<string, unknown> = {};
+/**
+ * How long a deletion without routine confirmation waits for the usage check, per stage (server, then closed
+ * projects), before asking instead: the user is waiting on a click.
+ */
+const UNCONFIRMED_DELETION_CHECK_TIMEOUT_MS = 3_000;
+/** A usage check this quick finishes unnoticed; a slower one shows a progress toast until it does. */
+const PENDING_CHECK_NOTICE_DELAY_MS = 400;
+
+/**
+ * Items a deletion is under way for (checking, asking, or deleting), per account lifetime, shared by every surface
+ * that deletes (grid, selection bar, Preview, menus), each with its own image actions.
+ */
+const deletionsInFlight = new WeakMap<AccountScope, Set<GalleryItemKey>>();
+
+/** Claims the items for one deletion; null when any is already claimed. The release ends the claim. */
+const claimDeletion = (items: readonly GalleryItemRef[]): (() => void) | null => {
+ const owner = captureAccountScope();
+ const claimed = deletionsInFlight.get(owner) ?? new Set<GalleryItemKey>();
+ const keys = items.map(toGalleryItemKey);
+
+ if (keys.some((key) => claimed.has(key))) {
+ return null;
+ }
+
+ deletionsInFlight.set(owner, claimed);
+ keys.forEach((key) => claimed.add(key));
+
+ return () => keys.forEach((key) => claimed.delete(key));
+};
+
+/**
+ * The one "checking" notice for every silent-deletion check running at once, from any surface: shown once a check has
+ * run for a moment, and dismissed only when the last running check ends, however it ends.
+ */
+const PENDING_CHECK_NOTICE_ID = 'gallery-deletion-usage-check';
+let pendingChecks = 0;
+
+/** Counts a check as running until the returned release, which is safe to call more than once. */
+const holdPendingCheckNotice = (title: string): (() => void) => {
+ pendingChecks += 1;
+ const timer = setTimeout(() => {
+ // The same id updates a notice already showing instead of stacking a second one.
+ toaster.create({ duration: Number.POSITIVE_INFINITY, id: PENDING_CHECK_NOTICE_ID, title, type: 'loading' });
+ }, PENDING_CHECK_NOTICE_DELAY_MS);
+ let released = false;
+
+ return () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ clearTimeout(timer);
+ pendingChecks -= 1;
+ if (pendingChecks === 0) {
+ toaster.dismiss(PENDING_CHECK_NOTICE_ID);
+ }
+ };
+};
/**
* Selected as booleans so Video panel edits re-render action consumers only when an answer flips (the workbench
@@ -570,21 +632,83 @@ export const useImageActions = ({
},
});
};
- const deleteItems: ImageActions['deleteItems'] = (items, options) => {
- const project = projectId ? queries.getProject(projectId) : queries.getSnapshot().activeProject;
- const usage = project ? collectMediaUsage(project, items) : [];
+ const deleteItems: ImageActions['deleteItems'] = async (items, options) => {
+ // A repeated Delete (key repeat, a second surface) for items already being checked, asked about or deleted is
+ // dropped: running it again would delete them twice and report the second, refused attempt as a failure.
+ const release = claimDeletion(items);
+
+ if (!release) {
+ return;
+ }
- // The opt-out covers deleting one item the user is looking at. A batch, an item off screen and media the
- // project still uses always ask: the dialog names what goes, and authored work would point at nothing.
+ const usageHost: MediaUsageHost = {
+ getLoadedProjects: () => queries.getSnapshot().projects,
+ getSyncBase: (targetProjectId) => getProjectSyncSnapshot().projects[targetProjectId],
+ openProjectId: projectId ?? queries.getSnapshot().activeProject.id,
+ };
+ const request = { kind: 'items', refs: items } as const;
+ // The dialog shows the check running while its code loads; nothing of it is part of the editor's startup.
+ const checkUsage = (signal: AbortSignal) =>
+ import('./mediaUsageReport').then(({ resolveMediaUsage }) => resolveMediaUsage(request, usageHost, { signal }));
+ // The opt-out covers deleting one item the user is looking at. A batch, an item off screen and media still in
+ // use always ask: the dialog names what goes, and authored work would point at nothing.
const canSkipFutureConfirmations = items.length === 1 && options?.targetsOffScreen !== true;
+ const confirm = (usage?: GalleryMediaUsageReport) =>
+ requestDeletionConfirmation(items, () => deleteItemsConfirmed(items), {
+ canSkipFutureConfirmations,
+ checkUsage,
+ returnFocus: options?.returnFocus,
+ usage,
+ });
- return confirmImageDeletion || usage.length > 0 || !canSkipFutureConfirmations
- ? requestDeletionConfirmation(items, () => deleteItemsConfirmed(items), {
- canSkipFutureConfirmations,
- returnFocus: options?.returnFocus,
- usage,
- })
- : deleteItemsConfirmed(items);
+ try {
+ if (confirmImageDeletion || !canSkipFutureConfirmations) {
+ return await confirm();
+ }
+
+ // Without routine confirmation, one visible item goes silently only once the check finds nothing using it; a
+ // use, or a check that could not finish in time, still asks. A check slower than a moment says it is running.
+ const owner = captureAccountScope();
+ const releaseNotice = holdPendingCheckNotice(t('widgets.gallery.deleteInUse.checking'));
+ // The report the dialog shows when one asks; none when it must check again.
+ let usage: GalleryMediaUsageReport | undefined;
+ let isUnused = false;
+ let checkFailed = false;
+
+ try {
+ const [{ isUsedInLoadedProjects, resolveMediaUsage }, { isGalleryMediaUnused }] = await Promise.all([
+ import('./mediaUsageReport'),
+ import('@features/gallery/mediaUsage'),
+ ]);
+ const report = await resolveMediaUsage(request, usageHost, {
+ projectReadsTimeoutMs: UNCONFIRMED_DELETION_CHECK_TIMEOUT_MS,
+ serverTimeoutMs: UNCONFIRMED_DELETION_CHECK_TIMEOUT_MS,
+ });
+
+ if (!isGalleryMediaUnused(report)) {
+ usage = report;
+ } else {
+ // The answer can be seconds old. A use added in this tab since still asks; the dialog checks again rather
+ // than show an answer that missed it.
+ isUnused = !isUsedInLoadedProjects(items, usageHost);
+ }
+ } catch {
+ checkFailed = true;
+ } finally {
+ // Before any dialog opens: the notice is about the check, not the answer.
+ releaseNotice();
+ }
+
+ if (checkFailed) {
+ // The resolver rejects only on an account change, and the deletion belonged to the previous account. Its
+ // code failing to load leaves the check undone: the dialog runs it again, and offers Retry if it fails.
+ return isAccountScopeCurrent(owner) ? await confirm() : undefined;
+ }
+
+ return isUnused ? await deleteItemsConfirmed(items) : await confirm(usage);
+ } finally {
+ release();
+ }
};
/** Groups refs by a known prior value; refs whose prior value is unknown are left out. */
const groupByPrior = <Value>(
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
index c178b0bc8f..0f47e52597 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
@@ -25,6 +25,7 @@ import {
getProjectDocumentSchemaRefusal,
getProjectWriteSizeRefusal,
getProject,
+ getProjectWithinSize,
isProjectCanvasSchemaUnsupportedError,
ProjectCreateAbsentError,
saveProjectWorkspace,
@@ -38,6 +39,77 @@ beforeEach(() => {
accountLifecycle.activate('project-api-test-user');
});
+describe('getProjectWithinSize', () => {
+ it('parses a record within the bound and skips one past it, declared or measured, without parsing it', async () => {
+ const record = { name: 'Small', project_id: 'p-1' };
+ const body = JSON.stringify(record);
+ const cancel = vi.fn(() => Promise.resolve());
+ const text = vi.fn(() => Promise.resolve(body));
+
+ transport.apiFetch.mockResolvedValueOnce(
+ new Response(body, { headers: { 'Content-Length': String(body.length) } })
+ );
+ await expect(getProjectWithinSize('p-1', 1000)).resolves.toEqual(record);
+ expect(transport.apiFetch).toHaveBeenCalledWith(
+ '/api/v1/projects/p-1?max_canvas_schema_version=6&max_document_schema_version=4',
+ { signal: undefined }
+ );
+
+ transport.apiFetch.mockResolvedValueOnce({
+ body: { cancel },
+ headers: new Headers({ 'Content-Length': '5000' }),
+ text,
+ });
+ await expect(getProjectWithinSize('p-1', 1000)).resolves.toBeNull();
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(text).not.toHaveBeenCalled();
+
+ // Without a declared length (a chunked answer) the body is measured as it arrives.
+ transport.apiFetch.mockResolvedValueOnce(new Response(`{"padding":"${'x'.repeat(2000)}"}`));
+ await expect(getProjectWithinSize('p-1', 1000)).resolves.toBeNull();
+ });
+
+ it('stops reading a compressed answer whose small declared length hides a body past the bound', async () => {
+ // What a gzipped answer looks like once the browser decodes it: the header counts the compressed bytes.
+ const chunk = new TextEncoder().encode(`{"padding":"${'x'.repeat(390)}",`);
+ let pulls = 0;
+ let cancelled = false;
+ const body = new ReadableStream<Uint8Array>({
+ cancel: () => {
+ cancelled = true;
+ },
+ pull: (controller) => {
+ pulls += 1;
+ controller.enqueue(chunk);
+ },
+ });
+
+ transport.apiFetch.mockResolvedValueOnce(new Response(body, { headers: { 'Content-Length': '120' } }));
+
+ await expect(getProjectWithinSize('p-1', 1000)).resolves.toBeNull();
+ expect(cancelled).toBe(true);
+ // The third chunk crosses the bound; the endless rest is never pulled.
+ expect(pulls).toBeLessThanOrEqual(4);
+ });
+
+ it('decodes a record split across chunks, a character straddling two of them', async () => {
+ const record = { name: 'Café', project_id: 'p-1' };
+ const bytes = new TextEncoder().encode(JSON.stringify(record));
+ const split = bytes.indexOf(0xc3) + 1;
+ const body = new ReadableStream<Uint8Array>({
+ start: (controller) => {
+ controller.enqueue(bytes.slice(0, split));
+ controller.enqueue(bytes.slice(split));
+ controller.close();
+ },
+ });
+
+ transport.apiFetch.mockResolvedValueOnce(new Response(body, { headers: { 'Content-Length': '30' } }));
+
+ await expect(getProjectWithinSize('p-1', 1000)).resolves.toEqual(record);
+ });
+});
+
/** Cleanup requires proven project absence after an ambiguous create. */
describe('createProjectSettled', () => {
const request = { data: {}, name: 'Imported', project_id: 'project-1' };
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.ts
index f23d94e052..14957070d4 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts
@@ -132,18 +132,61 @@ export const listProjects = (signal?: AbortSignal): Promise<ProjectSummaryDTO[]>
signal
);
+const getProjectPath = (projectId: string): string =>
+ `${PROJECTS_BASE}/${encodeURIComponent(projectId)}?max_canvas_schema_version=${MAX_SUPPORTED_CANVAS_SCHEMA_VERSION}` +
+ `&max_document_schema_version=${PROJECT_SPLIT_DOCUMENT_SCHEMA_VERSION}`;
+
export const getProject = (projectId: string, signal?: AbortSignal): Promise<ProjectWithWorkspaceDTO> =>
withRequestDeadline(
- (signal) =>
- apiFetchJson<ProjectWithWorkspaceDTO>(
- `${PROJECTS_BASE}/${encodeURIComponent(projectId)}?max_canvas_schema_version=${MAX_SUPPORTED_CANVAS_SCHEMA_VERSION}` +
- `&max_document_schema_version=${PROJECT_SPLIT_DOCUMENT_SCHEMA_VERSION}`,
- { signal }
- ),
+ (signal) => apiFetchJson<ProjectWithWorkspaceDTO>(getProjectPath(projectId), { signal }),
PROJECT_REQUEST_TIMEOUT_MS,
signal
);
+/**
+ * A project record no larger than `maxBytes` once decoded, else null without parsing it: for reads that inspect a
+ * closed project in passing and must not spend the main thread on a large document. A declared `Content-Length` over
+ * the bound skips the body at once. That header counts the encoded body, and the server compresses JSON, so a small one
+ * proves nothing: the body is read as a stream, counting decoded bytes, and the read stops once past the bound.
+ */
+export const getProjectWithinSize = async (
+ projectId: string,
+ maxBytes: number,
+ signal?: AbortSignal
+): Promise<ProjectWithWorkspaceDTO | null> => {
+ const response = await apiFetch(getProjectPath(projectId), { signal });
+ const declared = Number(response.headers.get('Content-Length'));
+
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ await response.body?.cancel();
+ return null;
+ }
+
+ const decoder = new TextDecoder();
+ let text = '';
+ let size = 0;
+
+ if (response.body) {
+ const reader = response.body.getReader();
+
+ for (;;) {
+ const { done, value } = await reader.read();
+
+ if (done) {
+ break;
+ }
+ size += value.byteLength;
+ if (size > maxBytes) {
+ await reader.cancel();
+ return null;
+ }
+ text += decoder.decode(value, { stream: true });
+ }
+ }
+
+ return JSON.parse(text + decoder.decode()) as ProjectWithWorkspaceDTO;
+};
+
const isProjectWriteBusyError = (error: unknown): error is ApiError => {
if (!(error instanceof ApiError) || error.status !== 429) {
return false;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index 47c8f57aef..573825f81f 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -4835,6 +4835,8 @@ describe('project content and the caller’s workspace', () => {
expect(api.updateProject).not.toHaveBeenCalled();
expect(vi.mocked(api.saveProjectWorkspace).mock.calls.map(([, request]) => request.expected_revision)).toEqual([1]);
expect(api.records.get(project.id)).toMatchObject({ revision: 1, workspace: { revision: 2 } });
+ // What the copy here builds on, as the media usage check compares it with the server's.
+ expect(getProjectSyncSnapshot().projects[project.id]).toMatchObject({ revision: 1, workspaceRevision: 2 });
});
it('saves a change to the shared project as the content alone', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
index f1bcad18ff..9562e20c50 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
@@ -1938,6 +1938,7 @@ export const createDurableSyncedWorkbenchPersistence = (
isPendingPush:
!entry || pendingProjectIds.has(projectId) || conflict !== undefined || schemaRefusal !== undefined,
revision: entry?.revision ?? null,
+ ...(entry ? { workspaceRevision: entry.workspaceRevision } : {}),
...(conflict
? {
conflict: {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index e951df165f..60daedc700 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -11,6 +11,8 @@ import type { ProjectPushOutcome, ProjectSchemaRefusal } from './projectFlush';
export interface ProjectSyncInfo {
/** Server revision the next save is based on; null = never reached the server. */
revision: number | null;
+ /** The caller's workspace revision the next save is based on; null while the server holds none, absent if unknown. */
+ workspaceRevision?: number | null;
/** True when the local document differs from what the server acknowledged. */
isPendingPush: boolean;
/** Present when the server requires a newer canvas schema than this client supports. */
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index aa4f1e16cd..160b81339e 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -347,6 +347,9 @@ const GALLERY_STATE_MODULES = [
// costs a request.
'/features/gallery/react.ts',
'/features/gallery/ui/GalleryUiContext.tsx',
+ // The deletion dialogs' usage panel, published by the React entry: eager (Preview, image actions) and lazy (the
+ // Gallery's board menu) owners reach it; alone it costs a boot request. Its report view stays lazy.
+ '/features/gallery/ui/GalleryMediaUsagePanel.tsx',
'/features/gallery/ui/galleryStateView.ts',
'/features/queue/contracts.ts',
// The queue contracts, index and React entries re-export these; the lazy queue rows and widget share them. Alone
diff --git a/tests/app/routers/test_gallery_media_usage.py b/tests/app/routers/test_gallery_media_usage.py
new file mode 100644
index 0000000000..76a7727300
--- /dev/null
+++ b/tests/app/routers/test_gallery_media_usage.py
@@ -0,0 +1,472 @@
+"""`POST /api/v1/gallery/usage`: what still uses media before the gallery deletes it, per caller."""
+
+import json
+import uuid
+from typing import Any, Optional
+
+import pytest
+from fastapi import status
+from fastapi.testclient import TestClient
+
+from invokeai.app.services.gallery import gallery_default
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.database.database import Database
+from invokeai.app.services.shared.database.queries import intermediates as intermediate_queries
+from invokeai.app.services.shared.database.queries import media_references as media_reference_queries
+from invokeai.app.services.shared.media_references import MediaReferences
+from invokeai.app.services.workflow_records.workflow_records_common import (
+ WorkflowCategory,
+ WorkflowMeta,
+ WorkflowWithoutID,
+)
+from tests.app.routers.conftest import _auth, _create_board
+from tests.fixtures.sqlite_database import sqlite_cursor
+
+URL = "/api/v1/gallery/usage"
+
+
+def _user_id(invoker: Invoker, email: str) -> str:
+ user = invoker.services.users.get_by_email(email)
+ assert user is not None
+ return user.user_id
+
+
+def user1(mock_invoker: Invoker, user1_token: str) -> str:
+ return _user_id(mock_invoker, "[email protected]")
+
+
+def user2(mock_invoker: Invoker, user2_token: str) -> str:
+ return _user_id(mock_invoker, "[email protected]")
+
+
+def _image(invoker: Invoker, name: str, user_id: str, board_id: Optional[str] = None) -> None:
+ invoker.services.image_records.save(
+ image_name=name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ has_workflow=False,
+ user_id=user_id,
+ )
+ if board_id is not None:
+ invoker.services.board_image_records.add_image_to_board(board_id, name)
+
+
+def _video(invoker: Invoker, name: str, user_id: str, board_id: Optional[str] = None) -> None:
+ invoker.services.video_records.save(
+ video_name=name,
+ video_origin=ResourceOrigin.INTERNAL,
+ video_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ duration=1.0,
+ fps=24.0,
+ has_workflow=False,
+ user_id=user_id,
+ )
+ if board_id is not None:
+ invoker.services.board_video_records.add_video_to_board(board_id, name)
+
+
+def _naming(*images: str, videos: tuple[str, ...] = ()) -> dict[str, Any]:
+ return {
+ "images": [{"imageName": name} for name in images],
+ "videos": [{"videoName": name} for name in videos],
+ }
+
+
+def _project(invoker: Invoker, user_id: str, name: str, content: dict, workspace: Optional[dict] = None) -> str:
+ return invoker.services.project_records.create(
+ user_id,
+ name,
+ content,
+ minimum_document_schema_version=4,
+ max_document_schema_version=4,
+ workspace=workspace,
+ ).project_id
+
+
+def _workflow(invoker: Invoker, user_id: str, name: str, *images: str) -> str:
+ workflow = WorkflowWithoutID(
+ name=name,
+ author="",
+ description="",
+ version="1.0.0",
+ contact="",
+ tags="",
+ notes="",
+ exposedFields=[],
+ meta=WorkflowMeta(version="3.0.0", category=WorkflowCategory.User),
+ nodes=[{"id": f"n{index}", "data": {"image": {"image_name": image}}} for index, image in enumerate(images)],
+ edges=[],
+ )
+ return invoker.services.workflow_records.create(workflow, user_id=user_id).workflow_id
+
+
+def _quarantined(database: Database, user_id: str, project_id: str, name: str, *images: str) -> None:
+ with sqlite_cursor(database) as cursor:
+ cursor.execute(
+ "CREATE TABLE IF NOT EXISTS orphaned_projects_2026_08_06 (project_id TEXT, user_id TEXT, name TEXT,"
+ " data TEXT, PRIMARY KEY (user_id, project_id));"
+ )
+ cursor.execute("INSERT INTO orphaned_projects_2026_08_06 VALUES (?, ?, ?, '{}');", (project_id, user_id, name))
+ database.queries.media_references.replace(
+ owner_kind="quarantined_project",
+ user_id=user_id,
+ owner_id=project_id,
+ references=MediaReferences(images=set(images)),
+ )
+
+
+def _queue_item(database: Database, user_id: Optional[str], status: str, *images: str) -> None:
+ nodes = {f"n{index}": {"image": {"image_name": image}} for index, image in enumerate(images)}
+ with sqlite_cursor(database) as cursor:
+ cursor.execute(
+ "INSERT INTO session_queue (queue_id, session, session_id, batch_id, priority, user_id, status)"
+ " VALUES ('default', ?, ?, 'batch', 0, ?, ?);",
+ (json.dumps({"graph": {"nodes": nodes}}), uuid.uuid4().hex, user_id, status),
+ )
+
+
+def _usage(client: TestClient, token: str, **body: Any) -> dict[str, Any]:
+ response = client.post(URL, json=body, headers=_auth(token))
+ assert response.status_code == status.HTTP_200_OK, response.text
+ return response.json()
+
+
+def _documents(usage: dict[str, Any]) -> list[tuple[str, Optional[str], list[str], list[str]]]:
+ return [(d["kind"], d["name"], d["image_names"], d["video_names"]) for d in usage["documents"]]
+
+
+NO_QUEUE = {"item_count": 0, "image_names": [], "video_names": [], "image_count": 0, "video_count": 0}
+NO_OTHERS = {"document_count": 0, "queue_item_count": 0, "image_count": 0, "video_count": 0}
+
+
+def test_names_every_kind_of_the_callers_own_use(
+ client: TestClient, mock_invoker: Invoker, mock_sqlite_database: Database, user1_token: str, user1: str
+) -> None:
+ for name in ("content.png", "workspace.png", "flow.png", "canvas.png", "ref.png", "kept.png", "queued.png"):
+ _image(mock_invoker, name, user1)
+ for name in ("done.png", "free.png"):
+ _image(mock_invoker, name, user1)
+ _video(mock_invoker, "clip.mp4", user1)
+ project = _project(
+ mock_invoker,
+ user1,
+ "Poster",
+ _naming("content.png", videos=("clip.mp4",)),
+ workspace=_naming("workspace.png"),
+ )
+ workflow = _workflow(mock_invoker, user1, "Upscale", "flow.png")
+ client_state = mock_invoker.services.client_state_persistence
+ client_state.set_by_key(user1, "canvas", '{"layers": [{"image": {"image_name": "canvas.png"}}]}')
+ client_state.set_by_key(user1, "refs", '{"refs": [{"imageName": "ref.png"}]}')
+ _quarantined(mock_sqlite_database, user1, "old-project", "Before boards", "kept.png")
+ _queue_item(mock_sqlite_database, user1, "pending", "queued.png")
+ _queue_item(mock_sqlite_database, user1, "completed", "done.png")
+
+ usage = _usage(
+ client,
+ user1_token,
+ image_names=[
+ "content.png",
+ "workspace.png",
+ "flow.png",
+ "canvas.png",
+ "ref.png",
+ "kept.png",
+ "queued.png",
+ "done.png",
+ "free.png",
+ ],
+ video_names=["clip.mp4"],
+ )
+
+ assert usage["checked_image_count"] == 9
+ assert usage["checked_video_count"] == 1
+ assert usage["in_use_image_count"] == 7
+ assert usage["in_use_video_count"] == 1
+ assert _documents(usage) == [
+ ("legacy_editor", None, ["canvas.png", "ref.png"], []),
+ ("project", "Poster", ["content.png", "workspace.png"], ["clip.mp4"]),
+ ("quarantined_project", "Before boards", ["kept.png"], []),
+ ("workflow", "Upscale", ["flow.png"], []),
+ ]
+ assert [d["id"] for d in usage["documents"]] == ["legacy_editor", project, "old-project", workflow]
+ assert usage["documents_total"] == 4
+ assert usage["queue"] == {
+ "item_count": 1,
+ "image_names": ["queued.png"],
+ "video_names": [],
+ "image_count": 1,
+ "video_count": 0,
+ }
+ assert usage["other_accounts"] == NO_OTHERS
+
+
+def test_other_accounts_use_is_counted_without_naming_it(
+ client: TestClient,
+ mock_invoker: Invoker,
+ mock_sqlite_database: Database,
+ user1_token: str,
+ user1: str,
+ user2: str,
+) -> None:
+ _image(mock_invoker, "shared.png", user1)
+ _image(mock_invoker, "queued.png", user1)
+ _video(mock_invoker, "clip.mp4", user1)
+ own_project = _project(mock_invoker, user1, "Mine", _naming("shared.png"))
+ _project(mock_invoker, user2, "Secret plans", _naming("shared.png", videos=("clip.mp4",)))
+ _workflow(mock_invoker, user2, "Secret flow", "shared.png")
+ # Another account's workspace in the caller's project is that account's document.
+ mock_sqlite_database.queries.media_references.replace(
+ owner_kind="project_workspace",
+ user_id=user2,
+ owner_id=own_project,
+ references=MediaReferences(images={"shared.png"}),
+ )
+ _queue_item(mock_sqlite_database, user2, "in_progress", "queued.png")
+
+ response = client.post(
+ URL, json={"image_names": ["shared.png", "queued.png"], "video_names": ["clip.mp4"]}, headers=_auth(user1_token)
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ usage = response.json()
+ assert _documents(usage) == [("project", "Mine", ["shared.png"], [])]
+ assert usage["queue"] == NO_QUEUE
+ assert usage["other_accounts"] == {"document_count": 3, "queue_item_count": 1, "image_count": 2, "video_count": 1}
+ assert usage["in_use_image_count"] == 2
+ assert usage["in_use_video_count"] == 1
+ assert "Secret" not in response.text
+ assert user2 not in response.text
+
+
+def test_queue_work_without_an_owner_counts_as_another_accounts(
+ client: TestClient,
+ mock_invoker: Invoker,
+ mock_sqlite_database: Database,
+ admin_token: str,
+ user1_token: str,
+ user1: str,
+) -> None:
+ # The queue's own access rules match an item's owner by equality, so a row stored without one is no caller's.
+ _image(mock_invoker, "orphan.png", user1)
+ _queue_item(mock_sqlite_database, None, "pending", "orphan.png")
+
+ for token in (user1_token, admin_token):
+ usage = _usage(client, token, image_names=["orphan.png"])
+
+ assert usage["in_use_image_count"] == 1
+ assert usage["queue"] == NO_QUEUE
+ assert usage["other_accounts"] == {
+ "document_count": 0,
+ "queue_item_count": 1,
+ "image_count": 1,
+ "video_count": 0,
+ }
+
+
+def test_names_the_caller_may_not_delete_are_not_checked(
+ client: TestClient,
+ mock_invoker: Invoker,
+ mock_sqlite_database: Database,
+ admin_token: str,
+ user1_token: str,
+ user2: str,
+) -> None:
+ _image(mock_invoker, "theirs.png", user2)
+ _video(mock_invoker, "theirs.mp4", user2)
+ _project(mock_invoker, user2, "Theirs", _naming("theirs.png", "missing.png", videos=("theirs.mp4",)))
+ _queue_item(mock_sqlite_database, user2, "pending", "theirs.png")
+
+ usage = _usage(
+ client, user1_token, image_names=["theirs.png", "missing.png"], video_names=["theirs.mp4", "missing.mp4"]
+ )
+
+ assert (usage["checked_image_count"], usage["checked_video_count"]) == (0, 0)
+ assert (usage["in_use_image_count"], usage["in_use_video_count"]) == (0, 0)
+ assert usage["documents"] == []
+ assert usage["other_accounts"] == NO_OTHERS
+
+ # An administrator may delete anyone's media, so it is checked, but the owner's documents stay counts.
+ usage = _usage(client, admin_token, image_names=["theirs.png", "missing.png"], video_names=["theirs.mp4"])
+
+ assert (usage["checked_image_count"], usage["checked_video_count"]) == (1, 1)
+ assert usage["documents"] == []
+ assert usage["other_accounts"] == {"document_count": 1, "queue_item_count": 1, "image_count": 1, "video_count": 1}
+
+
+def test_board_scope_checks_what_deleting_the_board_would_delete(
+ client: TestClient,
+ mock_invoker: Invoker,
+ admin_token: str,
+ user1_token: str,
+ user1: str,
+ user2: str,
+) -> None:
+ board_id = _create_board(client, user1_token)
+ _image(mock_invoker, "mine.png", user1, board_id)
+ _video(mock_invoker, "mine.mp4", user1, board_id)
+ # Another account's contribution survives the owner's board deletion, so the owner does not check it.
+ _image(mock_invoker, "contributed.png", user2, board_id)
+ _project(mock_invoker, user1, "Poster", _naming("mine.png", videos=("mine.mp4",)))
+ _workflow(mock_invoker, user2, "Theirs", "contributed.png")
+
+ usage = _usage(client, user1_token, board_id=board_id)
+
+ assert (usage["checked_image_count"], usage["checked_video_count"]) == (1, 1)
+ assert _documents(usage) == [("project", "Poster", ["mine.png"], ["mine.mp4"])]
+ assert usage["other_accounts"] == NO_OTHERS
+
+ # An administrator deleting someone else's board deletes everyone's media on it.
+ usage = _usage(client, admin_token, board_id=board_id)
+
+ assert (usage["checked_image_count"], usage["checked_video_count"]) == (2, 1)
+ assert usage["in_use_image_count"] == 2
+ assert usage["documents"] == []
+ assert usage["other_accounts"] == {"document_count": 2, "queue_item_count": 0, "image_count": 2, "video_count": 1}
+
+
+def test_board_scope_spanning_query_chunks_reports_every_use(
+ client: TestClient,
+ mock_invoker: Invoker,
+ mock_sqlite_database: Database,
+ monkeypatch: pytest.MonkeyPatch,
+ user1_token: str,
+ user1: str,
+ user2: str,
+) -> None:
+ # Document names are read in chunks of ids per kind, active queue sessions in chunks of item ids.
+ monkeypatch.setattr(media_reference_queries, "IN_CHUNK", 2)
+ monkeypatch.setattr(intermediate_queries, "IN_CHUNK", 2)
+ board_id = _create_board(client, user1_token)
+ images = [f"board-{index}.png" for index in range(7)]
+ for name in images:
+ _image(mock_invoker, name, user1, board_id)
+ for index, name in enumerate(images[:5]):
+ _workflow(mock_invoker, user1, f"flow {index}", name)
+ for index, name in enumerate(images[:3]):
+ _project(mock_invoker, user1, f"project {index}", _naming(name, images[6]))
+ for name in images[:5]:
+ _queue_item(mock_sqlite_database, user1, "pending", name)
+ _workflow(mock_invoker, user2, "theirs", images[5])
+
+ usage = _usage(client, user1_token, board_id=board_id)
+
+ assert usage["checked_image_count"] == 7
+ assert usage["in_use_image_count"] == 7
+ assert _documents(usage) == [
+ *((("project", f"project {index}", sorted([images[index], images[6]]), []) for index in range(3))),
+ *((("workflow", f"flow {index}", [images[index]], []) for index in range(5))),
+ ]
+ assert usage["documents_total"] == 8
+ assert usage["queue"]["item_count"] == 5
+ assert usage["queue"]["image_names"] == sorted(images[:5])
+ assert usage["other_accounts"] == {"document_count": 1, "queue_item_count": 0, "image_count": 1, "video_count": 0}
+
+
+def test_board_scope_follows_the_board_deletion_errors(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str, user1: str
+) -> None:
+ board_id = _create_board(client, user1_token)
+
+ assert client.post(URL, json={"board_id": board_id}, headers=_auth(user2_token)).status_code == 403
+ assert client.post(URL, json={"board_id": "no-such-board"}, headers=_auth(user1_token)).status_code == 404
+
+ project = _project(mock_invoker, user1, "Poster", {})
+ inbox = mock_invoker.services.project_records.get_board_id(user1, project)
+ response = client.post(URL, json={"board_id": inbox}, headers=_auth(user1_token))
+ assert response.status_code == status.HTTP_409_CONFLICT
+
+
+ "body",
+ [
+ {"board_id": "b", "image_names": ["a.png"]},
+ {"board_id": "b", "video_names": ["a.mp4"]},
+ {"image_names": [""]},
+ {"image_names": ["x" * 256]},
+ {"image_names": [f"{index}.png" for index in range(1001)]},
+ {"video_names": [f"{index}.mp4" for index in range(1001)]},
+ ],
+)
+def test_malformed_requests_are_refused(client: TestClient, user1_token: str, body: dict[str, Any]) -> None:
+ response = client.post(URL, json=body, headers=_auth(user1_token))
+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT, response.text
+
+
+def test_lists_are_capped_and_counts_are_exact(
+ client: TestClient,
+ mock_invoker: Invoker,
+ mock_sqlite_database: Database,
+ monkeypatch: pytest.MonkeyPatch,
+ user1_token: str,
+ user1: str,
+) -> None:
+ monkeypatch.setattr(gallery_default, "MAX_USAGE_DOCUMENTS", 2)
+ monkeypatch.setattr(gallery_default, "MAX_USAGE_NAMES", 2)
+ names = ["a.png", "b.png", "c.png"]
+ for name in names:
+ _image(mock_invoker, name, user1)
+ for workflow_name in ("charlie", "Bravo", "alpha"):
+ _workflow(mock_invoker, user1, workflow_name, *names)
+ _queue_item(mock_sqlite_database, user1, "pending", *names)
+
+ usage = _usage(client, user1_token, image_names=names)
+
+ assert [(d["name"], d["image_names"], d["image_count"]) for d in usage["documents"]] == [
+ ("alpha", ["a.png", "b.png"], 3),
+ ("Bravo", ["a.png", "b.png"], 3),
+ ]
+ assert usage["documents_total"] == 3
+ assert usage["queue"]["image_names"] == ["a.png", "b.png"]
+ assert usage["queue"]["image_count"] == 3
+
+
+def test_projects_report_the_revisions_their_names_were_read_at(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, user1: str
+) -> None:
+ _image(mock_invoker, "a.png", user1)
+ projects = mock_invoker.services.project_records
+ bare = _project(mock_invoker, user1, "Bare", _naming("a.png"))
+ worked = _project(mock_invoker, user1, "Worked", _naming("a.png"), workspace=_naming("a.png"))
+ _workflow(mock_invoker, user1, "Flow", "a.png")
+
+ def revisions() -> dict[Optional[str], tuple[Optional[int], Optional[int]]]:
+ usage = _usage(client, user1_token, image_names=["a.png"])
+ return {d["name"]: (d["revision"], d["workspace_revision"]) for d in usage["documents"]}
+
+ def as_read(project_id: str) -> tuple[int, Optional[int]]:
+ record = projects.get(user1, project_id, max_document_schema_version=4)
+ return record.revision, record.workspace.revision if record.workspace else None
+
+ assert revisions() == {"Bare": as_read(bare), "Worked": as_read(worked), "Flow": (None, None)}
+ assert as_read(bare) == (1, None)
+
+ projects.update(
+ user1, bare, 1, "Bare", _naming("a.png"), minimum_document_schema_version=4, max_document_schema_version=4
+ )
+ projects.save_workspace(user1, bare, None, _naming(), max_document_schema_version=4)
+ projects.save_workspace(user1, worked, 1, _naming("a.png"), max_document_schema_version=4)
+
+ assert revisions() == {"Bare": (2, 1), "Worked": (1, 2), "Flow": (None, None)}
+
+
+def test_an_empty_request_checks_nothing(client: TestClient, user1_token: str) -> None:
+ assert client.post(URL, json={}).status_code == status.HTTP_401_UNAUTHORIZED
+
+ assert _usage(client, user1_token) == {
+ "checked_image_count": 0,
+ "checked_video_count": 0,
+ "in_use_image_count": 0,
+ "in_use_video_count": 0,
+ "documents": [],
+ "documents_total": 0,
+ "queue": NO_QUEUE,
+ "other_accounts": NO_OTHERS,
+ }
diff --git a/tests/app/routers/test_images.py b/tests/app/routers/test_images.py
index 3c4548ad27..451adf88ff 100644
--- a/tests/app/routers/test_images.py
+++ b/tests/app/routers/test_images.py
@@ -10,7 +10,7 @@ from pydantic import ValidationError
from invokeai.app.api.auth_dependencies import get_current_user_or_default
from invokeai.app.api.dependencies import ApiDependencies
-from invokeai.app.api.routers.images import MAX_IMAGE_BATCH_SIZE
+from invokeai.app.api.routers._limits import MAX_IMAGE_BATCH_SIZE
from invokeai.app.api_app import app
from invokeai.app.invocations.fields import MetadataField
from invokeai.app.services.auth.token_service import TokenData
@@ -849,6 +849,7 @@ def test_every_image_names_body_is_bounded(client: TestClient) -> None:
assert sorted(checked) == [
"/api/v1/board_images/batch",
"/api/v1/board_images/batch/delete",
+ "/api/v1/gallery/usage",
"/api/v1/images/copy",
"/api/v1/images/delete",
"/api/v1/images/download",
diff --git a/tests/app/services/intermediates/test_intermediates_records.py b/tests/app/services/intermediates/test_intermediates_records.py
index ca2714be89..b1b0d1a820 100644
--- a/tests/app/services/intermediates/test_intermediates_records.py
+++ b/tests/app/services/intermediates/test_intermediates_records.py
@@ -18,7 +18,7 @@ from invokeai.app.services.client_state_persistence.client_state_persistence_def
)
from invokeai.app.services.image_records.image_records_default import ImageRecordStorage
from invokeai.app.services.intermediates import intermediates_records_default
-from invokeai.app.services.intermediates.intermediates_common import BROWSER_HOLD_TTL_SECONDS
+from invokeai.app.services.intermediates.intermediates_common import BROWSER_HOLD_TTL_SECONDS, ActiveQueueMediaUse
from invokeai.app.services.intermediates.intermediates_records_default import (
IntermediatesRecords,
ReferenceOwner,
@@ -714,3 +714,26 @@ def test_a_hold_stays_active_while_its_finished_session_belongs_to_an_active_roo
conn.execute(update(session_queue).where(session_queue.c.item_id == child).values(status="completed"))
assert records.summarize(None)[("alice", None)]["image"].counts.active == 1
+
+
+def test_active_uses_name_each_items_account_and_follow_session_rewrites(
+ database: Database, records: IntermediatesRecords
+) -> None:
+ first = _queue_item(database, "s-1", session='{"a": {"image_name": "a.png"}, "b": {"video_name": "v.mp4"}}')
+ second = _queue_item(database, "s-2", status="in_progress", session='{"a": {"image_name": "other.png"}}')
+ _queue_item(database, "s-3", status="completed", session='{"a": {"image_name": "a.png"}}')
+ _queue_item(database, "s-4", session='{"a": {"image_name": "unasked.png"}}')
+ with database.begin(write=True) as conn:
+ conn.execute(update(session_queue).where(session_queue.c.item_id == second).values(user_id="bob"))
+ asked = MediaReferences(images={"a.png", "other.png"}, videos={"v.mp4"})
+
+ mine = ActiveQueueMediaUse("system", frozenset({"a.png"}), frozenset({"v.mp4"}))
+ bobs = ActiveQueueMediaUse("bob", frozenset({"other.png"}), frozenset())
+ assert sorted(records.get_active_uses(asked), key=repr) == sorted([mine, bobs], key=repr)
+
+ # A session rewritten while its item stays active is scanned again.
+ with database.begin(write=True) as conn:
+ conn.execute(
+ update(session_queue).where(session_queue.c.item_id == first).values(session="{}", session_revision=1)
+ )
+ assert records.get_active_uses(asked) == [bobs]