Skip to content

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

fix(intermediates): close review findings across queue privacy, deletion safety and UI

Josh Corbett86030faaf1f0
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdx
index 2ff2e7f467..42fa03c6cd 100644
--- a/docs/src/content/docs/features/intermediates.mdx
+++ b/docs/src/content/docs/features/intermediates.mdx
@@ -1,9 +1,9 @@
---
title: Intermediates
-description: Reclaim disk space by clearing the temporary images and videos generation leaves behind, per project and per account.
+description: Reclaim disk space by deleting the temporary images and videos generation leaves behind, per project and per account.
---
-Generation produces intermediate images and videos: canvas composites, filter previews, staging candidates and other temporary files that were never saved to the gallery. The **Intermediates** section of Settings lists them per project, shows how much space clearing them would reclaim, and clears them safely. It is also reachable from a project's actions menu, from the Users page (administrators) and from **Data & workspace**.
+Generation produces intermediate images and videos: canvas composites, filter previews, staging candidates and other temporary files that were never saved to the gallery. The **Intermediates** section of Settings lists them per project, shows how much space deleting them would reclaim, and deletes them safely. It is also reachable from a project's actions menu, from the Users page (administrators) and from **Data & workspace**.
## What the page shows
@@ -13,9 +13,9 @@ Select rows, or **Select all**, and press **Delete**. The confirmation explains
Administrators start on their own account. **Show everyone** expands the view to every account; they can search accounts as well as project names and can open one account from the Users page. Opening the section from a project action shows that project directly, even when it is outside the first results page.
-## Safe and force clearing
+## Safe and force deletion
-A normal clear deletes only safe items. It always keeps:
+A normal delete removes only safe items. It always keeps:
- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job and completed child-workflow media until the root workflow finishes;
- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected, and cached media for 30 minutes after the job that reused it ends;
@@ -23,31 +23,35 @@ A normal clear deletes only safe items. It always keeps:
- anything a saved document still names: a project or library workflow (canvas staging candidates, cropped reference images), the legacy editor's saved canvas and reference images, or a project set aside for repair when project boards were introduced;
- anything that is no longer an intermediate.
-The advanced option in the confirmation, **also delete items that saved projects or workflows still reference**, turns the delete into a force clear. The confirmation lists every document it would break; those projects will show missing images and undo may no longer restore them. Force clearing never touches active, browser-held or recent work and cannot be undone; it asks for an acknowledgement and for the word `CLEAR` to be typed. A regular user's force clear also keeps anything another account's document names, such as a shared workflow. A new saved reference added after the preview is kept until a new preview is confirmed.
+The advanced option in the confirmation, **also delete items that saved projects or workflows still reference**, turns it into a force delete. The confirmation lists the documents it would break (the first 200, with a count of any others); those projects will show missing images and undo may no longer restore them. A force delete never touches active, browser-held or recent work and cannot be undone; it asks for an acknowledgement and for the word `DELETE` to be typed. A regular user's force delete also keeps anything another account's document names, such as a shared workflow. The same applies when an administrator loses administrator rights while their force delete runs, or when they retry it afterwards. A new saved reference added after the preview is kept until a new preview is confirmed.
-A single preview includes at most 50,000 eligible items. If more remain, the confirmation says so; run Clear again after that batch finishes. Protected items do not use up the batch limit.
+A single preview includes at most 50,000 eligible items. If more remain, the confirmation says so; run Delete again after that batch finishes. Protected items do not use up the batch limit.
Every confirmation is based on a fresh server preview that freezes exactly which files the cleanup will act on. Files created after the preview are never included, and every batch re-checks its targets at the moment of deletion: an intermediate that was promoted, referenced or picked up by a job in the meantime is kept.
-An open editor refreshes its browser hold every five minutes and when the tab becomes visible again. It releases names removed from the current projects and undo history, and releases the whole hold when the tab closes or you sign out. If the tab crashes instead, the hold expires 15 minutes after its last refresh. Reopen an unsaved browser-only draft before clearing old intermediates.
+An open editor refreshes its browser hold every five minutes and when the tab becomes visible again. It releases names removed from the current projects and undo history, and releases the whole hold when the tab closes or you sign out. If the tab crashes instead, the hold expires 15 minutes after its last refresh. Each account holds media for at most eight open editors (tabs) at once; past that, the editor refreshed longest ago stops protecting its media until its next refresh. Reopen an unsaved browser-only draft before deleting old intermediates.
## Progress and results
Cleanup runs on the server, so you can navigate away while it works. The page reports deleted, kept and failed items separately, along with files whose records are gone but whose bytes could not be removed yet; those are purged on the next server start and are not counted as reclaimed. Operation receipts and unresolved targets survive a server restart; interrupted work is shown as failed and can be retried without widening the original request. The browser also restores its last operation after a page reload.
-The server accepts at most eight active operations at a time. Wait for one to finish before confirming more cleanup if that limit is reached. If unresolved targets fill the recovery limit, retry them before starting another cleanup; the server keeps their receipts rather than silently discarding them.
+The server accepts at most eight active operations at a time, and at most two per account. Wait for one to finish before confirming another delete if a limit is reached. Each account keeps up to 50 operation receipts and 100,000 unresolved targets; older finished receipts are discarded first, and a retry is discarded together with the operation it retried. If an account's unresolved targets fill its recovery limit, that account retries them before starting another delete; the server keeps their receipts rather than silently discarding them, and other accounts are not affected.
## Permissions
| Action | Regular user | Administrator |
| --- | --- | --- |
-| Clear a project's intermediates | Own projects | Any project |
-| Clear an account's intermediates | Own account | Any account |
-| Clear everyone's intermediates | No | Yes |
-| Force clear referenced intermediates | Own files that only your own documents name | Any authorized scope |
+| Delete a project's intermediates | Own projects | Any project |
+| Delete an account's intermediates | Own account | Any account |
+| Delete everyone's intermediates | No | Yes |
+| Force delete referenced intermediates | Own files that only your own documents name | Any authorized scope |
Cleanup is refused while [image storage maintenance](/features/image-storage-maintenance/) is active.
## Legacy endpoint
-The older `DELETE /api/v1/images/intermediates` route remains available to administrators. It now applies the same safety policy as a normal clear, so it keeps referenced, active and recent images and returns the number of images it deleted. It does not touch videos. `GET /api/v1/images/intermediates` counts exactly the images that route would delete, so the legacy button settles at zero after a clear.
+The older `DELETE /api/v1/images/intermediates` route remains available to administrators. It now applies the same safety policy as a normal delete, so it keeps referenced, active and recent images and returns the number of images it deleted. It does not touch videos. `GET /api/v1/images/intermediates` counts exactly the images that route would delete, so the legacy button settles at zero after it runs.
+
+## Limitations
+
+- Canvas uploads made before the server accepted the project they belong to are stored without a project and are never re-associated with it. They are still protected by saved references and browser holds, but they appear under **Unassigned**.
diff --git a/invokeai/app/api/routers/intermediates.py b/invokeai/app/api/routers/intermediates.py
index 7b84020da1..c43ded658a 100644
--- a/invokeai/app/api/routers/intermediates.py
+++ b/invokeai/app/api/routers/intermediates.py
@@ -8,6 +8,7 @@ from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller
from invokeai.app.services.intermediates.intermediates_common import (
+ BROWSER_HOLD_LEASE_ID_PATTERN,
IntermediatesBrowserHoldRequest,
IntermediatesIdempotencyConflictError,
IntermediatesOperation,
@@ -27,26 +28,6 @@ from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE
intermediates_router = APIRouter(prefix="/v1/intermediates", tags=["intermediates"])
-@intermediates_router.put("/holds/{lease_id}", status_code=status.HTTP_204_NO_CONTENT)
-def replace_intermediates_browser_hold(
- current_user: CurrentUserOrDefault,
- request: IntermediatesBrowserHoldRequest,
- lease_id: str = Path(min_length=1, max_length=64),
-) -> Response:
- """Protect names still held by this account's open browser editor, including undo state."""
- ApiDependencies.invoker.services.intermediates.replace_browser_hold(_caller(current_user), lease_id, request)
- return Response(status_code=status.HTTP_204_NO_CONTENT)
-
-
-@intermediates_router.delete("/holds/{lease_id}", status_code=status.HTTP_204_NO_CONTENT)
-def release_intermediates_browser_hold(
- current_user: CurrentUserOrDefault,
- lease_id: str = Path(min_length=1, max_length=64),
-) -> Response:
- ApiDependencies.invoker.services.intermediates.release_browser_hold(_caller(current_user), lease_id)
- return Response(status_code=status.HTTP_204_NO_CONTENT)
-
-
def _caller(current_user: CurrentUserOrDefault) -> IntermediatesCaller:
return IntermediatesCaller(user_id=current_user.user_id, is_admin=current_user.is_admin)
@@ -162,3 +143,31 @@ def retry_intermediates_operation(
IntermediatesUnavailableError,
) as error:
raise _translate(error)
+
+
+@intermediates_router.put(
+ "/holds/{lease_id}",
+ operation_id="replace_intermediates_browser_hold",
+ status_code=status.HTTP_204_NO_CONTENT,
+)
+def replace_intermediates_browser_hold(
+ current_user: CurrentUserOrDefault,
+ request: IntermediatesBrowserHoldRequest,
+ lease_id: str = Path(min_length=1, max_length=64, pattern=BROWSER_HOLD_LEASE_ID_PATTERN),
+) -> Response:
+ """Protect names still held by this account's open browser editor, including undo state."""
+ ApiDependencies.invoker.services.intermediates.replace_browser_hold(_caller(current_user), lease_id, request)
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
+@intermediates_router.delete(
+ "/holds/{lease_id}",
+ operation_id="release_intermediates_browser_hold",
+ status_code=status.HTTP_204_NO_CONTENT,
+)
+def release_intermediates_browser_hold(
+ current_user: CurrentUserOrDefault,
+ lease_id: str = Path(min_length=1, max_length=64, pattern=BROWSER_HOLD_LEASE_ID_PATTERN),
+) -> Response:
+ ApiDependencies.invoker.services.intermediates.release_browser_hold(_caller(current_user), lease_id)
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
diff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.py
index d5df005396..6ded39f5ed 100644
--- a/invokeai/app/api/routers/session_queue.py
+++ b/invokeai/app/api/routers/session_queue.py
@@ -176,6 +176,7 @@ _REDACTIONS: dict[str, Callable[[], Any]] = {
"user_id": lambda: "redacted",
"user_display_name": lambda: None,
"user_email": lambda: None,
+ "project_id": lambda: None,
"batch_id": lambda: "redacted",
"session_id": lambda: "redacted",
"origin": lambda: None,
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index 71db4893e5..ba2532ad49 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -277,7 +277,7 @@ class BaseInvocation(ABC, BaseModel):
if self.use_cache:
key = services.invocation_cache.create_key(self)
cached_value = services.invocation_cache.get(key)
- if cached_value is not None and services.intermediates is not None:
+ if cached_value is not None:
references = extract_media_references(cached_value.model_dump(mode="json"))
if not references.is_empty() and not services.intermediates.hold_cached_media(
context._data.queue_item.session_id, references
diff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.py
index 4ede34a109..3ec1a1fdeb 100644
--- a/invokeai/app/services/intermediates/intermediates_common.py
+++ b/invokeai/app/services/intermediates/intermediates_common.py
@@ -26,6 +26,14 @@ PREVIEW_TTL_SECONDS = 10 * 60
# stops protecting its media after this long.
BROWSER_HOLD_TTL_SECONDS = 15 * 60
MAX_BROWSER_HOLD_NAMES = 50_000
+# A lease id is `<holder>` or `<holder>.<part>`: one open editor (tab) is one holder, however many
+# parts it splits its hold into.
+BROWSER_HOLD_LEASE_ID_PATTERN = r"^[A-Za-z0-9_-]+(\.[A-Za-z0-9_.-]+)?$"
+# Open editors one account can hold media for at once; past it every lease of the least recently
+# refreshed editor lapses.
+MAX_BROWSER_HOLD_EDITORS_PER_USER = 8
+# A force preview lists at most this many broken documents; `affected_documents_total` counts them all.
+MAX_AFFECTED_DOCUMENTS = 200
MediaName = Annotated[str, Field(min_length=1, max_length=255)]
@@ -159,9 +167,12 @@ class IntermediatesPreview(BaseModel):
default_factory=list,
description=(
"Documents a force clear would break. A non-administrator's force clear keeps media other accounts'"
- " documents name, so these are always the caller's own"
+ " documents name, so these are always the caller's own. Bounded; see `affected_documents_total`"
),
)
+ affected_documents_total: int = Field(
+ default=0, description="How many documents a force clear would break, including any not listed"
+ )
class IntermediatesOperationRequest(BaseModel):
diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.py
index aec6f62b1d..ad9004e868 100644
--- a/invokeai/app/services/intermediates/intermediates_default.py
+++ b/invokeai/app/services/intermediates/intermediates_default.py
@@ -11,7 +11,6 @@ lock. Image and video deletion never hold each other's locks; queue and document
only the database lock.
"""
-import json
import logging
import queue
import threading
@@ -24,6 +23,7 @@ from typing import Callable, Optional, Sequence, cast
from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller, IntermediatesServiceBase
from invokeai.app.services.intermediates.intermediates_common import (
+ MAX_AFFECTED_DOCUMENTS,
PREVIEW_TTL_SECONDS,
RECENT_GRACE_SECONDS,
IntermediatesAffectedDocument,
@@ -50,20 +50,27 @@ from invokeai.app.services.intermediates.intermediates_common import (
)
from invokeai.app.services.intermediates.intermediates_measurement import IntermediatesSizeMeasurer
from invokeai.app.services.intermediates.intermediates_records_sqlite import (
- AffectedReference,
- IntermediateCandidate,
IntermediatesRecordsSqlite,
MediaKind,
- ScopeCounts,
+ OperationReceipt,
+ OperationTarget,
+ ReferenceOwner,
+ ReferenceOwners,
)
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
from invokeai.app.services.shared.media_references import MediaReferenceOwnerKind, MediaReferences
DELETE_BATCH_SIZE = 200
-MAX_RETAINED_OPERATIONS = 100
-MAX_RETAINED_TARGETS = 500_000
+# Receipts and unresolved targets are budgeted per confirming account. Up to the global ceiling,
+# which bounds memory, one account's interrupted cleanups never block another's; past it, ten
+# accounts at their full budget refuse new cleanup for everyone until they retry.
+MAX_RETAINED_OPERATIONS_PER_CALLER = 50
+MAX_RETAINED_TARGETS_PER_CALLER = 100_000
+MAX_RETAINED_TARGETS = 1_000_000
+# Operations run one at a time; the per-account share keeps one account from filling the queue.
MAX_ACTIVE_OPERATIONS = 8
+MAX_ACTIVE_OPERATIONS_PER_CALLER = 2
MAX_OPERATION_TARGETS = 50_000
MAX_PREVIEWS = 200
MAX_PREVIEWS_PER_CALLER = 4
@@ -77,6 +84,19 @@ def _now() -> datetime:
return datetime.now(timezone.utc)
+def _own_references(references: ReferenceOwners, user_id: str) -> ReferenceOwners:
+ """Drops the confirmations of other accounts' documents, so the delete guard keeps their media."""
+ return {name: {owner for owner in owners if owner.user_id == user_id} for name, owners in references.items()}
+
+
+@dataclass
+class _KindImpact:
+ delete: int = 0
+ keep_referenced: int = 0
+ keep_active: int = 0
+ keep_recent: int = 0
+
+
@dataclass
class _Preview:
dto: IntermediatesPreview
@@ -84,7 +104,7 @@ class _Preview:
# Frozen targets with the size known at preview time; sizes are what an operation reclaims.
targets: dict[MediaKind, list[tuple[str, Optional[int]]]]
allowed_user_ids: Optional[frozenset[str]]
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]]
+ confirmed_references: dict[MediaKind, ReferenceOwners]
@dataclass
@@ -93,9 +113,7 @@ class _Operation:
caller: IntermediatesCaller
targets: dict[MediaKind, list[tuple[str, Optional[int]]]]
allowed_user_ids: Optional[frozenset[str]]
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]] = field(
- default_factory=lambda: {"image": {}, "video": {}}
- )
+ confirmed_references: dict[MediaKind, ReferenceOwners] = field(default_factory=lambda: {"image": {}, "video": {}})
# Names whose deletion raised, or that were never attempted; a retry takes exactly these.
unresolved: dict[MediaKind, dict[str, Optional[int]]] = field(default_factory=lambda: {"image": {}, "video": {}})
last_progress_event_at: float = 0.0
@@ -122,35 +140,32 @@ class IntermediatesService(IntermediatesServiceBase):
self._invoker = invoker
self._stop.clear()
self._measurer.reset()
+ stored_operations, failures = self._records.load_operations()
+ for operation_id, error in failures:
+ self._logger.warning(f"Skipping unreadable intermediates operation {operation_id}: {error}")
with self._lock:
- for user_id, preview_id, key, state in self._records.load_operations():
- dto = IntermediatesOperation.model_validate(state["dto"])
- unresolved = {cast(MediaKind, kind): dict(state["unresolved"][kind]) for kind in ("image", "video")}
+ for stored in stored_operations:
+ receipt = stored.receipt
+ dto = receipt.dto
operation = _Operation(
dto=dto,
- caller=IntermediatesCaller(user_id=user_id, is_admin=bool(state["caller_is_admin"])),
+ caller=IntermediatesCaller(user_id=stored.user_id, is_admin=receipt.caller_is_admin),
targets={"image": [], "video": []},
allowed_user_ids=(
- frozenset(state["allowed_user_ids"]) if state["allowed_user_ids"] is not None else None
+ frozenset(receipt.allowed_user_ids) if receipt.allowed_user_ids is not None else None
),
- confirmed_references={
- cast(MediaKind, kind): {
- name: {tuple(ref) for ref in refs}
- for name, refs in state.get("confirmed_references", {}).get(kind, {}).items()
- }
- for kind in ("image", "video")
- },
- unresolved=unresolved,
+ confirmed_references=stored.confirmed_references,
+ unresolved=stored.unresolved,
)
if dto.status in ("pending", "running"):
dto.status = "failed"
dto.error = "Server restarted before cleanup finished; retry the remaining targets"
dto.completed_at = _now()
- self._records.save_operation(dto.operation_id, user_id, self._operation_state(operation))
+ self._records.save_operation(stored.user_id, self._receipt(operation))
self._operations[dto.operation_id] = operation
self._operation_order.append(dto.operation_id)
- if key is not None and preview_id is not None:
- self._idempotency[(user_id, key)] = (preview_id, dto.operation_id)
+ if stored.idempotency_key is not None and stored.preview_id is not None:
+ self._idempotency[(stored.user_id, stored.idempotency_key)] = (stored.preview_id, dto.operation_id)
self._prune_operations_locked()
def stop(self, invoker: Optional[Invoker] = None) -> None:
@@ -290,47 +305,51 @@ class IntermediatesService(IntermediatesServiceBase):
def create_preview(self, request: IntermediatesPreviewRequest, caller: IntermediatesCaller) -> IntermediatesPreview:
scope = request.scope
allowed = self._authorize_scope(scope, caller)
- candidates, has_more_eligible = self._collect_candidates(scope, request.mode)
- counts = self._records.summarize(allowed)
+ selection: Optional[list[IntermediatesScopeTarget]] = None
if scope.kind == "selection":
- selected_rows = {(target.user_id, target.project_id) for target in scope.targets}
- counts = {row: kinds for row, kinds in counts.items() if row in selected_rows}
+ # Duplicate rows would double-count; the order is irrelevant to the SQL.
+ selection = list({(t.user_id, t.project_id): t for t in scope.targets}.values())
+ classified = self._records.classify_scope(
+ user_id=scope.user_id if scope.kind == "owner" else None,
+ targets=selection,
+ mode=request.mode,
+ max_candidates=MAX_OPERATION_TARGETS,
+ )
impact = IntermediatesImpact()
- for kinds in counts.values():
- for kind in ("image", "video"):
- suffix = "images" if kind == "image" else "videos"
- scope_counts = kinds[cast(MediaKind, kind)].counts
- setattr(impact, f"keep_active_{suffix}", getattr(impact, f"keep_active_{suffix}") + scope_counts.active)
- setattr(impact, f"keep_recent_{suffix}", getattr(impact, f"keep_recent_{suffix}") + scope_counts.recent)
- if request.mode == "safe":
- setattr(
- impact,
- f"keep_referenced_{suffix}",
- getattr(impact, f"keep_referenced_{suffix}") + scope_counts.referenced,
- )
+ kind_impacts: dict[MediaKind, _KindImpact] = {"image": _KindImpact(), "video": _KindImpact()}
# Force mode confirms the documents it breaks. Another account's document is never the
# caller's to break unless the caller administers the instance, so its media is kept.
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]] = {"image": {}, "video": {}}
+ confirmed_references: dict[MediaKind, ReferenceOwners] = {"image": {}, "video": {}}
targets: dict[MediaKind, list[tuple[str, Optional[int]]]] = {"image": [], "video": []}
- for kind in ("image", "video"):
- media_kind = cast(MediaKind, kind)
- owners: dict[str, set[tuple[str, str, str]]] = {}
- if request.mode == "force":
- owners = self._records.reference_owners(
- media_kind, [c.name for c in candidates[media_kind] if c.classification == "referenced"]
- )
- for candidate in candidates[media_kind]:
+ for media_kind, kind_impact in kind_impacts.items():
+ counts = classified.counts[media_kind]
+ kind_impact.keep_active = counts.active
+ kind_impact.keep_recent = counts.recent
+ if request.mode == "safe":
+ kind_impact.keep_referenced = counts.referenced
+ owners = classified.reference_owners[media_kind]
+ for candidate in classified.candidates[media_kind]:
references = owners.get(candidate.name, set())
- deletable = candidate.classification == "safe" or (
- request.mode == "force"
- and candidate.classification == "referenced"
- and (caller.is_admin or all(user_id == caller.user_id for _, user_id, _ in references))
- )
- self._tally(impact, media_kind, candidate, deletable, targets)
- if deletable and references:
+ if candidate.classification == "referenced" and not (
+ caller.is_admin or all(owner.user_id == caller.user_id for owner in references)
+ ):
+ kind_impact.keep_referenced += 1
+ continue
+ kind_impact.delete += 1
+ if candidate.file_size_bytes is None:
+ impact.unknown_size_count += 1
+ else:
+ impact.reclaimable_bytes += candidate.file_size_bytes
+ targets[media_kind].append((candidate.name, candidate.file_size_bytes))
+ if references:
confirmed_references[media_kind][candidate.name] = references
- affected = self._describe_affected(confirmed_references) if request.mode == "force" else []
+ images, videos = kind_impacts["image"], kind_impacts["video"]
+ impact.delete_images, impact.delete_videos = images.delete, videos.delete
+ impact.keep_referenced_images, impact.keep_referenced_videos = images.keep_referenced, videos.keep_referenced
+ impact.keep_active_images, impact.keep_active_videos = images.keep_active, videos.keep_active
+ impact.keep_recent_images, impact.keep_recent_videos = images.keep_recent, videos.keep_recent
+ affected, affected_total = self._describe_affected(confirmed_references) if request.mode == "force" else ([], 0)
created = _now()
dto = IntermediatesPreview(
@@ -339,10 +358,11 @@ class IntermediatesService(IntermediatesServiceBase):
scope=scope,
created_at=created,
expires_at=created + timedelta(seconds=PREVIEW_TTL_SECONDS),
- target_rows=self._count_target_rows(scope, counts),
+ target_rows=len(selection) if selection is not None else len(classified.rows),
impact=impact,
- has_more_eligible=has_more_eligible,
+ has_more_eligible=classified.has_more,
affected_documents=affected,
+ affected_documents_total=affected_total,
)
with self._lock:
self._previews[dto.preview_id] = _Preview(
@@ -359,99 +379,48 @@ class IntermediatesService(IntermediatesServiceBase):
"""Returns the accounts the scope may touch, or None for every account."""
if scope.kind == "everyone":
if not caller.is_admin:
- raise IntermediatesScopeForbiddenError("Only administrators can clear everyone's intermediates")
+ raise IntermediatesScopeForbiddenError("Only administrators can delete everyone's intermediates")
return None
if scope.kind == "owner":
if scope.user_id is None:
- raise IntermediatesScopeInvalidError("An owner scope names the account to clear")
+ raise IntermediatesScopeInvalidError("An owner scope names the account whose intermediates to delete")
if scope.user_id != caller.user_id and not caller.is_admin:
- raise IntermediatesScopeForbiddenError("Only administrators can clear another account's intermediates")
+ raise IntermediatesScopeForbiddenError("Only administrators can delete another account's intermediates")
return frozenset({scope.user_id})
if not scope.targets:
raise IntermediatesScopeInvalidError("A selection scope names at least one row")
owners = frozenset(target.user_id for target in scope.targets)
if not caller.is_admin and owners != frozenset({caller.user_id}):
- raise IntermediatesScopeForbiddenError("Only administrators can clear another account's intermediates")
+ raise IntermediatesScopeForbiddenError("Only administrators can delete another account's intermediates")
return owners
- def _collect_candidates(
- self, scope: IntermediatesScope, mode: IntermediatesCleanupMode
- ) -> tuple[dict[MediaKind, list[IntermediateCandidate]], bool]:
- targets: Optional[Sequence[IntermediatesScopeTarget]] = None
- user_id: Optional[str] = None
- if scope.kind == "selection":
- # Duplicate rows would double-count; the order is irrelevant to the SQL.
- targets = list({(t.user_id, t.project_id): t for t in scope.targets}.values())
- elif scope.kind == "owner":
- user_id = scope.user_id
- images = self._records.list_candidates(
- "image", user_id=user_id, targets=targets, max_results=MAX_OPERATION_TARGETS, eligible_mode=mode
- )
- if len(images) > MAX_OPERATION_TARGETS:
- return {"image": images[:MAX_OPERATION_TARGETS], "video": []}, True
- remaining = MAX_OPERATION_TARGETS - len(images)
- videos = self._records.list_candidates(
- "video", user_id=user_id, targets=targets, max_results=remaining, eligible_mode=mode
- )
- has_more = len(videos) > remaining
- return {"image": images, "video": videos[:remaining]}, has_more
-
- @staticmethod
- def _count_target_rows(
- scope: IntermediatesScope, counts: dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]]
- ) -> int:
- """Rows (owner, project) the scope resolved to, counted the same way for every scope kind."""
- if scope.kind == "selection":
- return len({(t.user_id, t.project_id) for t in scope.targets})
- return len(counts)
-
- @staticmethod
- def _tally(
- impact: IntermediatesImpact,
- kind: MediaKind,
- candidate: IntermediateCandidate,
- deletable: bool,
- targets: dict[MediaKind, list[tuple[str, Optional[int]]]],
- ) -> None:
- suffix = "images" if kind == "image" else "videos"
- if deletable:
- setattr(impact, f"delete_{suffix}", getattr(impact, f"delete_{suffix}") + 1)
- if candidate.file_size_bytes is None:
- impact.unknown_size_count += 1
- else:
- impact.reclaimable_bytes += candidate.file_size_bytes
- targets[kind].append((candidate.name, candidate.file_size_bytes))
- else:
- attribute = f"keep_{candidate.classification}_{suffix}"
- setattr(impact, attribute, getattr(impact, attribute) + 1)
-
def _describe_affected(
- self, confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]]
- ) -> list[IntermediatesAffectedDocument]:
- counts: dict[tuple[str, str, str], int] = {}
+ self, confirmed_references: dict[MediaKind, ReferenceOwners]
+ ) -> tuple[list[IntermediatesAffectedDocument], int]:
+ """The documents a force clear breaks, bounded to the first few by kind and name, and how many there are."""
+ counts: dict[ReferenceOwner, int] = defaultdict(int)
for owners in confirmed_references.values():
for refs_for_name in owners.values():
for owner in refs_for_name:
- counts[owner] = counts.get(owner, 0) + 1
- refs = [
- AffectedReference(kind, user_id, owner_id, count) for (kind, user_id, owner_id), count in counts.items()
- ]
- names = self._records.get_document_names(refs)
- users = self._services.users.get_many(sorted({ref.user_id for ref in refs}))
+ counts[owner] += 1
+ names = self._records.get_document_names(counts)
+ ordered = sorted(
+ counts, key=lambda owner: (owner.owner_kind, (names.get(owner) or "").casefold(), owner.owner_id)
+ )[:MAX_AFFECTED_DOCUMENTS]
+ users = self._services.users.get_many(sorted({owner.user_id for owner in ordered}))
documents = [
IntermediatesAffectedDocument(
- kind=cast(MediaReferenceOwnerKind, ref.owner_kind),
- user_id=ref.user_id,
- user_display_name=users[ref.user_id].display_name if ref.user_id in users else None,
- user_email=users[ref.user_id].email if ref.user_id in users else None,
- owner_id=ref.owner_id,
- name=names.get((ref.owner_kind, ref.user_id, ref.owner_id)),
- references=ref.references,
+ kind=cast(MediaReferenceOwnerKind, owner.owner_kind),
+ user_id=owner.user_id,
+ user_display_name=users[owner.user_id].display_name if owner.user_id in users else None,
+ user_email=users[owner.user_id].email if owner.user_id in users else None,
+ owner_id=owner.owner_id,
+ name=names.get(owner),
+ references=counts[owner],
)
- for ref in refs
+ for owner in ordered
]
- documents.sort(key=lambda doc: (doc.kind, (doc.name or "").casefold(), doc.owner_id))
- return documents
+ return documents, len(counts)
def _expire_previews_locked(self, now: datetime, *, keep: Optional[str] = None) -> None:
"""Drops expired previews, then enforces the caps; ``keep`` (the one just created) always survives."""
@@ -503,16 +472,14 @@ class IntermediatesService(IntermediatesServiceBase):
return self._operations[operation_id].dto.model_copy(deep=True)
self._require_cleanup_available()
- if (
- sum(op.dto.status in ("pending", "running") for op in self._operations.values())
- >= MAX_ACTIVE_OPERATIONS
- ):
- raise IntermediatesUnavailableError("Too many cleanup operations are already running")
+ self._require_active_capacity_locked(caller.user_id)
self._expire_previews_locked(_now())
preview = self._previews.get(request.preview_id)
if preview is None or preview.caller_user_id != caller.user_id:
raise IntermediatesPreviewNotFoundError("Preview expired or unknown; request a new one")
- self._require_operation_capacity(len(preview.targets["image"]) + len(preview.targets["video"]))
+ self._require_operation_capacity(
+ caller.user_id, len(preview.targets["image"]) + len(preview.targets["video"])
+ )
# Single use: a second confirmation of the same preview must go through a new preview.
del self._previews[request.preview_id]
@@ -527,9 +494,8 @@ class IntermediatesService(IntermediatesServiceBase):
)
try:
self._records.save_operation(
- operation.dto.operation_id,
caller.user_id,
- self._operation_state(operation),
+ self._receipt(operation),
preview_id=request.preview_id,
idempotency_key=request.idempotency_key,
targets=self._operation_target_rows(operation),
@@ -558,41 +524,48 @@ class IntermediatesService(IntermediatesServiceBase):
raise IntermediatesOperationNotFoundError(operation_id)
if original.dto.status not in ("completed", "failed"):
raise IntermediatesUnavailableError("The operation is still running")
- if original.dto.retried_by_operation_id is not None:
+ existing_retry = (
+ self._operations.get(original.dto.retried_by_operation_id)
+ if original.dto.retried_by_operation_id is not None
+ else None
+ )
+ if existing_retry is not None:
# A duplicated retry request (lost response, double click) must not run the same
# targets twice; the retry that already took them over is the answer.
- existing_retry = self._operations[original.dto.retried_by_operation_id]
if existing_retry.caller.user_id != caller.user_id and not caller.is_admin:
raise IntermediatesUnavailableError("Another account already retried this operation")
return existing_retry.dto.model_copy(deep=True)
self._require_cleanup_available()
- if (
- sum(op.dto.status in ("pending", "running") for op in self._operations.values())
- >= MAX_ACTIVE_OPERATIONS
- ):
- raise IntermediatesUnavailableError("Too many cleanup operations are already running")
+ self._require_active_capacity_locked(caller.user_id)
unresolved = {kind: list(names.items()) for kind, names in original.unresolved.items()}
if not unresolved["image"] and not unresolved["video"]:
raise IntermediatesUnavailableError("The operation has nothing left to retry")
# A retry is authorized as the retrying caller, never as the original one.
self._authorize_scope(original.dto.scope, caller)
- self._require_operation_capacity(len(unresolved["image"]) + len(unresolved["video"]), replacing=original)
+ self._require_operation_capacity(
+ caller.user_id, len(unresolved["image"]) + len(unresolved["video"]), replacing=original
+ )
+ confirmed_references = original.confirmed_references
+ if not caller.is_admin:
+ confirmed_references = {
+ kind: _own_references(references, caller.user_id)
+ for kind, references in confirmed_references.items()
+ }
operation = self._register_operation_locked(
caller=caller,
mode=original.dto.mode,
scope=original.dto.scope,
targets=unresolved,
allowed_user_ids=original.allowed_user_ids,
- confirmed_references=original.confirmed_references,
+ confirmed_references=confirmed_references,
retried_from=operation_id,
)
original.dto.retried_by_operation_id = operation.dto.operation_id
try:
self._records.save_operation(
- operation.dto.operation_id,
caller.user_id,
- self._operation_state(operation),
- linked_operation=(operation_id, self._operation_state(original)),
+ self._receipt(operation),
+ linked_operation=self._receipt(original),
targets=self._operation_target_rows(operation),
)
except Exception:
@@ -614,7 +587,7 @@ class IntermediatesService(IntermediatesServiceBase):
scope: IntermediatesScope,
targets: dict[MediaKind, list[tuple[str, Optional[int]]]],
allowed_user_ids: Optional[frozenset[str]],
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]],
+ confirmed_references: dict[MediaKind, ReferenceOwners],
retried_from: Optional[str],
) -> _Operation:
dto = IntermediatesOperation(
@@ -644,17 +617,17 @@ class IntermediatesService(IntermediatesServiceBase):
return operation
@staticmethod
- def _operation_state(operation: _Operation) -> dict:
- return {
- "dto": operation.dto.model_dump(mode="json"),
- "caller_is_admin": operation.caller.is_admin,
- "allowed_user_ids": sorted(operation.allowed_user_ids) if operation.allowed_user_ids is not None else None,
- }
+ def _receipt(operation: _Operation) -> OperationReceipt:
+ return OperationReceipt(
+ dto=operation.dto,
+ caller_is_admin=operation.caller.is_admin,
+ allowed_user_ids=sorted(operation.allowed_user_ids) if operation.allowed_user_ids is not None else None,
+ )
@staticmethod
- def _operation_target_rows(operation: _Operation) -> list[tuple[str, str, Optional[int], str]]:
+ def _operation_target_rows(operation: _Operation) -> list[OperationTarget]:
return [
- (kind, name, size, json.dumps(sorted(operation.confirmed_references[kind].get(name, set()))))
+ (kind, name, size, operation.confirmed_references[kind].get(name, set()))
for kind, names in operation.unresolved.items()
for name, size in names.items()
]
@@ -666,51 +639,85 @@ class IntermediatesService(IntermediatesServiceBase):
retry = self._operations.get(retry_id) if retry_id is not None else None
return retry is None or retry.dto.status not in ("pending", "running")
- def _require_operation_capacity(self, incoming_targets: int, *, replacing: Optional[_Operation] = None) -> None:
- outstanding = sum(
- len(operation.unresolved["image"]) + len(operation.unresolved["video"])
- for operation in self._operations.values()
- )
- if replacing is not None:
- outstanding -= len(replacing.unresolved["image"]) + len(replacing.unresolved["video"])
- if outstanding + incoming_targets > MAX_RETAINED_TARGETS:
+ def _require_active_capacity_locked(self, caller_user_id: str) -> None:
+ active = [op for op in self._operations.values() if op.dto.status in ("pending", "running")]
+ if sum(op.caller.user_id == caller_user_id for op in active) >= MAX_ACTIVE_OPERATIONS_PER_CALLER:
+ raise IntermediatesUnavailableError("Wait for your running deletions to finish before starting another")
+ if len(active) >= MAX_ACTIVE_OPERATIONS:
+ raise IntermediatesUnavailableError("Too many cleanup operations are already running")
+
+ def _require_operation_capacity(
+ self, caller_user_id: str, incoming_targets: int, *, replacing: Optional[_Operation] = None
+ ) -> None:
+ """Refuses new work past the confirming account's budget; a retry hands its targets over rather than adding."""
+ outstanding = 0
+ caller_outstanding = 0
+ caller_operations: list[_Operation] = []
+ for operation in self._operations.values():
+ if operation is replacing:
+ continue
+ unresolved = len(operation.unresolved["image"]) + len(operation.unresolved["video"])
+ outstanding += unresolved
+ if operation.caller.user_id == caller_user_id:
+ caller_outstanding += unresolved
+ caller_operations.append(operation)
+ if (
+ caller_outstanding + incoming_targets > MAX_RETAINED_TARGETS_PER_CALLER
+ or outstanding + incoming_targets > MAX_RETAINED_TARGETS
+ ):
raise IntermediatesUnavailableError("Retry unresolved cleanup targets before starting more cleanup")
if (
- len(self._operations) >= MAX_RETAINED_OPERATIONS
- and replacing is None
- and not any(self._can_prune_operation_locked(operation) for operation in self._operations.values())
+ replacing is None
+ and len(caller_operations) >= MAX_RETAINED_OPERATIONS_PER_CALLER
+ and not any(self._can_prune_operation_locked(operation) for operation in caller_operations)
):
raise IntermediatesUnavailableError("Retry unresolved cleanup operations before starting more cleanup")
def _prune_operations_locked(self) -> None:
+ """Drops each account's oldest settled receipts past its budget; unresolved ones stay retryable.
+
+ A retry takes the operations it retried with it, even another account's: they point at it
+ and handed it everything they had left.
+ """
+ retained: dict[str, int] = defaultdict(int)
+ for operation in self._operations.values():
+ retained[operation.caller.user_id] += 1
evicted: list[str] = []
- retained_order = list(self._operation_order)
- unresolved_count = sum(
- len(operation.unresolved["image"]) + len(operation.unresolved["video"])
- for operation in self._operations.values()
- )
- while len(retained_order) > MAX_RETAINED_OPERATIONS or unresolved_count > MAX_RETAINED_TARGETS:
- oldest = None
- for operation_id in retained_order:
- candidate = self._operations[operation_id]
- if self._can_prune_operation_locked(candidate):
- oldest = operation_id
+ evicted_set: set[str] = set()
+ for operation_id in self._operation_order:
+ operation = self._operations[operation_id]
+ if (
+ operation_id in evicted_set
+ or retained[operation.caller.user_id] <= MAX_RETAINED_OPERATIONS_PER_CALLER
+ or not self._can_prune_operation_locked(operation)
+ ):
+ continue
+ chain = [operation]
+ previous_id = operation.dto.retried_from_operation_id
+ while previous_id is not None and previous_id not in evicted_set:
+ previous = self._operations.get(previous_id)
+ if previous is None:
break
- if oldest is None:
- break
- retained_order.remove(oldest)
- removed = self._operations[oldest]
- unresolved_count -= len(removed.unresolved["image"]) + len(removed.unresolved["video"])
- evicted.append(oldest)
+ chain.append(previous)
+ previous_id = previous.dto.retried_from_operation_id
+ if not all(self._can_prune_operation_locked(link) for link in chain):
+ continue
+ for link in chain:
+ retained[link.caller.user_id] -= 1
+ evicted.append(link.dto.operation_id)
+ evicted_set.add(link.dto.operation_id)
+ if not evicted:
+ return
try:
self._records.delete_operations(evicted)
except Exception as error:
self._logger.warning(f"Could not prune old intermediates operations: {error}")
return
- self._operation_order = retained_order
+ self._operation_order = [
+ operation_id for operation_id in self._operation_order if operation_id not in evicted_set
+ ]
for operation_id in evicted:
self._operations.pop(operation_id)
- evicted_set = set(evicted)
self._idempotency = {k: v for k, v in self._idempotency.items() if v[1] not in evicted_set}
def _enqueue(self, operation: _Operation) -> None:
@@ -746,7 +753,7 @@ class IntermediatesService(IntermediatesServiceBase):
return deleted
def count_safe_images(self, caller: IntermediatesCaller) -> int:
- counts = self._records.summarize(None if caller.is_admin else [caller.user_id])
+ counts = self._records.summarize(None if caller.is_admin else [caller.user_id], kinds=("image",))
return sum(kinds["image"].counts.safe for kinds in counts.values())
# endregion
@@ -756,7 +763,12 @@ class IntermediatesService(IntermediatesServiceBase):
def _worker_loop(self) -> None:
while not self._stop.is_set():
try:
- operation_id = self._pending.get(timeout=0.5)
+ # Due measurement only takes the turns operations leave free, so it polls the queue
+ # instead of waiting on it.
+ if self._measurer.is_due():
+ operation_id = self._pending.get_nowait()
+ else:
+ operation_id = self._pending.get(timeout=0.5)
except queue.Empty:
if self._measurer.is_due():
self._measurer.measure_once()
@@ -784,36 +796,37 @@ class IntermediatesService(IntermediatesServiceBase):
with self._lock:
operation.dto.status = "running"
operation.dto.started_at = _now()
- self._records.save_operation(
- operation.dto.operation_id, operation.caller.user_id, self._operation_state(operation)
- )
+ self._records.save_operation(operation.caller.user_id, self._receipt(operation))
self._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))
deleters: dict[MediaKind, Callable[[list[str], IntermediateDeleteGuard], IntermediateDeleteResult]] = {
"image": self._services.images.delete_intermediates_by_names,
"video": self._services.videos.delete_intermediates_by_names,
}
- for kind in ("image", "video"):
- media_kind = cast(MediaKind, kind)
+ for media_kind, deleter in deleters.items():
targets = operation.targets[media_kind]
- guard = self._records.make_delete_guard(
- media_kind,
- mode=operation.dto.mode,
- allowed_user_ids=operation.allowed_user_ids,
- confirmed_references=operation.confirmed_references[media_kind],
- )
for start in range(0, len(targets), DELETE_BATCH_SIZE):
batch = targets[start : start + DELETE_BATCH_SIZE]
- halt = self._halt_reason(operation)
+ halt, is_admin = self._batch_authority(operation)
if halt is not None:
self._finish(operation, error=halt)
return
sizes = dict(batch)
names = [name for name, _ in batch]
+ confirmed = operation.confirmed_references[media_kind]
+ batch_references = {name: confirmed[name] for name in names if name in confirmed}
+ if not is_admin:
+ batch_references = _own_references(batch_references, operation.caller.user_id)
+ guard = self._records.make_delete_guard(
+ media_kind,
+ mode=operation.dto.mode,
+ allowed_user_ids=operation.allowed_user_ids,
+ confirmed_references=batch_references,
+ )
try:
- result = deleters[media_kind](names, guard)
+ result = deleter(names, guard)
except Exception as error:
- self._logger.error(f"Intermediates cleanup batch failed ({kind}): {error}", exc_info=True)
+ self._logger.error(f"Intermediates cleanup batch failed ({media_kind}): {error}", exc_info=True)
self._record_batch(operation, media_kind, batch, deleted=[], deferred=[], failed=names, sizes=sizes)
continue
self._record_batch(
@@ -827,24 +840,26 @@ class IntermediatesService(IntermediatesServiceBase):
)
self._finish(operation, error=None)
- def _halt_reason(self, operation: _Operation) -> Optional[str]:
+ def _batch_authority(self, operation: _Operation) -> tuple[Optional[str], bool]:
+ """Why the next batch must not run, if it must not, and whether the confirmer administers the instance now."""
if self._stop.is_set():
- return "The server is shutting down"
+ return "The server is shutting down", False
image_moves = getattr(self._services, "image_moves", None)
if image_moves is not None and image_moves.is_maintenance_active():
- return "Image storage maintenance started"
+ return "Image storage maintenance started", False
# Single-user mode has no accounts to re-check: every request is the local administrator,
# and the `system` row that names it is deliberately not an admin.
if not self._services.configuration.multiuser:
- return None
+ return None, operation.caller.is_admin
# Authorization is re-read per batch: an account demoted, deactivated or deleted
- # mid-operation stops deleting at the next batch boundary.
+ # mid-operation stops deleting at the next batch boundary, and a demoted one no longer
+ # breaks other accounts' documents even inside its own scope.
user = self._services.users.get(operation.caller.user_id)
if user is None or not user.is_active:
- return "The confirming account is no longer active"
+ return "The confirming account is no longer active", False
if operation.allowed_user_ids != frozenset({operation.caller.user_id}) and not user.is_admin:
- return "The confirming account no longer administers this instance"
- return None
+ return "The confirming account no longer administers this instance", False
+ return None, operation.caller.is_admin and user.is_admin
def _record_batch(
self,
@@ -857,18 +872,13 @@ class IntermediatesService(IntermediatesServiceBase):
failed: Sequence[str],
sizes: dict[str, Optional[int]],
) -> None:
- suffix = "images" if kind == "image" else "videos"
deleted_set = set(deleted)
deferred_set = set(deferred)
failed_set = set(failed)
with self._lock:
progress = operation.dto.progress
names = [name for name, _ in batch]
- setattr(progress, f"processed_{suffix}", getattr(progress, f"processed_{suffix}") + len(names))
- setattr(progress, f"deleted_{suffix}", getattr(progress, f"deleted_{suffix}") + len(deleted_set))
- setattr(progress, f"failed_{suffix}", getattr(progress, f"failed_{suffix}") + len(failed_set))
retained = len(names) - len(deleted_set) - len(failed_set)
- setattr(progress, f"retained_{suffix}", getattr(progress, f"retained_{suffix}") + retained)
for name in deleted_set:
if name in deferred_set:
progress.pending_disk_cleanup += 1
@@ -883,11 +893,21 @@ class IntermediatesService(IntermediatesServiceBase):
if name not in failed_set:
unresolved.pop(name, None)
operation.confirmed_references[kind].pop(name, None)
- setattr(progress, f"unresolved_{suffix}", len(unresolved))
+ if kind == "image":
+ progress.processed_images += len(names)
+ progress.deleted_images += len(deleted_set)
+ progress.failed_images += len(failed_set)
+ progress.retained_images += retained
+ progress.unresolved_images = len(unresolved)
+ else:
+ progress.processed_videos += len(names)
+ progress.deleted_videos += len(deleted_set)
+ progress.failed_videos += len(failed_set)
+ progress.retained_videos += retained
+ progress.unresolved_videos = len(unresolved)
self._records.save_operation(
- operation.dto.operation_id,
operation.caller.user_id,
- self._operation_state(operation),
+ self._receipt(operation),
resolved_targets=(kind, [name for name in names if name not in failed_set]),
)
# Progress events are coalesced; the final state always goes out from `_finish`.
@@ -906,9 +926,7 @@ class IntermediatesService(IntermediatesServiceBase):
# Only the unresolved names matter after this point; the frozen list is the bulk of an
# operation's memory and would otherwise live for as long as the operation is retained.
operation.targets = {"image": [], "video": []}
- self._records.save_operation(
- operation.dto.operation_id, operation.caller.user_id, self._operation_state(operation)
- )
+ self._records.save_operation(operation.caller.user_id, self._receipt(operation))
self._prune_operations_locked()
snapshot = operation.dto.model_copy(deep=True)
self._services.events.emit_intermediates_operation_changed(snapshot)
diff --git a/invokeai/app/services/intermediates/intermediates_measurement.py b/invokeai/app/services/intermediates/intermediates_measurement.py
index 21f04f8d52..5fd08c1809 100644
--- a/invokeai/app/services/intermediates/intermediates_measurement.py
+++ b/invokeai/app/services/intermediates/intermediates_measurement.py
@@ -90,9 +90,9 @@ class IntermediatesSizeMeasurer:
# written before measuring it. Wake after the minimum age has elapsed.
retry_young = True
if remaining:
+ # Batches hold the database lock only for their reads and one write; the file stats
+ # between them leave it free for generation and saves.
self._requested.set()
- # Yield the database lock between batches so generation and saves keep flowing.
- time.sleep(0.05)
elif retry_young:
self._due_at = time.monotonic() + MEASURE_MIN_AGE_SECONDS
except Exception as error:
diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
index f25ad90cf8..30a0edd503 100644
--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py
+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
@@ -20,15 +20,21 @@ import re
import sqlite3
from collections import defaultdict
from dataclasses import dataclass, field
-from typing import Collection, Iterable, Literal, Optional, Sequence, cast
+from datetime import datetime, timedelta, timezone
+from typing import Collection, Iterable, Iterator, Literal, NamedTuple, Optional, Sequence, cast
+
+from pydantic import BaseModel
from invokeai.app.services.intermediates.intermediates_common import (
BROWSER_HOLD_TTL_SECONDS,
+ MAX_BROWSER_HOLD_EDITORS_PER_USER,
RECENT_GRACE_SECONDS,
IntermediatesCleanupMode,
IntermediatesKindCounts,
+ IntermediatesOperation,
IntermediatesScopeTarget,
)
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard
from invokeai.app.services.shared.media_references import IMAGE_NAME_KEYS, VIDEO_NAME_KEYS, MediaReferences
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -74,14 +80,63 @@ _TABLES: dict[MediaKind, tuple[str, str, str]] = {
}
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _sql_timestamp(moment: datetime) -> str:
+ """The text `STRFTIME('%Y-%m-%d %H:%M:%f', ...)` stores, so bound instants compare with stored ones as strings."""
+ return moment.strftime("%Y-%m-%d %H:%M:%S.") + f"{moment.microsecond // 1000:03d}"
+
+
+class _Clock(NamedTuple):
+ """One instant for every statement of a classification: SQLite fixes `'NOW'` per statement, not per transaction."""
+
+ now: str
+ recent_cutoff: str
+
+
+def _clock() -> _Clock:
+ now = _utc_now()
+ return _Clock(_sql_timestamp(now), _sql_timestamp(now - timedelta(seconds=RECENT_GRACE_SECONDS)))
+
+
+def _lease_holder(lease_id: str) -> str:
+ """The editor a lease belongs to: one tab holds several leases named `<holder>.<part>`."""
+ return lease_id.split(".", 1)[0]
+
+
+_HOLDER_SQL = "CASE WHEN INSTR(lease_id, '.') > 0 THEN SUBSTR(lease_id, 1, INSTR(lease_id, '.') - 1) ELSE lease_id END"
+
+
+class ReferenceOwner(NamedTuple):
+ """A saved document naming a media item, as `media_references` keys it."""
+
+ owner_kind: str
+ user_id: str
+ owner_id: str
+
+
+# Media name → the documents naming it.
+ReferenceOwners = dict[str, set[ReferenceOwner]]
+
+
@dataclass(frozen=True)
class IntermediateCandidate:
name: str
classification: Classification
file_size_bytes: Optional[int]
- user_id: str
- # The row the candidate belongs to; None for the owner's unassigned row.
- project_id: Optional[str]
+
+
+def _add_count(counts: IntermediatesKindCounts, classification: Classification, n: int) -> None:
+ if classification == "safe":
+ counts.safe += n
+ elif classification == "referenced":
+ counts.referenced += n
+ elif classification == "active":
+ counts.active += n
+ else:
+ counts.recent += n
@dataclass
@@ -94,27 +149,60 @@ class ScopeCounts:
unknown_size_count: int = 0
-@dataclass(frozen=True)
-class AffectedReference:
- owner_kind: str
+@dataclass
+class ScopeClassification:
+ """A preview's scope classified once, on one transaction, so its counts and targets agree."""
+
+ # (owner, project) rows holding any intermediate in scope.
+ rows: set[tuple[str, Optional[str]]] = field(default_factory=set)
+ counts: dict[MediaKind, IntermediatesKindCounts] = field(
+ default_factory=lambda: {"image": IntermediatesKindCounts(), "video": IntermediatesKindCounts()}
+ )
+ # Eligible intermediates, bounded; ``has_more`` says whether the bound cut any off.
+ candidates: dict[MediaKind, list[IntermediateCandidate]] = field(default_factory=lambda: {"image": [], "video": []})
+ has_more: bool = False
+ # Documents naming each referenced candidate; only read for a force clear.
+ reference_owners: dict[MediaKind, ReferenceOwners] = field(default_factory=lambda: {"image": {}, "video": {}})
+
+
+class OperationReceipt(BaseModel):
+ """The persisted receipt of an operation (`intermediates_operations.state_json`)."""
+
+ dto: IntermediatesOperation
+ caller_is_admin: bool
+ allowed_user_ids: Optional[list[str]]
+
+
+@dataclass
+class StoredOperation:
+ """An operation restored at startup: its receipt and the targets it left unresolved."""
+
user_id: str
- owner_id: str
- references: int
+ preview_id: Optional[str]
+ idempotency_key: Optional[str]
+ receipt: OperationReceipt
+ unresolved: dict[MediaKind, dict[str, Optional[int]]]
+ confirmed_references: dict[MediaKind, ReferenceOwners]
+
+
+# (kind, name, size, confirmed reference owners) of one unresolved operation target.
+OperationTarget = tuple[MediaKind, str, Optional[int], set[ReferenceOwner]]
class IntermediatesRecordsSqlite:
def __init__(self, db: SqliteDatabase) -> None:
self._db = db
# Media names an active queue item's session names, keyed by item id and stamped with the
- # row's status and monotonic session revision: a session rewritten while the item stays
- # active (a workflow-call parent resuming with its child's outputs) is re-scanned. Entries
- # live as long as the item is active. This cache is derived from committed
- # rows only, so it is safe across a rolled-back transaction; the temp table is not, which is
- # why it is rebuilt on every call rather than skipped on an unchanged set.
- self._active_inputs: dict[int, tuple[str, set[str], set[str]]] = {}
+ # row's session revision, which a trigger bumps on every session rewrite: a session
+ # rewritten while the item stays active (a workflow-call parent resuming with its child's
+ # outputs) is re-scanned, a status change alone is not. Entries live as long as the item is
+ # active. This cache is derived from committed rows only, so it is safe across a
+ # rolled-back transaction; the temp table is not, which is why it is rebuilt on every call
+ # rather than skipped on an unchanged set.
+ self._active_inputs: dict[int, tuple[int, set[str], set[str]]] = {}
@staticmethod
- def _prepare_session_holds(cursor: sqlite3.Cursor) -> None:
+ def _prepare_session_holds(cursor: sqlite3.Cursor, clock: _Clock) -> None:
# These holds share the cache's process lifetime. After restart the cache is empty and
# recovered queue sessions protect their serialized inputs through the normal scan.
# A cache hit reuses an old row, so the recency grace a fresh output gets is counted from
@@ -125,20 +213,18 @@ class IntermediatesRecordsSqlite:
"WITHOUT ROWID;"
)
cursor.execute(
- "UPDATE temp.intermediates_session_media SET released_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') "
+ "UPDATE temp.intermediates_session_media SET released_at = ? "
"WHERE released_at IS NULL AND session_id NOT IN "
- f"(SELECT session_id FROM ({_protected_queue_items_sql()}));"
- )
- cursor.execute(
- "DELETE FROM temp.intermediates_session_media "
- f"WHERE released_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds');"
+ f"(SELECT session_id FROM ({_protected_queue_items_sql()}));",
+ (clock.now,),
)
+ cursor.execute("DELETE FROM temp.intermediates_session_media WHERE released_at <= ?;", (clock.recent_cutoff,))
def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:
if references.is_empty():
return True
with self._db.transaction() as cursor:
- self._prepare_session_holds(cursor)
+ self._prepare_session_holds(cursor, _clock())
statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)
cursor.execute(
f"SELECT 1 FROM session_queue WHERE session_id = ? AND status IN ({statuses});", (session_id,)
@@ -192,6 +278,29 @@ class IntermediatesRecordsSqlite:
""",
(user_id, lease_id, kind, user_id),
)
+ # Past the cap, every lease of the editors refreshed longest ago stops protecting its
+ # media; an editor that is still open restores its leases on its next refresh. Leases
+ # are grouped on the user's primary-key range first, so only their ids reach the holder
+ # grouping.
+ cursor.execute(
+ f"""--sql
+ WITH leases AS (
+ SELECT lease_id, {_HOLDER_SQL} AS holder, MAX(expires_at) AS refreshed
+ FROM intermediates_browser_holds
+ WHERE user_id = ?
+ GROUP BY lease_id
+ ), lapsed AS (
+ SELECT holder FROM leases
+ WHERE holder != ?
+ GROUP BY holder
+ ORDER BY MAX(refreshed) DESC, holder
+ LIMIT -1 OFFSET ?
+ )
+ DELETE FROM intermediates_browser_holds
+ WHERE user_id = ? AND lease_id IN (SELECT lease_id FROM leases WHERE holder IN lapsed);
+ """,
+ (user_id, _lease_holder(lease_id), MAX_BROWSER_HOLD_EDITORS_PER_USER - 1, user_id),
+ )
def release_browser_hold(self, user_id: str, lease_id: str) -> None:
with self._db.transaction() as cursor:
@@ -199,7 +308,12 @@ class IntermediatesRecordsSqlite:
"DELETE FROM intermediates_browser_holds WHERE user_id = ? AND lease_id = ?;", (user_id, lease_id)
)
- def load_operations(self) -> list[tuple[str, Optional[str], Optional[str], dict]]:
+ def load_operations(self) -> tuple[list[StoredOperation], list[tuple[str, Exception]]]:
+ """Every persisted operation, and the ids of rows that could not be read with why.
+
+ An unreadable row is reported rather than raised, so one bad receipt cannot stop startup;
+ its rows stay in place for inspection.
+ """
with self._db.transaction() as cursor:
cursor.execute(
"SELECT operation_id, caller_user_id, preview_id, idempotency_key, state_json "
@@ -213,31 +327,55 @@ class IntermediatesRecordsSqlite:
targets: dict[str, list[tuple[str, str, Optional[int], str]]] = defaultdict(list)
for operation_id, kind, name, size, refs in cursor.fetchall():
targets[str(operation_id)].append((str(kind), str(name), size, str(refs)))
- loaded: list[tuple[str, Optional[str], Optional[str], dict]] = []
- for operation_id, user, preview, key, state_json in operations:
- state = json.loads(state_json)
- state["unresolved"] = {"image": {}, "video": {}}
- state["confirmed_references"] = {"image": {}, "video": {}}
+ loaded: list[StoredOperation] = []
+ failures: list[tuple[str, Exception]] = []
+ for operation_id, user, preview, key, state_json in operations:
+ try:
+ stored = StoredOperation(
+ user_id=str(user),
+ preview_id=preview,
+ idempotency_key=key,
+ receipt=OperationReceipt.model_validate_json(state_json),
+ unresolved={"image": {}, "video": {}},
+ confirmed_references={"image": {}, "video": {}},
+ )
for kind, name, size, refs_json in targets.get(str(operation_id), []):
- state["unresolved"][kind][name] = size
- refs = json.loads(refs_json)
+ if kind not in ("image", "video"):
+ raise ValueError(f"Unknown media kind {kind!r}")
+ media_kind = cast(MediaKind, kind)
+ stored.unresolved[media_kind][name] = size
+ refs = {ReferenceOwner(*ref) for ref in json.loads(refs_json)}
if refs:
- state["confirmed_references"][kind][name] = refs
- loaded.append((str(user), preview, key, state))
- return loaded
+ stored.confirmed_references[media_kind][name] = refs
+ except (ValueError, TypeError) as error:
+ failures.append((str(operation_id), error))
+ continue
+ loaded.append(stored)
+ return loaded, failures
def save_operation(
self,
- operation_id: str,
caller_user_id: str,
- state: dict,
+ receipt: OperationReceipt,
*,
preview_id: Optional[str] = None,
idempotency_key: Optional[str] = None,
- linked_operation: Optional[tuple[str, dict]] = None,
- targets: Optional[Sequence[tuple[str, str, Optional[int], str]]] = None,
- resolved_targets: Optional[tuple[str, Sequence[str]]] = None,
+ linked_operation: Optional[OperationReceipt] = None,
+ targets: Optional[Sequence[OperationTarget]] = None,
+ resolved_targets: Optional[tuple[MediaKind, Sequence[str]]] = None,
) -> None:
+ operation_id = receipt.dto.operation_id
+ state = receipt.model_dump(mode="json")
+ target_rows = (
+ [(operation_id, kind, name, size, json.dumps(sorted(refs))) for kind, name, size, refs in targets]
+ if targets is not None
+ else None
+ )
+ linked = (
+ (linked_operation.dto.operation_id, linked_operation.model_dump_json())
+ if linked_operation is not None
+ else None
+ )
with self._db.transaction() as cursor:
cursor.execute(
"INSERT INTO intermediates_operations "
@@ -253,11 +391,11 @@ class IntermediatesRecordsSqlite:
state["dto"]["created_at"],
),
)
- if targets is not None:
+ if target_rows is not None:
cursor.executemany(
"INSERT INTO intermediates_operation_targets "
"(operation_id, media_kind, media_name, size_bytes, confirmed_refs_json) VALUES (?, ?, ?, ?, ?);",
- [(operation_id, kind, name, size, refs) for kind, name, size, refs in targets],
+ target_rows,
)
if resolved_targets is not None:
kind, names = resolved_targets
@@ -266,11 +404,11 @@ class IntermediatesRecordsSqlite:
"WHERE operation_id = ? AND media_kind = ? AND media_name = ?;",
[(operation_id, kind, name) for name in names],
)
- if linked_operation is not None:
- linked_id, linked_state = linked_operation
+ if linked is not None:
+ linked_id, linked_state_json = linked
cursor.execute(
"UPDATE intermediates_operations SET state_json = ? WHERE operation_id = ?;",
- (json.dumps(linked_state), linked_id),
+ (linked_state_json, linked_id),
)
cursor.execute("DELETE FROM intermediates_operation_targets WHERE operation_id = ?;", (linked_id,))
@@ -290,6 +428,7 @@ class IntermediatesRecordsSqlite:
@staticmethod
def _classification_sql(kind: MediaKind) -> str:
+ """Binds a `_Clock`'s two fields, in order, ahead of any later parameters of the statement."""
table, name_column, _ = _TABLES[kind]
return f"""
CASE
@@ -301,9 +440,9 @@ class IntermediatesRecordsSqlite:
) OR EXISTS (
SELECT 1 FROM intermediates_browser_holds h
WHERE h.media_kind = '{kind}' AND h.media_name = m.{name_column}
- AND h.expires_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')
+ AND h.expires_at > ?
) THEN 'active'
- WHEN m.created_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds')
+ WHEN m.created_at > ?
OR m.{name_column} IN (
SELECT name FROM temp.intermediates_session_media
WHERE kind = '{kind}' AND released_at IS NOT NULL
@@ -315,13 +454,14 @@ class IntermediatesRecordsSqlite:
END
"""
- def _prepare(self, cursor: sqlite3.Cursor) -> None:
- """Makes the transaction's view of active work current.
+ def _prepare(self, cursor: sqlite3.Cursor) -> _Clock:
+ """Makes the transaction's view of active work current, and returns the instant its classifications use.
Runs on the caller's transaction so a classification and the enqueue it might race are
ordered by the database lock, never by a stale cache.
"""
- self._prepare_session_holds(cursor)
+ clock = _clock()
+ self._prepare_session_holds(cursor, clock)
cursor.execute(
"""--sql
CREATE TEMP TABLE IF NOT EXISTS intermediates_active_media (
@@ -333,11 +473,11 @@ class IntermediatesRecordsSqlite:
)
cursor.execute(
f"""--sql
- SELECT item_id, status || ':' || COALESCE(session_revision, 0)
+ SELECT item_id, COALESCE(session_revision, 0)
FROM ({_protected_queue_items_sql()});
"""
)
- active = {cast(int, row[0]): str(row[1]) for row in cursor.fetchall()}
+ active = {cast(int, row[0]): cast(int, row[1]) for row in cursor.fetchall()}
for stale in [item_id for item_id in self._active_inputs if item_id not in active]:
del self._active_inputs[stale]
@@ -351,9 +491,7 @@ class IntermediatesRecordsSqlite:
placeholders = ",".join("?" for _ in chunk)
cursor.execute(
f"""--sql
- SELECT item_id,
- status || ':' || COALESCE(session_revision, 0),
- session
+ SELECT item_id, COALESCE(session_revision, 0), session
FROM session_queue WHERE item_id IN ({placeholders});
""",
chunk,
@@ -361,7 +499,7 @@ class IntermediatesRecordsSqlite:
for item_id, stamp, session_json in cursor.fetchall():
session_text = session_json if isinstance(session_json, str) else ""
self._active_inputs[cast(int, item_id)] = (
- str(stamp),
+ cast(int, stamp),
set(_IMAGE_NAME_RE.findall(session_text)),
set(_VIDEO_NAME_RE.findall(session_text)),
)
@@ -379,62 +517,89 @@ class IntermediatesRecordsSqlite:
"INSERT OR IGNORE INTO temp.intermediates_active_media (kind, name) "
"SELECT kind, name FROM temp.intermediates_session_media WHERE released_at IS NULL;"
)
+ return clock
# endregion
# region summary
- def summarize(
- self, user_ids: Optional[Collection[str]]
- ) -> dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]]:
- """Aggregates the intermediates of ``user_ids`` (None: everyone) by (owner, project) and classification.
+ @classmethod
+ def _scoped_sql(cls, kind: MediaKind) -> str:
+ """Every intermediate of ``kind`` with its row and classification; callers append ``AND`` scope filters.
- Media whose project no longer exists, or that never had one, fold into the owner's
- unassigned row (``project_id`` None).
+ Media whose project no longer exists, or that never had one, belong to the owner's
+ unassigned row (``project_key`` NULL).
+ """
+ table, name_column, _ = _TABLES[kind]
+ return f"""
+ SELECT m.{name_column} AS name, m.user_id AS user_id,
+ CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END AS project_key,
+ m.file_size_bytes AS file_size_bytes,
+ {cls._classification_sql(kind)} AS cls
+ FROM {table} m
+ LEFT JOIN projects p ON p.user_id = m.user_id AND p.project_id = m.project_id
+ WHERE m.is_intermediate = TRUE
"""
+
+ @classmethod
+ def _aggregate(
+ cls, cursor: sqlite3.Cursor, clock: _Clock, kind: MediaKind, scope_clause: str, params: Sequence[object]
+ ) -> Iterator[tuple[str, Optional[str], Classification, int, int, int]]:
+ """(owner, project, classification, count, measured bytes, unmeasured count) groups within a scope."""
+ cursor.execute(
+ f"""--sql
+ SELECT user_id, project_key, cls, COUNT(*),
+ SUM(COALESCE(file_size_bytes, 0)),
+ SUM(CASE WHEN file_size_bytes IS NULL THEN 1 ELSE 0 END)
+ FROM ({cls._scoped_sql(kind)} {scope_clause})
+ GROUP BY user_id, project_key, cls;
+ """,
+ [*clock, *params],
+ )
+ for owner, project_key, classification, n, total_bytes, unknown in cursor.fetchall():
+ yield (
+ cast(str, owner),
+ cast(Optional[str], project_key),
+ cast(Classification, classification),
+ cast(int, n),
+ cast(int, total_bytes),
+ cast(int, unknown),
+ )
+
+ def summarize(
+ self, user_ids: Optional[Collection[str]], kinds: Sequence[MediaKind] = ("image", "video")
+ ) -> dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]]:
+ """Aggregates the ``kinds`` intermediates of ``user_ids`` (None: everyone) by (owner, project) and classification."""
rows: dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]] = defaultdict(
lambda: {"image": ScopeCounts(), "video": ScopeCounts()}
)
owners = sorted(user_ids) if user_ids is not None else None
# Owner chunks partition the GROUP BY, so their rows never need merging.
- owner_chunks: list[Optional[list[str]]] = (
- [owners[start : start + _MAX_SQL_VARIABLES] for start in range(0, len(owners), _MAX_SQL_VARIABLES)]
+ clauses: list[tuple[str, list[object]]] = (
+ [
+ (f"AND m.user_id IN ({','.join('?' for _ in chunk)})", list(chunk))
+ for chunk in (
+ owners[start : start + _MAX_SQL_VARIABLES] for start in range(0, len(owners), _MAX_SQL_VARIABLES)
+ )
+ ]
if owners is not None
- else [None]
+ else [("", [])]
)
with self._db.transaction() as cursor:
- self._prepare(cursor)
- for kind, chunk in ((kind, chunk) for kind in ("image", "video") for chunk in owner_chunks):
- table, _, _ = _TABLES[cast(MediaKind, kind)]
- owner_filter = f"AND m.user_id IN ({','.join('?' for _ in chunk)})" if chunk is not None else ""
- params: list[object] = list(chunk) if chunk is not None else []
- cursor.execute(
- f"""--sql
- SELECT user_id, project_key, cls, COUNT(*) AS n,
- SUM(COALESCE(file_size_bytes, 0)) AS bytes,
- SUM(CASE WHEN file_size_bytes IS NULL THEN 1 ELSE 0 END) AS unknown
- FROM (
- SELECT m.user_id AS user_id,
- CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END AS project_key,
- m.file_size_bytes AS file_size_bytes,
- {self._classification_sql(cast(MediaKind, kind))} AS cls
- FROM {table} m
- LEFT JOIN projects p ON p.user_id = m.user_id AND p.project_id = m.project_id
- WHERE m.is_intermediate = TRUE {owner_filter}
- )
- GROUP BY user_id, project_key, cls;
- """,
- params,
- )
- for owner, project_key, cls, n, total_bytes, unknown in cursor.fetchall():
- scope = rows[(cast(str, owner), cast(Optional[str], project_key))][cast(MediaKind, kind)]
- setattr(scope.counts, cls, cast(int, n))
- if cls == "safe":
- scope.safe_bytes += cast(int, total_bytes)
- scope.unknown_size_count += cast(int, unknown)
- elif cls == "referenced":
- scope.referenced_bytes += cast(int, total_bytes)
- scope.unknown_size_count += cast(int, unknown)
+ clock = self._prepare(cursor)
+ for kind in kinds:
+ for clause, params in clauses:
+ for owner, project_key, cls, n, total_bytes, unknown in self._aggregate(
+ cursor, clock, kind, clause, params
+ ):
+ scope = rows[(owner, project_key)][kind]
+ _add_count(scope.counts, cls, n)
+ if cls == "safe":
+ scope.safe_bytes += total_bytes
+ scope.unknown_size_count += unknown
+ elif cls == "referenced":
+ scope.referenced_bytes += total_bytes
+ scope.unknown_size_count += unknown
return dict(rows)
def get_projects(self, user_id: Optional[str]) -> dict[tuple[str, str], tuple[str, Optional[str]]]:
@@ -518,6 +683,22 @@ class IntermediatesRecordsSqlite:
# region candidates
+ @classmethod
+ def _scope_clauses(
+ cls, *, user_id: Optional[str], targets: Optional[Sequence[IntermediatesScopeTarget]]
+ ) -> list[tuple[str, list[object]]]:
+ """``AND`` filters (with their parameters) that together cover a scope; each stays under the variable limit."""
+ if targets is not None:
+ clauses: list[tuple[str, list[object]]] = []
+ for start in range(0, len(targets), _TARGETS_PER_STATEMENT):
+ predicate, params = cls._scope_predicate(targets[start : start + _TARGETS_PER_STATEMENT])
+ if predicate:
+ clauses.append((f"AND ({predicate})", params))
+ return clauses
+ if user_id is not None:
+ return [("AND m.user_id = ?", [user_id])]
+ return [("", [])]
+
@staticmethod
def _scope_predicate(targets: Sequence[IntermediatesScopeTarget]) -> tuple[str, list[object]]:
clauses: list[str] = []
@@ -531,65 +712,49 @@ class IntermediatesRecordsSqlite:
params.extend((target.user_id, target.project_id))
return " OR ".join(clauses), params
- def list_candidates(
+ def classify_scope(
self,
- kind: MediaKind,
*,
user_id: Optional[str],
targets: Optional[Sequence[IntermediatesScopeTarget]],
- max_results: Optional[int] = None,
- eligible_mode: Optional[IntermediatesCleanupMode] = None,
- ) -> list[IntermediateCandidate]:
- """Every intermediate in scope with its classification, for freezing a preview.
+ mode: IntermediatesCleanupMode,
+ max_candidates: int,
+ ) -> ScopeClassification:
+ """Counts every intermediate in scope and freezes up to ``max_candidates`` eligible ones, images first.
``targets`` narrows to selected rows; otherwise ``user_id`` narrows to an owner, and None
- means everyone.
+ means everyone. One transaction, one instant and one view of active work serve every figure, so a
+ preview's kept counts and its targets cannot disagree.
"""
- table, name_column, _ = _TABLES[kind]
- candidates: list[IntermediateCandidate] = []
+ clauses = self._scope_clauses(user_id=user_id, targets=targets)
+ eligible = "('safe', 'referenced')" if mode == "force" else "('safe')"
+ result = ScopeClassification()
+ remaining = max_candidates
with self._db.transaction() as cursor:
- self._prepare(cursor)
- select = f"""--sql
- SELECT m.{name_column}, {self._classification_sql(kind)} AS classification, m.file_size_bytes, m.user_id,
- CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END
- FROM {table} m
- LEFT JOIN projects p ON p.user_id = m.user_id AND p.project_id = m.project_id
- WHERE m.is_intermediate = TRUE
- """
-
- def filtered_query(scope_clause: str) -> str:
- scoped = f"{select} {scope_clause}"
- if eligible_mode is None:
- return scoped
- classes = "'safe', 'referenced'" if eligible_mode == "force" else "'safe'"
- return f"SELECT * FROM ({scoped}) WHERE classification IN ({classes})"
-
- if targets is not None:
- for start in range(0, len(targets), _TARGETS_PER_STATEMENT):
- predicate, params = self._scope_predicate(targets[start : start + _TARGETS_PER_STATEMENT])
- if not predicate:
+ clock = self._prepare(cursor)
+ for media_kind in _TABLES:
+ candidates = result.candidates[media_kind]
+ for clause, params in clauses:
+ for owner, project_key, cls, n, _, _ in self._aggregate(cursor, clock, media_kind, clause, params):
+ result.rows.add((owner, project_key))
+ _add_count(result.counts[media_kind], cls, n)
+ if len(candidates) > remaining:
continue
- remaining = None if max_results is None else max_results + 1 - len(candidates)
- tail = "" if remaining is None else " LIMIT ?"
cursor.execute(
- f"{filtered_query(f'AND ({predicate})')}{tail};",
- [*params, *([remaining] if remaining is not None else [])],
+ f"SELECT name, cls, file_size_bytes FROM ({self._scoped_sql(media_kind)} {clause}) "
+ f"WHERE cls IN {eligible} LIMIT ?;",
+ [*clock, *params, remaining + 1 - len(candidates)],
)
candidates.extend(self._to_candidates(cursor.fetchall()))
- if max_results is not None and len(candidates) > max_results:
- break
- elif user_id is not None:
- tail = "" if max_results is None else " LIMIT ?"
- cursor.execute(
- f"{filtered_query('AND m.user_id = ?')}{tail};",
- [user_id, *([max_results + 1] if max_results is not None else [])],
- )
- candidates.extend(self._to_candidates(cursor.fetchall()))
- else:
- tail = "" if max_results is None else " LIMIT ?"
- cursor.execute(f"{filtered_query('')}{tail};", [] if max_results is None else [max_results + 1])
- candidates.extend(self._to_candidates(cursor.fetchall()))
- return candidates
+ if len(candidates) > remaining:
+ result.has_more = True
+ del candidates[remaining:]
+ remaining -= len(candidates)
+ if mode == "force":
+ result.reference_owners[media_kind] = self._reference_owners(
+ cursor, media_kind, [c.name for c in candidates if c.classification == "referenced"]
+ )
+ return result
def page_intermediates(
self, kind: MediaKind, *, after_rowid: int, limit: int
@@ -601,16 +766,16 @@ class IntermediatesRecordsSqlite:
"""
table, name_column, _ = _TABLES[kind]
with self._db.transaction() as cursor:
- self._prepare(cursor)
+ clock = self._prepare(cursor)
cursor.execute(
f"""--sql
- SELECT m.rowid, m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes, m.user_id, NULL
+ SELECT m.rowid, m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes
FROM {table} m
WHERE m.is_intermediate = TRUE AND m.rowid > ?
ORDER BY m.rowid
LIMIT ?;
""",
- (after_rowid, limit),
+ (*clock, after_rowid, limit),
)
rows = cursor.fetchall()
if not rows:
@@ -624,64 +789,54 @@ class IntermediatesRecordsSqlite:
name=cast(str, row[0]),
classification=cast(Classification, row[1]),
file_size_bytes=cast(Optional[int], row[2]),
- user_id=cast(str, row[3]),
- project_id=cast(Optional[str], row[4]),
)
for row in rows
]
- def affected_references(self, kind: MediaKind, names: Sequence[str]) -> list[AffectedReference]:
- """The saved documents naming any of ``names``, with how many they name."""
- counts: dict[tuple[str, str, str], int] = defaultdict(int)
- with self._db.transaction() as cursor:
- for start in range(0, len(names), _MAX_SQL_VARIABLES):
- chunk = list(names[start : start + _MAX_SQL_VARIABLES])
- placeholders = ",".join("?" for _ in chunk)
- cursor.execute(
- f"""--sql
- SELECT owner_kind, user_id, owner_id, COUNT(*)
- FROM media_references
- WHERE media_kind = ? AND media_name IN ({placeholders})
- GROUP BY owner_kind, user_id, owner_id;
- """,
- [kind, *chunk],
- )
- for owner_kind, owner_user, owner_id, n in cursor.fetchall():
- counts[(cast(str, owner_kind), cast(str, owner_user), cast(str, owner_id))] += cast(int, n)
- return [AffectedReference(owner_kind=k, user_id=u, owner_id=o, references=n) for (k, u, o), n in counts.items()]
-
- def reference_owners(self, kind: MediaKind, names: Sequence[str]) -> dict[str, set[tuple[str, str, str]]]:
- owners: dict[str, set[tuple[str, str, str]]] = {}
- with self._db.transaction() as cursor:
- for start in range(0, len(names), _MAX_SQL_VARIABLES - 1):
- chunk = list(names[start : start + _MAX_SQL_VARIABLES - 1])
- placeholders = ",".join("?" for _ in chunk)
- cursor.execute(
- f"SELECT media_name, owner_kind, user_id, owner_id FROM media_references "
- f"WHERE media_kind = ? AND media_name IN ({placeholders});",
- [kind, *chunk],
- )
- for name, owner_kind, user_id, owner_id in cursor.fetchall():
- owners.setdefault(str(name), set()).add((str(owner_kind), str(user_id), str(owner_id)))
+ @staticmethod
+ def _reference_owners(cursor: sqlite3.Cursor, kind: MediaKind, names: Sequence[str]) -> ReferenceOwners:
+ owners: ReferenceOwners = {}
+ for start in range(0, len(names), _MAX_SQL_VARIABLES - 1):
+ chunk = list(names[start : start + _MAX_SQL_VARIABLES - 1])
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"SELECT media_name, owner_kind, user_id, owner_id FROM media_references "
+ f"WHERE media_kind = ? AND media_name IN ({placeholders});",
+ [kind, *chunk],
+ )
+ for name, owner_kind, user_id, owner_id in cursor.fetchall():
+ owners.setdefault(str(name), set()).add(ReferenceOwner(str(owner_kind), str(user_id), str(owner_id)))
return owners
- def get_document_names(self, refs: Sequence[AffectedReference]) -> dict[tuple[str, str, str], str]:
- """Names of the referencing documents; client state has none."""
+ def get_document_names(self, owners: Iterable[ReferenceOwner]) -> dict[ReferenceOwner, str]:
+ """Names of the referencing documents, one query per kind and chunk; client state has none."""
queries = {
- "project": "SELECT name FROM projects WHERE user_id = ? AND project_id = ?;",
- "quarantined_project": "SELECT name FROM orphaned_projects_2026_08_06 WHERE user_id = ? AND project_id = ?;",
- "workflow": "SELECT name FROM workflow_library WHERE workflow_id = ?;",
+ "project": "SELECT user_id, project_id, name FROM projects WHERE project_id IN ({});",
+ "quarantined_project": (
+ "SELECT user_id, project_id, name FROM orphaned_projects_2026_08_06 WHERE project_id IN ({});"
+ ),
+ # Workflow ids are globally unique, so the owner is not part of the match.
+ "workflow": "SELECT NULL, workflow_id, name FROM workflow_library WHERE workflow_id IN ({});",
}
- names: dict[tuple[str, str, str], str] = {}
+ wanted: dict[str, set[ReferenceOwner]] = defaultdict(set)
+ for owner in owners:
+ if owner.owner_kind in queries:
+ wanted[owner.owner_kind].add(owner)
+ names: dict[ReferenceOwner, str] = {}
with self._db.transaction() as cursor:
- for ref in refs:
- query = queries.get(ref.owner_kind)
- if query is None:
- continue
- cursor.execute(query, (ref.owner_id,) if ref.owner_kind == "workflow" else (ref.user_id, ref.owner_id))
- row = cursor.fetchone()
- if row is not None and row[0] is not None:
- names[(ref.owner_kind, ref.user_id, ref.owner_id)] = cast(str, row[0])
+ for owner_kind, kind_owners in wanted.items():
+ ids = sorted({owner.owner_id for owner in kind_owners})
+ found: dict[tuple[Optional[str], str], str] = {}
+ for start in range(0, len(ids), _MAX_SQL_VARIABLES):
+ chunk = ids[start : start + _MAX_SQL_VARIABLES]
+ cursor.execute(queries[owner_kind].format(",".join("?" for _ in chunk)), chunk)
+ for user_id, owner_id, name in cursor.fetchall():
+ if name is not None:
+ found[(cast(Optional[str], user_id), cast(str, owner_id))] = cast(str, name)
+ for owner in kind_owners:
+ name = found.get((None if owner_kind == "workflow" else owner.user_id, owner.owner_id))
+ if name is not None:
+ names[owner] = name
return names
# endregion
@@ -694,8 +849,8 @@ class IntermediatesRecordsSqlite:
*,
mode: IntermediatesCleanupMode,
allowed_user_ids: Optional[frozenset[str]],
- confirmed_references: Optional[dict[str, set[tuple[str, str, str]]]] = None,
- ):
+ confirmed_references: Optional[ReferenceOwners] = None,
+ ) -> IntermediateDeleteGuard:
"""The final check of a cleanup batch, run on the deleting transaction.
Re-applies the policy to the frozen targets at the moment of deletion: anything that became
@@ -706,22 +861,12 @@ class IntermediatesRecordsSqlite:
deletable = "('safe')" if mode == "safe" else "('safe', 'referenced')"
def guard(cursor: sqlite3.Cursor, names: Sequence[str]) -> list[str]:
- self._prepare(cursor)
+ clock = self._prepare(cursor)
kept: list[str] = []
for start in range(0, len(names), _MAX_SQL_VARIABLES):
chunk = list(names[start : start + _MAX_SQL_VARIABLES])
placeholders = ",".join("?" for _ in chunk)
- current_references: dict[str, set[tuple[str, str, str]]] = {}
- if mode == "force":
- cursor.execute(
- f"SELECT media_name, owner_kind, user_id, owner_id FROM media_references "
- f"WHERE media_kind = ? AND media_name IN ({placeholders});",
- [kind, *chunk],
- )
- for name, owner_kind, user_id, owner_id in cursor.fetchall():
- current_references.setdefault(str(name), set()).add(
- (str(owner_kind), str(user_id), str(owner_id))
- )
+ current_references = self._reference_owners(cursor, kind, chunk) if mode == "force" else {}
cursor.execute(
f"""--sql
SELECT name, user_id FROM (
@@ -731,7 +876,7 @@ class IntermediatesRecordsSqlite:
WHERE m.{name_column} IN ({placeholders}) AND m.is_intermediate = TRUE
) WHERE cls IN {deletable};
""",
- chunk,
+ [*clock, *chunk],
)
# Ownership is re-read here rather than trusted from the preview.
kept.extend(
diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.py
index 7c32a1c935..6c6ccd223a 100644
--- a/invokeai/app/services/invocation_services.py
+++ b/invokeai/app/services/invocation_services.py
@@ -109,10 +109,10 @@ class InvocationServices:
gallery: "GalleryServiceABC",
image_index_records: "ImageIndexRecordsBase",
image_index: "ImageIndexServiceBase",
+ intermediates: "IntermediatesServiceBase",
image_moves: "ImageMoveService | None" = None,
progress_previews: "ProgressPreviewsBase | None" = None,
fonts: "FontService | None" = None,
- intermediates: "IntermediatesServiceBase | None" = None,
):
self.board_images = board_images
self.board_image_records = board_image_records
diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.py
index 4ecf26c93d..4f8ea95f8d 100644
--- a/invokeai/app/services/project_records/project_records_sqlite.py
+++ b/invokeai/app/services/project_records/project_records_sqlite.py
@@ -92,6 +92,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
)
document_json, document_bytes = _serialize_project_document(data)
_require_project_document_size(document_bytes)
+ references = extract_media_references(data)
try:
with self._db.transaction() as cursor:
@@ -124,7 +125,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
owner_kind="project",
user_id=user_id,
owner_id=project_id,
- references=extract_media_references(data),
+ references=references,
)
record = self._fetch_record(cursor, user_id=user_id, project_id=project_id)
except sqlite3.IntegrityError as e:
@@ -201,6 +202,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
max_canvas_schema_version: int = DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,
) -> ProjectRecordDTO:
document_json, document_bytes = _serialize_project_document(data)
+ references = extract_media_references(data)
with self._db.transaction() as cursor:
cursor.execute(
@@ -291,7 +293,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
owner_kind="project",
user_id=user_id,
owner_id=project_id,
- references=extract_media_references(data),
+ references=references,
)
record = self._fetch_record(cursor, user_id=user_id, project_id=project_id)
diff --git a/invokeai/app/services/shared/media_references.py b/invokeai/app/services/shared/media_references.py
index ed4c224cdd..1ae4253cf3 100644
--- a/invokeai/app/services/shared/media_references.py
+++ b/invokeai/app/services/shared/media_references.py
@@ -10,6 +10,9 @@ save and its references are never observed apart, and the extractor here is the
Extraction is deliberately over-inclusive: every string under an image- or video-name key counts,
history included. A false reference retains a file; a missed one deletes something in use.
+
+Applied migrations call the table DDL, the extractors and `replace_media_references`: keep their DDL
+and signatures frozen, since changing them changes what a fresh install's migrations do.
"""
import json
@@ -21,7 +24,7 @@ MediaReferenceOwnerKind = Literal["project", "workflow", "client_state", "quaran
MediaKind = Literal["image", "video"]
IMAGE_NAME_KEYS = frozenset({"imageName", "image_name"})
-VIDEO_NAME_KEYS = frozenset({"videoName", "video_name"})
+VIDEO_NAME_KEYS = frozenset({"videoName", "video_name", "source_video_name"})
# Bounds a pathological document: names are generated UUID filenames, so anything longer is not
# one and is not worth a row.
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py
index 7c2353d943..a1ce015c16 100644
--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py
@@ -10,7 +10,7 @@ file, how large it is, or whether a saved document still needs it. This migratio
inferred.
- `images.file_size_bytes` / `videos.file_size_bytes`: on-disk size of the media file plus its
thumbnail (and video sidecar). NULL means not yet measured, never zero.
-- `media_references`: the assets every saved project document and library workflow names, backfilled
+- `media_references`: the assets every saved project document and user library workflow names, backfilled
here from the existing rows and kept current by their writers from now on.
"""
@@ -111,10 +111,14 @@ class AddIntermediatesManagementCallback:
select="SELECT user_id, project_id, data FROM projects ORDER BY rowid ASC;",
)
if _table_exists(cursor, "workflow_library"):
+ # Only user workflows: default workflows are synced from files and never indexed at runtime.
indexed += self._index_rows(
cursor,
owner_kind="workflow",
- select="SELECT user_id, workflow_id, workflow FROM workflow_library ORDER BY rowid ASC;",
+ select=(
+ "SELECT user_id, workflow_id, workflow FROM workflow_library"
+ " WHERE category = 'user' ORDER BY rowid ASC;"
+ ),
)
if indexed:
self._logger.info(f"Intermediates management migration: indexed media references of {indexed} document(s)")
diff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.py
index 24b5f8a9c8..140b1b273b 100644
--- a/invokeai/app/services/video_files/video_files_disk.py
+++ b/invokeai/app/services/video_files/video_files_disk.py
@@ -181,6 +181,7 @@ class DiskVideoFileStorage(VideoFileStorageBase):
raise VideoFileDeleteException from e
def begin_delete(self, videos: Sequence[tuple[str, str]]) -> _PendingDelete:
+ # Resolving each path validates the names before anything is journalled; the paths are re-derived at commit.
for name, subfolder in videos:
self.__delete_candidates(name, subfolder)
directory = Path(tempfile.mkdtemp(prefix=".delete_", dir=self.__output_folder))
diff --git a/invokeai/app/services/videos/videos_base.py b/invokeai/app/services/videos/videos_base.py
index bd57780bf1..4bf0b5d2a5 100644
--- a/invokeai/app/services/videos/videos_base.py
+++ b/invokeai/app/services/videos/videos_base.py
@@ -153,10 +153,10 @@ class VideoServiceABC(ABC):
def delete_intermediates_by_names(
self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
) -> IntermediateDeleteResult:
- """Deletes the named videos that are still intermediates, reporting the names removed.
+ """Deletes the named videos that are still intermediates, journalled, reporting the names removed.
- Files are staged before the conditional record delete and restored for every name the
- delete (or ``guard``) kept, so a promoted or protected video is never damaged.
+ ``guard`` is consulted on the deleting transaction so the cleanup policy's final check and
+ the record removal are one atomic step.
"""
pass
diff --git a/invokeai/app/services/workflow_records/workflow_records_sqlite.py b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
index c275078868..29e4dc43e0 100644
--- a/invokeai/app/services/workflow_records/workflow_records_sqlite.py
+++ b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
@@ -4,7 +4,8 @@ from typing import Optional
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.media_references import (
- extract_media_references,
+ MediaReferences,
+ extract_media_references_from_json,
replace_media_references,
)
from invokeai.app.services.shared.pagination import PaginatedResults
@@ -62,8 +63,10 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
if workflow.meta.category is WorkflowCategory.Default:
raise ValueError("Default workflows cannot be created via this method")
+ workflow_with_id = Workflow(**workflow.model_dump(), id=uuid_string())
+ document_json = workflow_with_id.model_dump_json()
+ references = extract_media_references_from_json(document_json)
with self._db.transaction() as cursor:
- workflow_with_id = Workflow(**workflow.model_dump(), id=uuid_string())
cursor.execute(
"""--sql
INSERT OR IGNORE INTO workflow_library (
@@ -74,15 +77,17 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
)
VALUES (?, ?, ?, ?);
""",
- (workflow_with_id.id, workflow_with_id.model_dump_json(), user_id, is_public),
+ (workflow_with_id.id, document_json, user_id, is_public),
)
- self._index_references(cursor, workflow_with_id, user_id=user_id)
+ self._index_references(cursor, workflow_with_id.id, references, user_id=user_id)
return self.get(workflow_with_id.id)
def update(self, workflow: Workflow, user_id: Optional[str] = None) -> WorkflowRecordDTO:
if workflow.meta.category is WorkflowCategory.Default:
raise ValueError("Default workflows cannot be updated")
+ document_json = workflow.model_dump_json()
+ references = extract_media_references_from_json(document_json)
with self._db.transaction() as cursor:
if user_id is not None:
cursor.execute(
@@ -91,7 +96,7 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
SET workflow = ?
WHERE workflow_id = ? AND category = 'user' AND user_id = ?;
""",
- (workflow.model_dump_json(), workflow.id, user_id),
+ (document_json, workflow.id, user_id),
)
else:
cursor.execute(
@@ -100,11 +105,14 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
SET workflow = ?
WHERE workflow_id = ? AND category = 'user';
""",
- (workflow.model_dump_json(), workflow.id),
+ (document_json, workflow.id),
)
if cursor.rowcount:
self._index_references(
- cursor, workflow, user_id=user_id if user_id is not None else self._owner_of(cursor, workflow.id)
+ cursor,
+ workflow.id,
+ references,
+ user_id=user_id if user_id is not None else self._owner_of(cursor, workflow.id),
)
return self.get(workflow.id)
@@ -171,14 +179,13 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
)
return self.get(workflow_id)
- def _index_references(self, cursor: sqlite3.Cursor, workflow: Workflow, *, user_id: str) -> None:
+ @staticmethod
+ def _index_references(
+ cursor: sqlite3.Cursor, workflow_id: str, references: MediaReferences, *, user_id: str
+ ) -> None:
"""Records the media a library workflow names, on the caller's transaction."""
replace_media_references(
- cursor,
- owner_kind="workflow",
- user_id=user_id,
- owner_id=workflow.id,
- references=extract_media_references(workflow.model_dump(mode="json")),
+ cursor, owner_kind="workflow", user_id=user_id, owner_id=workflow_id, references=references
)
@staticmethod
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index fd9267803f..edafc21d9d 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -7518,95 +7518,6 @@
}
}
},
- "/api/v1/intermediates/holds/{lease_id}": {
- "put": {
- "tags": ["intermediates"],
- "summary": "Replace Intermediates Browser Hold",
- "description": "Protect names still held by this account's open browser editor, including undo state.",
- "operationId": "replace_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__put",
- "security": [
- {
- "HTTPBearer": []
- }
- ],
- "parameters": [
- {
- "name": "lease_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 64,
- "title": "Lease Id"
- }
- }
- ],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/IntermediatesBrowserHoldRequest"
- }
- }
- }
- },
- "responses": {
- "204": {
- "description": "Successful Response"
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- }
- }
- }
- },
- "delete": {
- "tags": ["intermediates"],
- "summary": "Release Intermediates Browser Hold",
- "operationId": "release_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__delete",
- "security": [
- {
- "HTTPBearer": []
- }
- ],
- "parameters": [
- {
- "name": "lease_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 64,
- "title": "Lease Id"
- }
- }
- ],
- "responses": {
- "204": {
- "description": "Successful Response"
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- }
- }
- }
- }
- },
"/api/v1/intermediates/summary": {
"get": {
"tags": ["intermediates"],
@@ -7933,6 +7844,97 @@
}
}
},
+ "/api/v1/intermediates/holds/{lease_id}": {
+ "put": {
+ "tags": ["intermediates"],
+ "summary": "Replace Intermediates Browser Hold",
+ "description": "Protect names still held by this account's open browser editor, including undo state.",
+ "operationId": "replace_intermediates_browser_hold",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "lease_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_.-]+)?$",
+ "title": "Lease Id"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IntermediatesBrowserHoldRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "204": {
+ "description": "Successful Response"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["intermediates"],
+ "summary": "Release Intermediates Browser Hold",
+ "operationId": "release_intermediates_browser_hold",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "lease_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_.-]+)?$",
+ "title": "Lease Id"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Successful Response"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/videos/upload": {
"post": {
"tags": ["videos"],
@@ -49680,7 +49682,13 @@
},
"type": "array",
"title": "Affected Documents",
- "description": "Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own"
+ "description": "Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own. Bounded; see `affected_documents_total`"
+ },
+ "affected_documents_total": {
+ "type": "integer",
+ "title": "Affected Documents Total",
+ "description": "How many documents a force clear would break, including any not listed",
+ "default": 0
}
},
"type": "object",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index a23d20e0cc..88062379a2 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1822,27 +1822,6 @@ export type paths = {
patch?: never;
trace?: never;
};
- "/api/v1/intermediates/holds/{lease_id}": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- /**
- * Replace Intermediates Browser Hold
- * @description Protect names still held by this account's open browser editor, including undo state.
- */
- put: operations["replace_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__put"];
- post?: never;
- /** Release Intermediates Browser Hold */
- delete: operations["release_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__delete"];
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/api/v1/intermediates/summary": {
parameters: {
query?: never;
@@ -1940,6 +1919,27 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/intermediates/holds/{lease_id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ /**
+ * Replace Intermediates Browser Hold
+ * @description Protect names still held by this account's open browser editor, including undo state.
+ */
+ put: operations["replace_intermediates_browser_hold"];
+ post?: never;
+ /** Release Intermediates Browser Hold */
+ delete: operations["release_intermediates_browser_hold"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/videos/upload": {
parameters: {
query?: never;
@@ -20947,9 +20947,15 @@ export type components = {
impact: components["schemas"]["IntermediatesImpact"];
/**
* Affected Documents
- * @description Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own
+ * @description Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own. Bounded; see `affected_documents_total`
*/
affected_documents?: components["schemas"]["IntermediatesAffectedDocument"][];
+ /**
+ * Affected Documents Total
+ * @description How many documents a force clear would break, including any not listed
+ * @default 0
+ */
+ affected_documents_total?: number;
};
/** IntermediatesPreviewRequest */
IntermediatesPreviewRequest: {
@@ -53323,68 +53329,6 @@ export interface operations {
};
};
};
- replace_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__put: {
- parameters: {
- query?: never;
- header?: never;
- path: {
- lease_id: string;
- };
- cookie?: never;
- };
- requestBody: {
- content: {
- "application/json": components["schemas"]["IntermediatesBrowserHoldRequest"];
- };
- };
- responses: {
- /** @description Successful Response */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description Validation Error */
- 422: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["HTTPValidationError"];
- };
- };
- };
- };
- release_intermediates_browser_hold_api_v1_intermediates_holds__lease_id__delete: {
- parameters: {
- query?: never;
- header?: never;
- path: {
- lease_id: string;
- };
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Successful Response */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description Validation Error */
- 422: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["HTTPValidationError"];
- };
- };
- };
- };
get_intermediates_summary: {
parameters: {
query?: {
@@ -53552,6 +53496,68 @@ export interface operations {
};
};
};
+ replace_intermediates_browser_hold: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ lease_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["IntermediatesBrowserHoldRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ release_intermediates_browser_hold: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ lease_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
upload_video: {
parameters: {
query: {
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index dc856ee8fd..2e25592c10 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -40,7 +40,7 @@ The queue pilot is the first migrated feature. Its private `QueueBackendPort` is
Queue exposes board-independent active backend sessions, including preparation and result settlement. The Gallery progress section includes every unfinished batch slot, including queued work; Preview follows executing and settling sessions. Both use gallery-destination projections of the active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions do not participate in board counts, saved-image selection, or navigation. Saved outputs retain their actual backend board destinations; automatic result selection does not change the browsed board or its paging window.
-Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the manager requests a server preview, which freezes the targets, and confirms it. The client's one input to that policy is a browser hold lease: `holdLease` (a public entry, started by Workbench for the provider's lifetime) keeps the media open editors still need (live content from every open project plus the undo state each live Canvas engine retains, read through `projects/projectAssets`) classified as active. It sends sorted names in batches within the server's per-kind limit, stages a changed set under a second lease before releasing the old one, refreshes every five minutes and when a tab becomes visible after a minute away, and releases with `keepalive` on dispose and `pagehide`; the server expires a lease after 15 minutes, which bounds anything a crash leaves behind. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.
+Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the manager requests a server preview, which freezes the targets, and confirms it. The client's one input to that policy is a browser hold lease: `holdLease` (a public entry, started by Workbench for the provider's lifetime) keeps the media open editors still need (live content from every open project plus the undo state each live Canvas engine retains) classified as active. Workbench owns the name set: `projects/projectAssets` scans each immutable project subtree once, and each Canvas engine registers its retained undo state with the mounted Workbench, which re-reads it when the history changes; an engine released by one Workbench is replaced, not reused, by the next, and one another Workbench still uses is refused. The lease sends sorted names in batches within the server's per-kind limit, each under an id `<holder>.<part>` sharing one holder per tab because the server caps distinct holders per account, skips unchanged sets without re-serialising them, stages a changed set under a second lease before releasing the old one, refreshes every five minutes and when a tab becomes visible after missing a refresh, and releases with `keepalive` on dispose and `pagehide`; the server expires a lease after 15 minutes, which bounds anything a crash leaves behind. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.
Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 21b7401897..4adb091127 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -295,6 +295,7 @@
"source:src/workbench/launchpad/projects/projectsMetrics.ts",
"source:src/workbench/launchpad/projects/useProjectCardActions.ts",
"source:src/workbench/launchpad/startEntries.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/paletteStore.ts",
@@ -885,6 +886,7 @@
"source:src/workbench/layoutPresetSnapshots.ts",
"source:src/workbench/layoutPresets.ts",
"source:src/workbench/layoutWidgetSet.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/WorkbenchCommandPalette.tsx",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 20dd6aae2d..094bf0410f 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -707,6 +707,7 @@
"source:src/workbench/launchpad/projects/projectsMetrics.ts",
"source:src/workbench/launchpad/projects/useProjectCardActions.ts",
"source:src/workbench/launchpad/startEntries.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/paletteStore.ts",
@@ -1580,6 +1581,7 @@
"source:src/workbench/layoutPresetSnapshots.ts",
"source:src/workbench/layoutPresets.ts",
"source:src/workbench/layoutWidgetSet.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/WorkbenchCommandPalette.tsx",
@@ -2642,6 +2644,7 @@
"source:src/workbench/layoutPresetSnapshots.ts",
"source:src/workbench/layoutPresets.ts",
"source:src/workbench/layoutWidgetSet.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/WorkbenchCommandPalette.tsx",
@@ -3908,6 +3911,7 @@
"source:src/workbench/layoutPresetSnapshots.ts",
"source:src/workbench/layoutPresets.ts",
"source:src/workbench/layoutWidgetSet.ts",
+ "source:src/workbench/mediaReferences.ts",
"source:src/workbench/palette/LaunchpadCommandPalette.tsx",
"source:src/workbench/palette/PaletteButton.tsx",
"source:src/workbench/palette/WorkbenchCommandPalette.tsx",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 9fe1683a46..44968299bc 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -545,7 +545,7 @@
"importReferences": "Import without font files",
"installing": "Installing fonts {{completed}} / {{total}}"
},
- "clearIntermediates": "Clear intermediates…"
+ "deleteIntermediates": "Delete intermediates…"
},
"users": {
"accountCount_one": "{{count}} account in this workspace.",
@@ -4202,7 +4202,7 @@
},
"intermediates": {
"title": "Intermediates",
- "description": "Temporary images and videos that generation leaves behind. Clear the ones nothing needs to reclaim disk space.",
+ "description": "Temporary images and videos that generation leaves behind. Delete the ones nothing needs to reclaim disk space.",
"refresh": "Refresh",
"searchLabel": "Search projects",
"searchPlaceholder": "Search projects…",
@@ -4219,67 +4219,71 @@
},
"dialog": {
"title": "Delete intermediates?",
- "forceTitle": "Force clear intermediates?",
- "loadingPreview": "Checking what can be cleared…",
- "batchLimit": "This preview includes up to 50,000 eligible items. More remain in this scope; run Clear again after this batch finishes.",
- "previewFailed": "Could not check what can be cleared.",
- "summary": "Clear {{images}} and {{videos}} from {{projects}}?",
+ "forceTitle": "Force delete intermediates?",
+ "loadingPreview": "Checking what can be deleted…",
+ "batchLimit": "This preview includes up to 50,000 eligible items. More remain in this scope; run Delete again after this batch finishes.",
+ "previewFailed": "Could not check what can be deleted.",
+ "summary": "Delete {{images}} and {{videos}} from {{projects}}?",
"reclaim": "Approximately {{size}} can be reclaimed.",
"reclaimUnknown": "Reclaimable space is still being measured.",
- "reclaimPartial_one": "{{count}} item is not measured yet.",
- "reclaimPartial_other": "{{count}} items are not measured yet.",
- "kept_one": "{{count}} in-use item will be kept.",
- "kept_other": "{{count}} in-use items will be kept.",
- "nothing": "Nothing is safe to clear right now.",
- "forceWarning": "Force clearing also deletes intermediates that saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Queued, running and recently created work stays protected. Deletion cannot be undone.",
- "forceWarningOwn": "Force clearing also deletes intermediates that your saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Items another account's documents use are always kept, as are queued, running and recently created work. Deletion cannot be undone.",
+ "reclaimPartial_one": "{{count, number}} item is not measured yet.",
+ "reclaimPartial_other": "{{count, number}} items are not measured yet.",
+ "kept_one": "{{count, number}} in-use item will be kept.",
+ "kept_other": "{{count, number}} in-use items will be kept.",
+ "nothing": "Nothing is safe to delete right now.",
+ "forceWarning": "Force delete also removes intermediates that saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Queued, running and recently created work stays protected. Deletion cannot be undone.",
+ "forceWarningOwn": "Force delete also removes intermediates that your saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Items another account's documents use are always kept, as are queued, running and recently created work. Deletion cannot be undone.",
"affected": "Documents that will lose references",
- "affectedProject_one": "Project “{{name}}” ({{count}} item)",
- "affectedProject_other": "Project “{{name}}” ({{count}} items)",
- "affectedWorkflow_one": "Workflow “{{name}}” ({{count}} item)",
- "affectedWorkflow_other": "Workflow “{{name}}” ({{count}} items)",
+ "affectedProject_one": "Project “{{name}}” ({{count, number}} item)",
+ "affectedProject_other": "Project “{{name}}” ({{count, number}} items)",
+ "affectedWorkflow_one": "Workflow “{{name}}” ({{count, number}} item)",
+ "affectedWorkflow_other": "Workflow “{{name}}” ({{count, number}} items)",
"affectedOwner": "· {{owner}}",
- "affectedClientState_one": "Legacy editor state ({{count}} item)",
- "affectedClientState_other": "Legacy editor state ({{count}} items)",
- "affectedQuarantinedProject_one": "Recovered project “{{name}}” ({{count}} item)",
- "affectedQuarantinedProject_other": "Recovered project “{{name}}” ({{count}} items)",
+ "affectedClientState_one": "Legacy editor state ({{count, number}} item)",
+ "affectedClientState_other": "Legacy editor state ({{count, number}} items)",
+ "affectedQuarantinedProject_one": "Recovered project “{{name}}” ({{count, number}} item)",
+ "affectedQuarantinedProject_other": "Recovered project “{{name}}” ({{count, number}} items)",
+ "affectedMore_one": "and {{count, number}} more document",
+ "affectedMore_other": "and {{count, number}} more documents",
"acknowledge": "I understand this may break saved documents and cannot be undone.",
"typeToConfirm": "Type {{word}} to confirm",
"confirm": "Delete",
"forceConfirm": "Force delete",
- "startFailed": "Could not start the cleanup.",
- "startTimedOut": "The server did not answer in time. Pressing Confirm again is safe: it resumes this same cleanup rather than starting a second one.",
+ "startFailed": "Could not start deleting intermediates.",
+ "startTimedOut": "The server did not answer in time, so the deletion may already be running. Selecting “{{action}}” again is safe: it resumes this same deletion rather than starting a second one.",
"keptReasons": "{{reasons}}.",
"keptReferenced": "{{items}} referenced by saved documents",
"keptActive": "{{items}} used by queued or running work",
"keptRecent": "{{items}} created recently",
"forceToggle": "Also delete items that saved documents still reference (advanced)",
"previewExpired": "This check is no longer current. Check again before deleting.",
- "tooManyRows": "More than {{count}} projects match. Narrow the search or clear the selection and choose projects."
+ "tooManyRows": "More than {{count, number}} projects match. Narrow the search or clear the selection and choose projects."
},
"operation": {
- "pending": "Preparing cleanup…",
+ "regionLabel": "Deletion status",
+ "pending": "Preparing to delete…",
"status": {
- "pending": "Cleanup queued",
- "running": "Clearing intermediates…",
- "completed": "Cleanup finished",
- "failed": "Cleanup stopped"
+ "pending": "Deletion queued",
+ "running": "Deleting intermediates",
+ "completed": "Deletion finished",
+ "failed": "Deletion stopped"
},
"progress": "{{done}} of {{total}} processed",
+ "progressAnnouncement": "{{status}}: {{percent, number(style: percent)}} processed.",
"deleted": "Deleted",
"retained": "Kept",
"failed": "Failed",
- "pendingDisk": "Awaiting disk cleanup",
+ "pendingDisk": "Awaiting removal from disk",
"reclaimed": "Reclaimed",
"retry": "Retry unresolved",
"dismiss": "Dismiss",
- "retryFailed": "Could not retry the cleanup.",
- "lookupFailed": "Could not load cleanup status.",
- "pendingDiskNote": "Some files could not be removed yet. They are cleaned up on the next server start and their space is not counted as reclaimed."
+ "retryFailed": "Could not retry the deletion.",
+ "lookupFailed": "Could not load deletion status.",
+ "pendingDiskNote": "Some files could not be removed yet. They are removed on the next server start and their space is not counted as reclaimed."
},
"empty": {
"title": "No intermediates",
- "description": "There is nothing to clean up.",
+ "description": "There is nothing to delete.",
"noMatches": "No matching projects",
"noMatchesDescription": "No project matches your search."
},
@@ -4291,13 +4295,17 @@
"showEveryone": "Show everyone",
"showMine": "My account",
"projectFilter": "Selected project",
- "showAllProjects": "Show all projects"
+ "showAllProjects": "Show all projects",
+ "unknownAccount": "Unknown account",
+ "unknownAccountWithId": "Unknown account {{id}}",
+ "nameWithEmail": "{{name}} ({{email}})"
},
"list": {
"selectAll": "Select all",
"selectRow": "Select {{name}}",
- "selectRowForOwner": "Select {{name}} for {{owner}} (account {{userId}})",
+ "selectRowForOwner": "Select {{name}} for {{owner}}",
"delete": "Delete",
+ "deleteWaiting": "Delete is available again once the current deletion finishes.",
"used": "Used",
"unused": "Unused",
"unassigned": "Unassigned",
@@ -4313,7 +4321,7 @@
"selection": {
"checking": "Checking selection…",
"estimateFailed": "Could not estimate selection. Refresh to retry.",
- "tooManyRows": "More than {{count}} matching projects. Narrow your search to review this selection.",
+ "tooManyRows": "More than {{count, number}} matching projects. Narrow your search to review this selection.",
"estimate": "{{count, number}} selected · {{images}}, {{videos}}, about {{size}}",
"available": "{{images}}, {{videos}} unused · about {{size}} reclaimable"
}
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 9b09b77338..bfbed8a5ee 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -44,12 +44,29 @@ const ARCHITECTURE_CAPABILITIES = JSON.parse(
)
);
-/** POST /__faults sets capabilities to error, empty, or ok until POST /__reset; independent of workload profile. */
+/**
+ * POST /__faults sets capabilities to error, empty, or ok, and `intermediatesCaller` to admin or user, until POST
+ * /__reset; independent of workload profile. `user` also turns on multi-user auth with a non-admin session: sign in
+ * with any email and password (or reload a page that already holds the token) to reach the non-admin UI.
+ */
const CAPABILITY_FAULTS = new Set(['ok', 'error', 'empty']);
+const INTERMEDIATES_CALLERS = new Set(['admin', 'user']);
-const createFaults = () => ({ capabilities: 'ok' });
+const createFaults = () => ({ capabilities: 'ok', intermediatesCaller: 'admin' });
const MOCK_USER_ID = 'fixture-user';
+const MOCK_USER_TOKEN = 'mock-user-token';
+
+const mockNonAdminUser = () => ({
+ created_at: '2026-01-01T00:00:00Z',
+ display_name: 'Fixture User',
+ email: '[email protected]',
+ is_active: true,
+ is_admin: false,
+ last_login_at: null,
+ updated_at: '2026-01-01T00:00:00Z',
+ user_id: MOCK_USER_ID,
+});
const clone = (value) => structuredClone(value);
@@ -94,6 +111,7 @@ const createState = (profile) => {
profile,
projects: new Map(fixture.projects.map((project) => [project.project_id, clone(project)])),
intermediates: fixture.intermediates.map(clone),
+ intermediatesIdempotency: new Map(),
intermediatesOperations: new Map(),
intermediatesPreviews: new Map(),
queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),
@@ -682,6 +700,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
if (method === 'POST') {
const body = await readJsonBody(request);
const requested = url.searchParams.get('capabilities') ?? body.capabilities;
+ const caller = url.searchParams.get('intermediatesCaller') ?? body.intermediatesCaller;
if (requested !== undefined && requested !== null) {
if (!CAPABILITY_FAULTS.has(requested)) {
@@ -690,6 +709,14 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
faults.capabilities = requested;
}
+
+ if (caller !== undefined && caller !== null) {
+ if (!INTERMEDIATES_CALLERS.has(caller)) {
+ return json(400, { detail: `Unknown intermediates caller: ${String(caller)}` });
+ }
+
+ faults.intermediatesCaller = caller;
+ }
}
return json(200, { ok: true, faults: { ...faults } });
@@ -702,12 +729,26 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
if (method === 'GET' && path === '/api/v1/auth/status') {
return json(200, {
admin_email: null,
- multiuser_enabled: false,
+ multiuser_enabled: faults.intermediatesCaller === 'user',
setup_required: false,
strict_password_checking: false,
});
}
+ if (faults.intermediatesCaller === 'user' && path.startsWith('/api/v1/auth/')) {
+ if (method === 'POST' && path === '/api/v1/auth/login') {
+ return json(200, { expires_in: 86_400, token: MOCK_USER_TOKEN, user: mockNonAdminUser() });
+ }
+ if (method === 'GET' && path === '/api/v1/auth/me') {
+ return request.headers.authorization === `Bearer ${MOCK_USER_TOKEN}`
+ ? json(200, mockNonAdminUser())
+ : json(401, { detail: 'Not authenticated' });
+ }
+ if (method === 'POST' && (path === '/api/v1/auth/media-cookie' || path === '/api/v1/auth/logout')) {
+ return json(200, { success: true });
+ }
+ }
+
if (method === 'GET' && path === '/api/v1/image_map/points') {
const includeVideos = url.searchParams.get('include_videos') === 'true';
const points = imageMapPoints(state, includeVideos);
@@ -1072,18 +1113,37 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
}
if (method === 'GET' && path === '/api/v1/intermediates/summary') {
- const search = (url.searchParams.get('search') ?? '').trim().toLowerCase();
+ // Mirrors IntermediatesService.get_summary: non-admins see only their rows and may not name another owner.
+ const isAdmin = faults.intermediatesCaller === 'admin';
+ const ownerId = url.searchParams.get('owner_id');
+ if (!isAdmin && ownerId !== null && ownerId !== MOCK_USER_ID) {
+ return json(403, { detail: 'Only administrators can inspect other accounts' });
+ }
+ const ownerFilter = isAdmin ? ownerId : MOCK_USER_ID;
+ const projectId = url.searchParams.get('project_id');
+ const search = (url.searchParams.get('search') ?? '').toLowerCase();
const sort = url.searchParams.get('sort') ?? 'reclaimable_bytes';
const descending = (url.searchParams.get('order') ?? 'desc') === 'desc';
const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
const limit = Math.max(1, Number(url.searchParams.get('limit') ?? 50));
const rows = state.intermediates
- .filter((row) => !search || (row.project_name ?? '').toLowerCase().includes(search))
+ .filter((row) => ownerFilter === null || row.user_id === ownerFilter)
+ .filter((row) => projectId === null || row.project_id === projectId)
+ .filter(
+ (row) =>
+ !search ||
+ [row.project_name, ...(isAdmin ? [row.user_display_name, row.user_email] : [])].some((value) =>
+ (value ?? '').toLowerCase().includes(search)
+ )
+ )
.sort((left, right) =>
- sort === 'project_name'
- ? (left.project_name ?? '').localeCompare(right.project_name ?? '') * (descending ? -1 : 1)
- : (right.reclaimable_bytes - left.reclaimable_bytes) * (descending ? 1 : -1)
+ (left.project_name ?? '').toLowerCase().localeCompare((right.project_name ?? '').toLowerCase())
);
+ if (sort === 'reclaimable_bytes') {
+ rows.sort((left, right) => (right.reclaimable_bytes - left.reclaimable_bytes) * (descending ? 1 : -1));
+ } else if (descending) {
+ rows.reverse();
+ }
const totals = rows.reduce(
(acc, row) => ({
rows: acc.rows + 1,
@@ -1112,22 +1172,55 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
totals,
recent_grace_seconds: 1800,
measuring: false,
- can_manage_everyone: true,
+ can_manage_everyone: isAdmin,
});
}
if (method === 'POST' && path === '/api/v1/intermediates/previews') {
const requested = await readJsonBody(request);
+ // Mirrors IntermediatesService._authorize_scope.
+ const isAdmin = faults.intermediatesCaller === 'admin';
+ const scope = requested?.scope ?? {};
+ if (scope.kind === 'everyone' && !isAdmin) {
+ return json(403, { detail: "Only administrators can clear everyone's intermediates" });
+ }
+ if (scope.kind === 'owner' && !scope.user_id) {
+ return json(422, { detail: 'An owner scope names the account to clear' });
+ }
+ if (scope.kind === 'owner' && scope.user_id !== MOCK_USER_ID && !isAdmin) {
+ return json(403, { detail: "Only administrators can clear another account's intermediates" });
+ }
+ if (scope.kind === 'selection' && !(scope.targets?.length > 0)) {
+ return json(422, { detail: 'A selection scope names at least one row' });
+ }
+ if (scope.kind === 'selection' && !isAdmin && scope.targets.some((target) => target.user_id !== MOCK_USER_ID)) {
+ return json(403, { detail: "Only administrators can clear another account's intermediates" });
+ }
const previewId = `preview-${state.intermediatesPreviews.size + 1}`;
const targets =
- requested?.scope?.kind === 'selection'
+ scope.kind === 'selection'
? state.intermediates.filter((row) =>
- requested.scope.targets.some(
+ scope.targets.some(
(target) => target.user_id === row.user_id && (target.project_id ?? null) === row.project_id
)
)
- : state.intermediates;
+ : scope.kind === 'owner'
+ ? state.intermediates.filter((row) => row.user_id === scope.user_id)
+ : state.intermediates;
const force = requested?.mode === 'force';
+ const affectedDocuments = force
+ ? targets
+ .filter((row) => row.images.referenced + row.videos.referenced > 0)
+ .map((row) => ({
+ kind: 'project',
+ user_id: row.user_id,
+ user_display_name: row.user_display_name,
+ user_email: row.user_email,
+ owner_id: row.project_id ?? 'unassigned',
+ name: row.project_name,
+ references: row.images.referenced + row.videos.referenced,
+ }))
+ : [];
const impact = targets.reduce(
(acc, row) => ({
delete_images: acc.delete_images + row.images.safe + (force ? row.images.referenced : 0),
@@ -1166,19 +1259,8 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
expires_at: new Date(Date.now() + 600_000).toISOString(),
target_rows: targets.length,
impact,
- affected_documents: force
- ? targets
- .filter((row) => row.images.referenced + row.videos.referenced > 0)
- .map((row) => ({
- kind: 'project',
- user_id: row.user_id,
- user_display_name: row.user_display_name,
- user_email: row.user_email,
- owner_id: row.project_id ?? 'unassigned',
- name: row.project_name,
- references: row.images.referenced + row.videos.referenced,
- }))
- : [],
+ affected_documents: affectedDocuments.slice(0, 200),
+ affected_documents_total: affectedDocuments.length,
};
state.intermediatesPreviews.set(previewId, { preview, targets });
return json(201, preview);
@@ -1186,6 +1268,14 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
if (method === 'POST' && path === '/api/v1/intermediates/operations') {
const requested = await readJsonBody(request);
+ // Mirrors IntermediatesService.start_operation: a repeated key replays its operation, even once the
+ // single-use preview is gone.
+ const settled = state.intermediatesIdempotency.get(requested?.idempotency_key);
+ if (settled) {
+ return settled.previewId === requested.preview_id
+ ? json(202, state.intermediatesOperations.get(settled.operationId))
+ : json(409, { detail: 'Idempotency key was used for a different preview' });
+ }
const frozen = state.intermediatesPreviews.get(requested?.preview_id);
if (!frozen) {
return json(404, { detail: 'Preview expired or unknown; request a new one' });
@@ -1195,7 +1285,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
const { impact } = frozen.preview;
const operation = {
operation_id: operationId,
- user_id: 'fixture-user',
+ user_id: MOCK_USER_ID,
mode: frozen.preview.mode,
scope: frozen.preview.scope,
status: 'completed',
@@ -1238,6 +1328,12 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
row.unknown_size_count = 0;
}
state.intermediatesOperations.set(operationId, operation);
+ if (typeof requested.idempotency_key === 'string') {
+ state.intermediatesIdempotency.set(requested.idempotency_key, {
+ operationId,
+ previewId: requested.preview_id,
+ });
+ }
return json(202, operation);
}
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 46879ba068..e75050b3ab 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -118,6 +118,7 @@
"layoutPresetSnapshots.ts": "workbench",
"layoutPresets.ts": "workbench",
"layoutWidgetSet.ts": "workbench",
+ "mediaReferences.ts": "workbench",
"panZoom.ts": "workbench",
"performanceMarks.ts": "workbench",
"persistenceContracts.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
index d028081ae0..fb4b902a1b 100644
--- a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
@@ -30,6 +30,7 @@ import {
} from '@features/fonts';
import { useFontRuntime, useFontRuntimeSnapshot } from '@features/fonts/react';
import { useCapabilities } from '@features/identity';
+import { formatBytes } from '@platform/i18n/languages';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
assertAccountScopeCurrent,
@@ -264,19 +265,6 @@ const FontDetail = ({
);
};
-const formatBytes = (bytes: number): string => {
- if (!Number.isFinite(bytes) || bytes < 1) {
- return '0 B';
- }
- if (bytes < 1024) {
- return `${Math.round(bytes)} B`;
- }
- if (bytes < 1024 * 1024) {
- return `${(bytes / 1024).toFixed(1)} KB`;
- }
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-};
-
const UploadStatusList = ({ items }: { items: readonly UploadItem[] }) => {
const { t } = useTranslation('fonts');
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
index 14444ece96..50eca31b0c 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
@@ -29,7 +29,7 @@ export const UserManagement = () => {
export const UsersManagementPanel = ({
onManageIntermediates,
}: {
- onManageIntermediates?: (userId: string) => void;
+ onManageIntermediates?: (userId: string, label: string) => void;
}) => {
const { t } = useTranslation();
const session = useAuthSession();
@@ -52,7 +52,7 @@ const UsersDirectory = ({
onManageIntermediates,
}: {
currentUserId: string;
- onManageIntermediates?: (userId: string) => void;
+ onManageIntermediates?: (userId: string, label: string) => void;
}) => {
const { t } = useTranslation();
const notify = useIdentityNotify();
@@ -215,7 +215,7 @@ const UserRow = ({
user,
}: {
isSelf: boolean;
- onManageIntermediates?: (userId: string) => void;
+ onManageIntermediates?: (userId: string, label: string) => void;
setDeleteTarget: (user: UserDTO) => void;
setFormTarget: (target: UserFormTarget) => void;
setUserActive: (user: UserDTO, isActive: boolean) => void;
@@ -225,8 +225,8 @@ const UserRow = ({
const handleDelete = useCallback(() => setDeleteTarget(user), [setDeleteTarget, user]);
const handleEdit = useCallback(() => setFormTarget({ mode: 'edit', user }), [setFormTarget, user]);
const handleIntermediates = useCallback(
- () => onManageIntermediates?.(user.user_id),
- [onManageIntermediates, user.user_id]
+ () => onManageIntermediates?.(user.user_id, user.display_name || user.email),
+ [onManageIntermediates, user.display_name, user.email, user.user_id]
);
const handleSetActive = useCallback(
(event: { checked: boolean }) => void setUserActive(user, event.checked),
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
index a567a644d4..e5b2959c1f 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
@@ -3,7 +3,11 @@ import { useTranslation } from 'react-i18next';
import { UsersManagementPanel } from './UserManagement';
-export const UsersPage = ({ onManageIntermediates }: { onManageIntermediates?: (userId: string) => void }) => {
+export const UsersPage = ({
+ onManageIntermediates,
+}: {
+ onManageIntermediates?: (userId: string, label: string) => void;
+}) => {
const { t } = useTranslation();
return (
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
index 6b376b4335..a1f7ec9026 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
@@ -5,12 +5,14 @@ import type { IntermediatesRow } from './types';
import {
EMPTY_SELECTION,
isRowSelected,
+ resolveMatchingTargets,
resolveScope,
selectAllMatching,
summarizeSelection,
toggleRowSelection,
withRowSelected,
} from './selection';
+import { getIntermediatesRowKey } from './types';
const row = (projectId: string | null, overrides: Partial<IntermediatesRow> = {}): IntermediatesRow => ({
coverImageName: null,
@@ -55,7 +57,7 @@ describe('row selection', () => {
selection = toggleRowSelection(selection, secondPage[1]!);
expect(summarizeSelection(selection, totals)?.rows).toBe(2);
- expect(resolveScope({ hasSubsetFilter: false, loadedRows: secondPage, ownerId: 'alice', selection })).toEqual({
+ expect(resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection })).toEqual({
kind: 'selection',
targets: [
{ projectId: 'a', userId: 'alice' },
@@ -83,16 +85,18 @@ describe('row selection', () => {
reclaimableBytes: 300,
});
expect(toggleRowSelection(selection, page[1]!)).toEqual(selectAllMatching());
+ const request = resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection });
+ expect(request).toEqual({ kind: 'matching', excluded: new Set([getIntermediatesRowKey(page[1]!)]) });
expect(
- resolveScope({ hasSubsetFilter: false, loadedRows: [...page, row('off-page')], ownerId: 'alice', selection })
- ).toEqual({
- kind: 'selection',
- targets: [
- { userId: 'alice', projectId: 'a' },
- { userId: 'alice', projectId: null },
- { userId: 'alice', projectId: 'off-page' },
- ],
- });
+ resolveMatchingTargets(selection.mode === 'all-matching' ? selection.excluded : new Set(), [
+ ...page,
+ row('off-page'),
+ ])
+ ).toEqual([
+ { userId: 'alice', projectId: 'a' },
+ { userId: 'alice', projectId: null },
+ { userId: 'alice', projectId: 'off-page' },
+ ]);
expect(isRowSelected(selection, page[0]!)).toBe(true);
expect(isRowSelected(selection, page[1]!)).toBe(false);
expect(isRowSelected(selection, page[2]!)).toBe(true);
@@ -127,32 +131,29 @@ describe('selection summary', () => {
});
describe('scope resolution', () => {
- it('turns all-matching without a search into the owner or everyone scope', () => {
- expect(
- resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
- ).toEqual({ kind: 'owner', userId: 'alice' });
- expect(
- resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: null, selection: selectAllMatching() })
- ).toEqual({
+ it('turns all-matching without a filter into the owner or everyone scope', () => {
+ expect(resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection: selectAllMatching() })).toEqual({
+ kind: 'owner',
+ userId: 'alice',
+ });
+ expect(resolveScope({ hasSubsetFilter: false, ownerId: null, selection: selectAllMatching() })).toEqual({
kind: 'everyone',
});
});
- it('turns picks, and all-matching under a search, into explicit targets', () => {
+ it('turns picks into explicit targets whichever page showed them', () => {
const picks = toggleRowSelection(EMPTY_SELECTION, page[2]!);
- expect(resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: 'alice', selection: picks })).toEqual({
+ expect(resolveScope({ hasSubsetFilter: true, ownerId: 'alice', selection: picks })).toEqual({
kind: 'selection',
targets: [{ projectId: null, userId: 'alice' }],
});
- expect(
- resolveScope({ hasSubsetFilter: true, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
- ).toEqual({
- kind: 'selection',
- targets: page.map(({ projectId, userId }) => ({ projectId, userId })),
+ });
+
+ it('leaves all-matching under a filter unresolved rather than narrowing it to the loaded page', () => {
+ expect(resolveScope({ hasSubsetFilter: true, ownerId: 'alice', selection: selectAllMatching() })).toEqual({
+ kind: 'matching',
+ excluded: new Set(),
});
- expect(
- resolveScope({ hasSubsetFilter: true, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
- ).not.toEqual({ kind: 'owner', userId: 'alice' });
});
});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
index 897a053017..a12b2df9e8 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
@@ -125,34 +125,37 @@ export const summarizeSelection = (
return summary;
};
-export const selectionToTargets = (
- selection: IntermediatesSelection,
- loadedRows: readonly IntermediatesRow[]
-): IntermediatesScopeTarget[] =>
- [
- ...(selection.mode === 'all-matching'
- ? loadedRows.filter((row) => isRowSelected(selection, row))
- : selection.rows.values()),
- ].map(({ projectId, userId }) => ({
- projectId,
- userId,
- }));
+const toTarget = ({ projectId, userId }: IntermediatesScopeTarget): IntermediatesScopeTarget => ({ projectId, userId });
+
+/**
+ * What a confirmation acts on before it reaches the server. `matching` is every row the current filters match minus
+ * the exclusions; the cleanup scope cannot express filters, so it must be resolved against a complete matching read
+ * with `resolveMatchingTargets` before a preview is requested.
+ */
+export type IntermediatesScopeRequest = IntermediatesScope | { kind: 'matching'; excluded: ReadonlySet<string> };
/**
- * The scope a confirmation acts on. Without a row filter, "all matching" is exactly the owner filter (or everyone),
- * which the server can freeze without the client enumerating rows.
+ * Without a row filter or exclusions, "all matching" is exactly the owner filter (or everyone), which the server can
+ * freeze without the client enumerating rows. Explicit picks become their targets.
*/
export const resolveScope = (options: {
selection: IntermediatesSelection;
- loadedRows: readonly IntermediatesRow[];
hasSubsetFilter: boolean;
ownerId: string | null;
-}): IntermediatesScope => {
- const { hasSubsetFilter, loadedRows, ownerId, selection } = options;
+}): IntermediatesScopeRequest => {
+ const { hasSubsetFilter, ownerId, selection } = options;
- if (selection.mode === 'all-matching' && selection.excluded.size === 0 && !hasSubsetFilter) {
- return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
+ if (selection.mode === 'rows') {
+ return { kind: 'selection', targets: [...selection.rows.values()].map(toTarget) };
}
-
- return { kind: 'selection', targets: selectionToTargets(selection, loadedRows) };
+ if (selection.excluded.size > 0 || hasSubsetFilter) {
+ return { kind: 'matching', excluded: selection.excluded };
+ }
+ return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
};
+
+/** The explicit targets of a `matching` request, given every row the filters match. */
+export const resolveMatchingTargets = (
+ excluded: ReadonlySet<string>,
+ matchingRows: readonly IntermediatesRow[]
+): IntermediatesScopeTarget[] => matchingRows.filter((row) => !excluded.has(getIntermediatesRowKey(row))).map(toTarget);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
index fa02601f20..4107b3426d 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
@@ -110,6 +110,8 @@ export interface IntermediatesPreview {
hasMoreEligible: boolean;
impact: IntermediatesImpact;
affectedDocuments: IntermediatesAffectedDocument[];
+ /** Every affected document; the server lists only the first of them. */
+ affectedDocumentsTotal: number;
}
export interface IntermediatesOperationProgress {
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
index 121a9808fb..9b89db8ccd 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
@@ -79,6 +79,7 @@ describe('intermediates transport', () => {
const fetchMock = fetchJson(
{
affected_documents: [],
+ affected_documents_total: 0,
created_at: 'now',
expires_at: 'later',
has_more_eligible: true,
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
index fd39fec410..484c6fb03c 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
@@ -103,6 +103,7 @@ interface PreviewDTO {
has_more_eligible: boolean;
impact: ImpactDTO;
affected_documents: AffectedDocumentDTO[];
+ affected_documents_total: number;
}
interface ProgressDTO {
@@ -246,6 +247,57 @@ export const mapIntermediatesOperation = (dto: IntermediatesOperationDTO): Inter
userId: dto.user_id,
});
+const PROGRESS_KEYS = [
+ 'processed_images',
+ 'processed_videos',
+ 'deleted_images',
+ 'deleted_videos',
+ 'retained_images',
+ 'retained_videos',
+ 'failed_images',
+ 'failed_videos',
+ 'reclaimed_bytes',
+ 'unknown_size_count',
+ 'pending_disk_cleanup',
+ 'unresolved_images',
+ 'unresolved_videos',
+] as const satisfies readonly (keyof ProgressDTO)[];
+const OPERATION_STATUSES = new Set<unknown>(['pending', 'running', 'completed', 'failed']);
+const CLEANUP_MODES = new Set<unknown>(['safe', 'force']);
+
+const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;
+const isCount = (value: unknown): boolean => typeof value === 'number' && Number.isFinite(value);
+const isNullableString = (value: unknown): boolean => value === null || typeof value === 'string';
+
+const isScopeDTO = (value: unknown): value is ScopeDTO =>
+ isRecord(value) &&
+ (value.kind === 'everyone' ||
+ (value.kind === 'owner' && isNullableString(value.user_id)) ||
+ (value.kind === 'selection' &&
+ Array.isArray(value.targets) &&
+ value.targets.every(
+ (target) => isRecord(target) && typeof target.user_id === 'string' && isNullableString(target.project_id)
+ )));
+
+const isOperationDTO = (value: unknown): value is IntermediatesOperationDTO =>
+ isRecord(value) &&
+ typeof value.operation_id === 'string' &&
+ typeof value.user_id === 'string' &&
+ CLEANUP_MODES.has(value.mode) &&
+ OPERATION_STATUSES.has(value.status) &&
+ isScopeDTO(value.scope) &&
+ isCount(value.target_images) &&
+ isCount(value.target_videos) &&
+ isRecord(value.progress) &&
+ PROGRESS_KEYS.every((key) => isCount((value.progress as Record<string, unknown>)[key])) &&
+ [value.created_at, value.started_at, value.completed_at, value.error].every(isNullableString) &&
+ isNullableString(value.retried_from_operation_id) &&
+ isNullableString(value.retried_by_operation_id);
+
+/** Reads a socket event's operation, which arrives unvalidated; a malformed event yields null. */
+export const parseIntermediatesOperationEvent = (payload: unknown): IntermediatesOperation | null =>
+ isRecord(payload) && isOperationDTO(payload.operation) ? mapIntermediatesOperation(payload.operation) : null;
+
const buildSummaryUrl = (params: IntermediatesSummaryParams): string => {
const query = new URLSearchParams();
@@ -315,6 +367,7 @@ export const createIntermediatesPreview = async (
return {
affectedDocuments: dto.affected_documents.map(mapAffectedDocument),
+ affectedDocumentsTotal: dto.affected_documents_total,
createdAt: dto.created_at,
expiresAt: dto.expires_at,
impact: mapImpact(dto.impact),
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts b/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts
index 8d6fc0af15..60023f2a1b 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts
@@ -2,12 +2,15 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
- * What an entry point wants the manager to start on: a project to preselect, or an account to filter by. Consumed
- * once by the manager when it mounts, so a stale intent never resurfaces on a later visit.
+ * What an entry point wants the manager to start on: a project to preselect, or an account to filter by. The manager
+ * reads it while rendering and consumes it once that render commits, so a discarded render cannot lose it and a
+ * stale intent never resurfaces on a later visit.
*/
export interface IntermediatesFocus {
projectId?: string;
ownerId?: string;
+ /** How to name `ownerId` before any of its rows load. */
+ ownerLabel?: string;
}
const focusStore = createExternalStore<{ focus: IntermediatesFocus | null }>({ focus: null });
@@ -21,10 +24,11 @@ export const requestIntermediatesFocus = (focus: IntermediatesFocus): void => {
focusStore.setSnapshot({ focus });
};
-export const takeIntermediatesFocus = (): IntermediatesFocus | null => {
- const { focus } = focusStore.getSnapshot();
+export const peekIntermediatesFocus = (): IntermediatesFocus | null => focusStore.getSnapshot().focus;
- focusStore.setSnapshot({ focus: null });
-
- return focus;
+/** Clears `focus` unless a newer request has replaced it. */
+export const consumeIntermediatesFocus = (focus: IntermediatesFocus | null): void => {
+ if (focus !== null && focusStore.getSnapshot().focus === focus) {
+ focusStore.setSnapshot({ focus: null });
+ }
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
index e19dddb931..7d5b4bf1a2 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
@@ -1,11 +1,27 @@
-import { captureAccountScope, registerAccountOwnedResource, type AccountScope } from '@platform/state/accountLifecycle';
+import type { IntermediatesOperation } from '@features/intermediates/core/types';
+import type { QueryClient } from '@tanstack/react-query';
+
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import { getIntermediatesOperation, startIntermediatesOperation } from './api';
+import { intermediatesKeys } from './keys';
+import { attachIntermediatesRealtime } from './realtime';
+
/**
* The operation the manager is following. Kept outside the component so closing Settings while a cleanup runs and
* reopening it later shows the same operation, its result and its retry affordance.
*/
-export const activeOperationStore = createExternalStore<{ operationId: string | null }>({ operationId: null });
+export const activeOperationStore = createExternalStore<{
+ operationId: string | null;
+ /** Why replaying a start whose response was lost failed; cleared when the manager next opens. */
+ recoveryError: unknown;
+}>({ operationId: null, recoveryError: null });
interface PendingStart {
previewId: string;
@@ -13,9 +29,9 @@ interface PendingStart {
}
/**
- * A Confirm still in flight when the page reloads or the section closes is replayed once on the next mount; its
- * idempotency key makes the replay return the same operation. A start that settled with an error is cleared, so only
- * a fresh Confirm in the dialog can run it again.
+ * A Confirm whose response never arrived (a reload, a closed section, a timeout) is replayed once when the manager
+ * next opens; its idempotency key makes the replay return the same operation. A start that settled with an error is
+ * cleared, so only a fresh Confirm in the dialog can run it again.
*/
interface Receipt {
operationId?: string;
@@ -47,20 +63,11 @@ const writeReceipt = (receipt: Receipt, owner?: AccountScope): void => {
}
};
-/** Restores the followed operation and returns a start whose response was lost, if any. */
-export const restoreIntermediatesReceipt = (): PendingStart | null => {
- const receipt = readReceipt();
- if (typeof receipt.operationId === 'string' && receipt.operationId.length > 0) {
- activeOperationStore.setSnapshot({ operationId: receipt.operationId });
- }
- return receipt.pendingStart ?? null;
-};
-
export const recordPendingIntermediatesStart = (pendingStart: PendingStart): void => {
writeReceipt({ ...readReceipt(), pendingStart });
};
-export const isPendingIntermediatesStartCurrent = (pendingStart: PendingStart, owner?: AccountScope): boolean => {
+const isPendingStartCurrent = (pendingStart: PendingStart, owner?: AccountScope): boolean => {
const current = readReceipt(owner).pendingStart;
return current?.previewId === pendingStart.previewId && current.idempotencyKey === pendingStart.idempotencyKey;
};
@@ -72,11 +79,114 @@ export const clearPendingIntermediatesStart = (owner?: AccountScope): void => {
};
registerAccountOwnedResource({
- clear: () => activeOperationStore.setSnapshot({ operationId: null }),
+ clear: () => activeOperationStore.setSnapshot({ operationId: null, recoveryError: null }),
name: 'intermediates-active-operation',
});
export const followIntermediatesOperation = (operationId: string | null): void => {
- activeOperationStore.setSnapshot({ operationId });
+ activeOperationStore.patchSnapshot({ operationId });
writeReceipt({ operationId: operationId ?? undefined });
};
+
+/** Follows an operation the server just returned, seeding its query so the panel needs no extra lookup. */
+export const adoptIntermediatesOperation = (
+ queryClient: QueryClient,
+ owner: AccountScope,
+ operation: IntermediatesOperation
+): void => {
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+};
+
+/** Walks the retry chain to the operation that currently owns the unresolved targets. */
+export const findLatestIntermediatesRetry = async (
+ operationId: string,
+ signal: AbortSignal
+): Promise<IntermediatesOperation> => {
+ let operation = await getIntermediatesOperation(operationId, signal);
+ const visited = new Set<string>([operationId]);
+ while (operation.retriedByOperationId && !visited.has(operation.retriedByOperationId)) {
+ visited.add(operation.retriedByOperationId);
+ operation = await getIntermediatesOperation(operation.retriedByOperationId, signal);
+ }
+ return operation;
+};
+
+let attachedManagers = 0;
+// Single-flight per account and receipt, so a remount (or StrictMode's replayed mount) never repeats the request.
+const reconciling = new Set<string>();
+
+const runOnce = (key: string, work: () => Promise<void>): void => {
+ if (reconciling.has(key)) {
+ return;
+ }
+ reconciling.add(key);
+ void work().finally(() => reconciling.delete(key));
+};
+
+const replayPendingStart = (queryClient: QueryClient, owner: AccountScope, pending: PendingStart): void => {
+ runOnce(`${receiptKey(owner)}\u0000start\u0000${pending.idempotencyKey}`, async () => {
+ try {
+ const operation = await startIntermediatesOperation(pending, owner.signal);
+ if (isAccountScopeCurrent(owner) && isPendingStartCurrent(pending)) {
+ adoptIntermediatesOperation(queryClient, owner, operation);
+ }
+ } catch (error) {
+ if (isPendingStartCurrent(pending, owner)) {
+ clearPendingIntermediatesStart(owner);
+ if (attachedManagers > 0 && isAccountScopeCurrent(owner)) {
+ activeOperationStore.patchSnapshot({ recoveryError: error });
+ }
+ }
+ }
+ });
+};
+
+const catchUpWithRetry = (queryClient: QueryClient, owner: AccountScope, followed: string): void => {
+ runOnce(`${receiptKey(owner)}\u0000retry\u0000${followed}`, async () => {
+ try {
+ const operation = await findLatestIntermediatesRetry(followed, owner.signal);
+ if (
+ isAccountScopeCurrent(owner) &&
+ activeOperationStore.getSnapshot().operationId === followed &&
+ operation.operationId !== followed
+ ) {
+ adoptIntermediatesOperation(queryClient, owner, operation);
+ }
+ } catch {
+ // The operation query reports lookup failures in the panel.
+ }
+ });
+};
+
+/**
+ * Registers an open manager: attaches realtime updates for its lifetime and reconciles the receipt, replaying a
+ * Confirm whose response was lost or catching up with a retry started elsewhere.
+ */
+export const attachIntermediatesManager = (queryClient: QueryClient): (() => void) => {
+ if (attachedManagers === 0) {
+ activeOperationStore.patchSnapshot({ recoveryError: null });
+ }
+ attachedManagers += 1;
+ const detachRealtime = attachIntermediatesRealtime(queryClient);
+ const owner = captureAccountScope();
+ const receipt = readReceipt(owner);
+ if (typeof receipt.operationId === 'string' && receipt.operationId.length > 0) {
+ activeOperationStore.patchSnapshot({ operationId: receipt.operationId });
+ }
+ const followed = activeOperationStore.getSnapshot().operationId;
+ if (receipt.pendingStart) {
+ replayPendingStart(queryClient, owner, receipt.pendingStart);
+ } else if (followed) {
+ catchUpWithRetry(queryClient, owner, followed);
+ }
+
+ let attached = true;
+ return () => {
+ if (attached) {
+ attached = false;
+ attachedManagers -= 1;
+ detachRealtime();
+ }
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
index ca4dd0404a..d12af0c6b0 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
@@ -6,12 +6,20 @@ import { afterEach, expect, it, vi } from 'vitest';
const hub = vi.hoisted(() => ({
connection: null as ConnectionListener | null,
+ operationChanged: null as ((payload: unknown) => void) | null,
status: 'connected' as BackendConnectionStatus,
}));
vi.mock('@platform/transport/socketHub', () => ({
socketHub: {
- on: () => () => undefined,
+ on: (event: string, listener: (payload: unknown) => void) => {
+ if (event === 'intermediates_operation_changed') {
+ hub.operationChanged = listener;
+ }
+ return () => {
+ hub.operationChanged = null;
+ };
+ },
onConnectionChange: (listener: ConnectionListener) => {
hub.connection = listener;
listener(hub.status);
@@ -23,6 +31,41 @@ vi.mock('@platform/transport/socketHub', () => ({
}));
const { attachIntermediatesRealtime } = await import('./realtime');
+const { intermediatesKeys } = await import('./keys');
+const { captureAccountScope } = await import('@platform/state/accountLifecycle');
+
+const operationEvent = (status: string, operationId = 'op-1') => ({
+ operation: {
+ completed_at: status === 'completed' ? 'later' : null,
+ created_at: 'now',
+ error: null,
+ mode: 'safe',
+ operation_id: operationId,
+ progress: {
+ deleted_images: 1,
+ deleted_videos: 0,
+ failed_images: 0,
+ failed_videos: 0,
+ pending_disk_cleanup: 0,
+ processed_images: 1,
+ processed_videos: 0,
+ reclaimed_bytes: 10,
+ retained_images: 0,
+ retained_videos: 0,
+ unknown_size_count: 0,
+ unresolved_images: 0,
+ unresolved_videos: 0,
+ },
+ retried_by_operation_id: null,
+ retried_from_operation_id: null,
+ scope: { kind: 'owner', targets: [], user_id: 'alice' },
+ started_at: 'now',
+ status,
+ target_images: 2,
+ target_videos: 0,
+ user_id: 'alice',
+ },
+});
afterEach(() => {
hub.status = 'connected';
@@ -50,3 +93,34 @@ it('refetches once the socket connects after opening while disconnected', () =>
expect(invalidate).toHaveBeenCalledOnce();
detach();
});
+
+it('stores socket operations and invalidates the account summaries once when one settles', () => {
+ const queryClient = new QueryClient();
+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries');
+ const detach = attachIntermediatesRealtime(queryClient);
+ const key = intermediatesKeys.operation(captureAccountScope(), 'op-1');
+
+ hub.operationChanged!(operationEvent('running'));
+ expect(queryClient.getQueryData(key)).toMatchObject({ operationId: 'op-1', status: 'running' });
+ expect(invalidate).not.toHaveBeenCalled();
+
+ hub.operationChanged!(operationEvent('completed'));
+ hub.operationChanged!(operationEvent('completed'));
+ expect(queryClient.getQueryData(key)).toMatchObject({ status: 'completed' });
+ expect(invalidate).toHaveBeenCalledOnce();
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: intermediatesKeys.summaries(captureAccountScope()) });
+ detach();
+});
+
+it('ignores malformed socket events without throwing', () => {
+ const queryClient = new QueryClient();
+ const setQueryData = vi.spyOn(queryClient, 'setQueryData');
+ const detach = attachIntermediatesRealtime(queryClient);
+ const { progress: _progress, ...withoutProgress } = operationEvent('completed').operation;
+
+ for (const payload of [undefined, null, 'x', {}, { operation: null }, { operation: withoutProgress }]) {
+ expect(() => hub.operationChanged!(payload)).not.toThrow();
+ }
+ expect(setQueryData).not.toHaveBeenCalled();
+ detach();
+});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
index b5b05eb4d4..43f4319277 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
@@ -4,9 +4,7 @@ import { isOperationSettled, type IntermediatesOperation } from '@features/inter
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { socketHub } from '@platform/transport/socketHub';
-import type { IntermediatesOperationDTO } from './api';
-
-import { mapIntermediatesOperation } from './api';
+import { parseIntermediatesOperationEvent } from './api';
import { intermediatesKeys } from './keys';
const isOperationKey = (queryKey: readonly unknown[], accountKey: readonly unknown[]): boolean =>
@@ -47,15 +45,10 @@ export const attachIntermediatesRealtime = (queryClient: QueryClient): (() => vo
});
const detachOperation = socketHub.on('intermediates_operation_changed', (payload: never) => {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
- const event = payload as unknown as { operation?: IntermediatesOperationDTO } | undefined;
-
- if (!event?.operation) {
+ const operation: IntermediatesOperation | null = parseIntermediatesOperationEvent(payload);
+ if (!operation || !isAccountScopeCurrent(owner)) {
return;
}
- const operation = mapIntermediatesOperation(event.operation);
queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
noteSettled(operation);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
index 282d1030e3..6f2f289fd0 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
@@ -124,17 +124,26 @@ it('releases on pagehide and holds again when the page is restored', async () =>
}
});
-it('does not resend an unchanged hold each time the tab becomes visible', async () => {
+it('refreshes an unchanged hold on becoming visible only after missing a heartbeat', async () => {
const lease = startWith({ images: ['held.png'], videos: [] });
+ const startedAt = Date.now();
+ const clock = vi.spyOn(Date, 'now');
try {
await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));
await settle();
expect(document.visibilityState).toBe('visible');
+ clock.mockReturnValue(startedAt + 2 * 60_000);
document.dispatchEvent(new Event('visibilitychange'));
document.dispatchEvent(new Event('visibilitychange'));
await settle();
expect(calls('PUT')).toHaveLength(1);
+
+ clock.mockReturnValue(startedAt + 6 * 60_000);
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(2));
+ expect(calls('PUT')[1]!.url).toBe(calls('PUT')[0]!.url);
} finally {
+ clock.mockRestore();
lease.stop();
}
});
@@ -147,7 +156,7 @@ it('keeps old batches held until every replacement batch is installed', async ()
let exposed = false;
let failSecondStagedBatch = true;
fetchMock.mockImplementation((url, options) => {
- if (started && options?.method === 'PUT' && String(url).endsWith('-1-1') && failSecondStagedBatch) {
+ if (started && options?.method === 'PUT' && String(url).endsWith('.1-1') && failSecondStagedBatch) {
failSecondStagedBatch = false;
throw new Error('temporary network failure');
}
@@ -172,6 +181,9 @@ it('keeps old batches held until every replacement batch is installed', async ()
lease.update({ images: ['a.png', ...imageNames], videos: [] });
await vi.waitFor(() => expect(initialLeases.every((leaseUrl) => !held.has(leaseUrl))).toBe(true));
expect(exposed).toBe(false);
+ // The server caps distinct holders per account, grouping every `<holder>.<part>` id under its holder.
+ const holders = new Set(calls('PUT').map(({ url }) => decodeURIComponent(url.split('/').at(-1)!).split('.')[0]));
+ expect(holders.size).toBe(1);
} finally {
lease.stop();
}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
index ce0ed7bfa3..fd376a77cf 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
@@ -13,12 +13,18 @@ export const MAX_HOLD_NAMES_PER_KIND = 50_000;
/** The server keeps a lease for 15 minutes; refreshing well inside that survives a missed beat. */
const HEARTBEAT_MS = 5 * 60_000;
-const RESEND_ON_VISIBLE_AFTER_MS = 60_000;
+/** A tab back from a stretch long enough that throttled timers may have missed the heartbeat. */
+const RESEND_ON_VISIBLE_AFTER_MS = HEARTBEAT_MS;
const CHANGE_DEBOUNCE_MS = 250;
type Batch = { images: string[]; videos: string[] };
+/** Each batch's request body, which also serves as its signature. */
+type Plan = string[];
type Slot = 0 | 1;
+const sameNames = (left: ReadonlySet<string>, right: ReadonlySet<string>): boolean =>
+ left.size === right.size && [...left].every((name) => right.has(name));
+
const holdPath = (leaseId: string): string => `/api/v1/intermediates/holds/${encodeURIComponent(leaseId)}`;
/** Each request stays within the per-kind limit; sorted input keeps unchanged batches byte-identical. */
@@ -45,7 +51,7 @@ export const startIntermediatesHoldLease = ({
subscribe,
}: {
owner: AccountScope;
- /** Current names to hold, in any order. */
+ /** Current names to hold, in any order; returning the previous object again means nothing changed. */
read: () => HeldMediaNames;
/** Notifies when `read` may return something new. */
subscribe: (onChange: () => void) => () => void;
@@ -59,10 +65,11 @@ export const startIntermediatesHoldLease = ({
let pendingRefresh = false;
let lastSentAt = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
+ let planned: { held: HeldMediaNames; images: Set<string>; plan: Plan; videos: Set<string> } | null = null;
// Releases must authenticate as the account that took the lease, even after sign-out cleared the session.
let leaseToken: string | null = null;
- const batchLeaseId = (slot: Slot, index: number): string => `${leaseId}-${slot}-${index}`;
+ const batchLeaseId = (slot: Slot, index: number): string => `${leaseId}.${slot}-${index}`;
const isStopped = (): boolean => disposed || owner.signal.aborted;
const fireRelease = (id: string): void => {
@@ -103,14 +110,14 @@ export const startIntermediatesHoldLease = ({
}
};
- const putBatch = async (slot: Slot, index: number, batch: Batch): Promise<boolean> => {
+ const putBatch = async (slot: Slot, index: number, body: string): Promise<boolean> => {
if (isStopped()) {
return false;
}
const token = getHttpAuthToken();
try {
await apiFetch(holdPath(batchLeaseId(slot, index)), {
- body: JSON.stringify(batch),
+ body,
headers: { 'Content-Type': 'application/json' },
method: 'PUT',
signal: owner.signal,
@@ -124,29 +131,43 @@ export const startIntermediatesHoldLease = ({
fireRelease(batchLeaseId(slot, index));
return false;
}
- leaseSignatures[slot][index] = JSON.stringify([batch.images, batch.videos]);
+ leaseSignatures[slot][index] = body;
return true;
};
+ /** Sorting and serialising up to 50k names per kind is the expensive part; an unchanged set reuses its plan. */
+ const planFor = (held: HeldMediaNames): Plan => {
+ if (planned?.held === held) {
+ return planned.plan;
+ }
+ const imageSet = new Set(held.images);
+ const videoSet = new Set(held.videos);
+ if (planned && sameNames(imageSet, planned.images) && sameNames(videoSet, planned.videos)) {
+ planned.held = held;
+ return planned.plan;
+ }
+ const plan = partitionHeldMediaNames([...imageSet].sort(), [...videoSet].sort()).map((batch) =>
+ JSON.stringify(batch)
+ );
+ planned = { held, images: imageSet, plan, videos: videoSet };
+ return plan;
+ };
+
const sendOnce = async (refresh: boolean): Promise<void> => {
- const held = read();
- const images = [...new Set(held.images)].sort();
- const videos = [...new Set(held.videos)].sort();
- if (!images.length && !videos.length) {
+ const bodies = planFor(read());
+ if (!bodies.length) {
await releaseSlot(0);
await releaseSlot(1);
activeSlot = null;
return;
}
- const batches = partitionHeldMediaNames(images, videos);
- const signatures = batches.map((batch) => JSON.stringify([batch.images, batch.videos]));
const current = activeSlot === null ? null : leaseSignatures[activeSlot];
let trimActive = false;
- if (current && current.length === signatures.length && signatures.every((value, i) => value === current[i])) {
+ if (current && current.length === bodies.length && bodies.every((value, i) => value === current[i])) {
if (refresh) {
let refreshed = true;
- for (let index = 0; index < batches.length; index += 1) {
- refreshed = (await putBatch(activeSlot!, index, batches[index]!)) && refreshed;
+ for (let index = 0; index < bodies.length; index += 1) {
+ refreshed = (await putBatch(activeSlot!, index, bodies[index]!)) && refreshed;
}
if (refreshed) {
lastSentAt = Date.now();
@@ -156,8 +177,8 @@ export const startIntermediatesHoldLease = ({
} else {
const nextSlot: Slot = activeSlot === 0 ? 1 : 0;
let staged = true;
- for (let index = 0; index < batches.length; index += 1) {
- staged = (await putBatch(nextSlot, index, batches[index]!)) && staged;
+ for (let index = 0; index < bodies.length; index += 1) {
+ staged = (await putBatch(nextSlot, index, bodies[index]!)) && staged;
}
if (staged && !isStopped()) {
const oldSlot = activeSlot;
@@ -171,7 +192,7 @@ export const startIntermediatesHoldLease = ({
}
if (activeSlot !== null) {
if (trimActive) {
- await releaseSlot(activeSlot, batches.length);
+ await releaseSlot(activeSlot, bodies.length);
}
await releaseSlot(activeSlot === 0 ? 1 : 0);
}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/index.ts b/invokeai/frontend/webv2/src/features/intermediates/index.ts
index c65e2a518c..9b395b3ec7 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/index.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/index.ts
@@ -1,11 +1 @@
-export type {
- IntermediatesCleanupMode,
- IntermediatesOperation,
- IntermediatesPreview,
- IntermediatesRow,
- IntermediatesScope,
- IntermediatesScopeTarget,
- IntermediatesSummary,
-} from './core/types';
-export { requestIntermediatesFocus, type IntermediatesFocus } from './data/focus';
-export { intermediatesKeys, type IntermediatesSummaryParams } from './data/keys';
+export { requestIntermediatesFocus } from './data/focus';
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
index 933c2e98ae..30497b6358 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
@@ -1,20 +1,17 @@
import type {
- IntermediatesAffectedDocument,
IntermediatesAffectedDocumentKind,
IntermediatesCleanupMode,
IntermediatesPreview,
} from '@features/intermediates/core/types';
/* eslint-disable react-perf/jsx-no-new-function-as-prop */
-import type { RefObject } from 'react';
import { Alert, Box, chakra, Checkbox, Dialog, Input, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
+import { formatBytes } from '@platform/i18n/languages';
import { Button, CloseButton } from '@platform/ui/Button';
-import { useCallback, useId, useState } from 'react';
+import { useCallback, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { formatBytes } from './format';
-
-const CONFIRM_WORD = 'CLEAR';
+const CONFIRM_WORD = 'DELETE';
const AFFECTED_DOCUMENT_LABELS = {
client_state: 'intermediates.dialog.affectedClientState',
@@ -40,9 +37,8 @@ export interface ClearDialogProps {
currentUserId: string | null;
/** Force previews for administrators may include other accounts' documents; others' are never touched. */
canManageEveryone: boolean;
- finalFocusRef: RefObject<HTMLElement | null>;
- /** Receives focus when the trigger can no longer take it, e.g. a Delete button disabled by the cleared selection. */
- fallbackFocusRef: RefObject<HTMLElement | null>;
+ /** Where focus lands when the dialog closes. */
+ getFinalFocus: () => HTMLElement | null;
onClose: () => void;
onConfirm: () => void;
onRetryPreview: () => void;
@@ -104,9 +100,6 @@ const Impact = ({ preview }: { preview: IntermediatesPreview }) => {
);
};
-const getDocumentOwnerLabel = (document: IntermediatesAffectedDocument): string =>
- document.userDisplayName || document.userEmail || document.userId;
-
const AffectedDocuments = ({
currentUserId,
preview,
@@ -115,6 +108,7 @@ const AffectedDocuments = ({
preview: IntermediatesPreview;
}) => {
const { t } = useTranslation();
+ const hidden = preview.affectedDocumentsTotal - preview.affectedDocuments.length;
if (preview.affectedDocuments.length === 0) {
return null;
@@ -135,11 +129,18 @@ const AffectedDocuments = ({
{currentUserId !== null && document.userId !== currentUserId ? (
<Text as="span" color="fg.muted">
{' '}
- {t('intermediates.dialog.affectedOwner', { owner: getDocumentOwnerLabel(document) })}
+ {t('intermediates.dialog.affectedOwner', {
+ owner: document.userDisplayName || document.userEmail || t('intermediates.owner.unknownAccount'),
+ })}
</Text>
) : null}
</Text>
))}
+ {hidden > 0 ? (
+ <Text as="li" color="fg.muted" fontSize="xs">
+ {t('intermediates.dialog.affectedMore', { count: hidden })}
+ </Text>
+ ) : null}
</Stack>
</Stack>
);
@@ -152,8 +153,7 @@ const AffectedDocuments = ({
export const ClearDialog = ({
canManageEveryone,
currentUserId,
- fallbackFocusRef,
- finalFocusRef,
+ getFinalFocus,
onClose,
onConfirm,
onModeChange,
@@ -168,6 +168,7 @@ export const ClearDialog = ({
typed: '',
});
const confirmInputId = useId();
+ const cancelRef = useRef<HTMLButtonElement | null>(null);
const isForce = state?.mode === 'force';
const preview = state?.preview ?? null;
const acknowledged = confirmation.previewId === preview?.previewId && confirmation.acknowledged;
@@ -196,11 +197,9 @@ export const ClearDialog = ({
<Dialog.Root
closeOnEscape={!state?.isStarting}
closeOnInteractOutside={!state?.isStarting}
- finalFocusEl={() => {
- const trigger = finalFocusRef.current;
-
- return trigger && !(trigger as HTMLButtonElement).disabled ? trigger : fallbackFocusRef.current;
- }}
+ finalFocusEl={getFinalFocus}
+ // Cancel, not the force toggle: Space on a first-tabbable checkbox would switch to a force preview.
+ initialFocusEl={() => cancelRef.current}
lazyMount
open={state !== null}
role="alertdialog"
@@ -222,7 +221,7 @@ export const ClearDialog = ({
<Stack gap="3">
{/* zag snapshots aria-describedby at open, so the Description must exist before the preview lands. */}
<Dialog.Description asChild>
- <Box>
+ <Box aria-busy={(preview === null && !state?.previewError) || undefined} aria-live="polite">
{state?.previewError ? (
<Alert.Root size="sm" status="error" variant="surface">
<Alert.Indicator />
@@ -314,7 +313,7 @@ export const ClearDialog = ({
</Stack>
</Dialog.Body>
<Dialog.Footer>
- <Button disabled={state?.isStarting} size="xs" variant="ghost" onClick={onClose}>
+ <Button ref={cancelRef} disabled={state?.isStarting} size="xs" variant="ghost" onClick={onClose}>
{t('common.cancel')}
</Button>
<Button
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
index 530e0ef459..fec8b64d73 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
@@ -4,17 +4,28 @@ import type { TFunction } from 'i18next';
import { Badge, Checkbox, Flex, HStack, Icon, Image, Stack, Text } from '@chakra-ui/react';
import { getIntermediatesRowKey, getKindInUse } from '@features/intermediates/core/types';
+import { formatBytes, formatCount } from '@platform/i18n/languages';
import { absolutizeApiUrl } from '@platform/transport/http';
import { Row } from '@platform/ui/Row';
import { FolderIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { formatBytes, formatCount } from './format';
-
export const getRowLabel = (row: IntermediatesRow, unassignedLabel: string): string =>
row.projectId === null ? unassignedLabel : row.projectName || row.projectId;
-export const getOwnerLabel = (row: IntermediatesRow): string => row.userDisplayName || row.userEmail || row.userId;
+export const getOwnerLabel = (row: IntermediatesRow, t: TFunction): string =>
+ row.userDisplayName || row.userEmail || t('intermediates.owner.unknownAccount');
+
+/**
+ * Adds the email to a display name, or a short id to an account with neither, so rows of different accounts stay
+ * distinguishable to assistive tech.
+ */
+const getOwnerAccessibleLabel = (row: IntermediatesRow, t: TFunction): string =>
+ row.userDisplayName && row.userEmail
+ ? t('intermediates.owner.nameWithEmail', { email: row.userEmail, name: row.userDisplayName })
+ : row.userDisplayName || row.userEmail
+ ? getOwnerLabel(row, t)
+ : t('intermediates.owner.unknownAccountWithId', { id: row.userId.slice(0, 8) });
const Cover = ({ imageName }: { imageName: string | null }) =>
imageName ? (
@@ -66,7 +77,7 @@ const describeRow = (row: IntermediatesRow, showOwner: boolean, t: TFunction): s
unmeasured: row.unknownSizeCount > 0 ? t('intermediates.list.unmeasured', { count: row.unknownSizeCount }) : '',
}).trim();
- return showOwner ? t('intermediates.list.ownerAndSize', { owner: getOwnerLabel(row), size }) : size;
+ return showOwner ? t('intermediates.list.ownerAndSize', { owner: getOwnerLabel(row, t), size }) : size;
};
export interface IntermediatesListProps {
@@ -117,11 +128,7 @@ export const IntermediatesList = ({ isBusy, isSelected, onToggleRow, rows, showO
<Checkbox.Root
aria-label={
showOwner
- ? t('intermediates.list.selectRowForOwner', {
- name: label,
- owner: getOwnerLabel(row),
- userId: row.userId,
- })
+ ? t('intermediates.list.selectRowForOwner', { name: label, owner: getOwnerAccessibleLabel(row, t) })
: t('intermediates.list.selectRow', { name: label })
}
checked={selected}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
index 0c17676cd6..ef77403d2c 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
@@ -10,7 +10,7 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
-import { act } from 'react';
+import { act, StrictMode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { page } from 'vitest/browser';
@@ -84,16 +84,16 @@ const documentOf = (userId: string) => ({
userId,
});
+const forceAffectedDocuments: IntermediatesPreview['affectedDocuments'] = [
+ { ...documentOf('alice'), kind: 'project', name: 'Portraits', ownerId: 'p1', references: 2 },
+ { ...documentOf('alice'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
+ { ...documentOf('alice'), kind: 'quarantined_project', name: 'Old sketch', ownerId: 'q1', references: 1 },
+ { ...documentOf('bob'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
+];
+
const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesPreview => ({
- affectedDocuments:
- mode === 'force'
- ? [
- { ...documentOf('alice'), kind: 'project', name: 'Portraits', ownerId: 'p1', references: 2 },
- { ...documentOf('alice'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
- { ...documentOf('alice'), kind: 'quarantined_project', name: 'Old sketch', ownerId: 'q1', references: 1 },
- { ...documentOf('bob'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
- ]
- : [],
+ affectedDocuments: mode === 'force' ? forceAffectedDocuments : [],
+ affectedDocumentsTotal: mode === 'force' ? forceAffectedDocuments.length : 0,
createdAt: 'now',
expiresAt: 'later',
impact: {
@@ -151,7 +151,14 @@ let root: Root;
let queryClient: QueryClient;
const renderManager = async (
- options: { focusProjectId?: string; currentUserId?: string | null; canClearOthersIntermediates?: boolean } = {}
+ options: {
+ focusProjectId?: string;
+ focusOwner?: { ownerId: string; ownerLabel?: string };
+ currentUserId?: string | null;
+ currentUserLabel?: string;
+ canClearOthersIntermediates?: boolean;
+ strict?: boolean;
+ } = {}
): Promise<void> => {
host = document.createElement('div');
host.style.height = '640px';
@@ -164,20 +171,22 @@ const renderManager = async (
const { requestIntermediatesFocus } = await import('@features/intermediates/data/focus');
const { IntermediatesManager } = await import('./IntermediatesManager');
- if (options.focusProjectId) {
- requestIntermediatesFocus({ projectId: options.focusProjectId });
+ if (options.focusProjectId || options.focusOwner) {
+ requestIntermediatesFocus({ projectId: options.focusProjectId, ...options.focusOwner });
}
+ const manager = (
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <IntermediatesManager
+ canClearOthersIntermediates={options.canClearOthersIntermediates ?? false}
+ currentUserId={options.currentUserId === undefined ? 'alice' : options.currentUserId}
+ currentUserLabel={options.currentUserLabel}
+ />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
await act(() => {
- root.render(
- <ChakraProvider value={system}>
- <QueryClientProvider client={queryClient}>
- <IntermediatesManager
- canClearOthersIntermediates={options.canClearOthersIntermediates ?? false}
- currentUserId={options.currentUserId === undefined ? 'alice' : options.currentUserId}
- />
- </QueryClientProvider>
- </ChakraProvider>
- );
+ root.render(options.strict ? <StrictMode>{manager}</StrictMode> : manager);
});
};
@@ -198,6 +207,23 @@ const buttonWithText = (text: string, scope: ParentNode = document): HTMLButtonE
return button!;
};
+/** Serves `operation` to polls and pushes it into the cache the way a realtime update does, without waiting a poll. */
+const followOperation = async (initial: IntermediatesOperation) => {
+ const { intermediatesOperationQueryOptions } = await import('@features/intermediates/data/queries');
+ let current = initial;
+ dependencies.getIntermediatesOperation.mockImplementation(() => Promise.resolve(current));
+ return async (next: IntermediatesOperation) => {
+ current = next;
+ await act(() => {
+ queryClient.setQueryData(intermediatesOperationQueryOptions(next.operationId).queryKey, next);
+ });
+ };
+};
+
+/** Delete stays focusable while unavailable, so the reason it waits can be announced. */
+const isDeleteUnavailable = (): boolean =>
+ buttonWithText('intermediates.list.delete', host).getAttribute('aria-disabled') === 'true';
+
const setInputValue = (input: HTMLInputElement, value: string) => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
setter.call(input, value);
@@ -220,7 +246,7 @@ const openForceDialogReadyToConfirm = async (
await act(() => toggles()[0]!.click());
await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.affectedClientState'));
await act(() => toggles()[1]!.click());
- await act(() => setInputValue(dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])')!, 'CLEAR'));
+ await act(() => setInputValue(dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])')!, 'DELETE'));
return dialog;
};
@@ -283,7 +309,10 @@ describe('IntermediatesManager', () => {
summaryOf(
params.ownerId
? [row(null, null, 1)]
- : [row(null, null, 1), { ...row(null, null, 1), userDisplayName: 'Alice', userId: 'bob' }]
+ : [
+ row(null, null, 1),
+ { ...row(null, null, 1), userDisplayName: 'Alice', userEmail: '[email protected]', userId: 'bob' },
+ ]
)
)
);
@@ -295,8 +324,8 @@ describe('IntermediatesManager', () => {
element.getAttribute('aria-label')
);
expect(names).toEqual([
- 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=Alice,userId=alice)',
- 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=Alice,userId=bob)',
+ 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=intermediates.owner.nameWithEmail([email protected],name=Alice))',
+ 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=intermediates.owner.nameWithEmail([email protected],name=Alice))',
]);
});
@@ -340,6 +369,68 @@ describe('IntermediatesManager', () => {
);
});
+ it('moves focus to the started operation, whose status the Delete control no longer reflects', async () => {
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ const dialog = await vi.waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ await act(() => buttonWithText('intermediates.dialog.confirm', dialog).click());
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ await vi.waitFor(() => {
+ const focused = document.activeElement as HTMLElement;
+ expect(focused.getAttribute('tabindex')).toBe('-1');
+ expect(focused.textContent).toContain('intermediates.operation.status.running');
+ });
+ });
+
+ it.each([
+ ['its rows', { currentUserId: 'alice' }, 'Alice'],
+ ['the entry point', { currentUserId: 'alice', focusOwner: { ownerId: 'bob-3f1c9a7e', ownerLabel: 'Bob' } }, 'Bob'],
+ ['the signed-in account', { currentUserId: 'carol-5d2e8b10', currentUserLabel: 'Carol' }, 'Carol'],
+ ['nothing', { currentUserId: 'dave-9a0b1c2d' }, 'intermediates.owner.unknownAccount'],
+ ] as const)('names the account filter from %s without showing its id', async (_source, options, name) => {
+ if (name !== 'Alice') {
+ dependencies.getIntermediatesSummary.mockReset().mockResolvedValue(summaryOf([]));
+ }
+ await renderManager({ canClearOthersIntermediates: true, ...options });
+ await vi.waitFor(() => expect(host.textContent).toContain(`intermediates.owner.filtered(name=${name})`));
+ const ownerId = 'focusOwner' in options ? options.focusOwner.ownerId : options.currentUserId;
+ expect(host.textContent).not.toContain(ownerId);
+ });
+
+ it('tells apart rows of accounts that have neither a name nor an email', async () => {
+ const anonymous = (userId: string): IntermediatesRow => ({
+ ...row(null, null, 1),
+ userDisplayName: null,
+ userEmail: null,
+ userId,
+ });
+ dependencies.getIntermediatesSummary
+ .mockReset()
+ .mockResolvedValue(summaryOf([anonymous('0a1b2c3d-first'), anonymous('9f8e7d6c-second')]));
+ await renderManager({ canClearOthersIntermediates: true });
+ const showEveryone = await vi.waitFor(() => {
+ const button = host.querySelector<HTMLButtonElement>('button[aria-label="intermediates.owner.showEveryone"]');
+ expect(button).not.toBeNull();
+ return button!;
+ });
+ await act(() => showEveryone.click());
+ const labels = await vi.waitFor(() => {
+ const found = [...host.querySelectorAll('[role="list"] [aria-label]')].map((node) =>
+ node.getAttribute('aria-label')
+ );
+ expect(found).toHaveLength(2);
+ return found;
+ });
+ expect(new Set(labels).size).toBe(2);
+ expect(labels[0]).toContain('intermediates.owner.unknownAccountWithId(id=0a1b2c3d)');
+ });
+
it('replays a confirmed start receipt after a reload', async () => {
const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
recordPendingIntermediatesStart({ idempotencyKey: 'confirmed-key', previewId: 'confirmed-preview' });
@@ -501,6 +592,16 @@ describe('IntermediatesManager', () => {
expect(dialog.textContent).not.toContain('intermediates.dialog.forceWarningOwn');
});
+ it('counts the affected documents the server left out of the list', async () => {
+ dependencies.createIntermediatesPreview.mockImplementation(({ mode }: { mode: 'safe' | 'force' }) =>
+ Promise.resolve({ ...previewOf(mode, 4), affectedDocumentsTotal: mode === 'force' ? 204 : 0 })
+ );
+ const dialog = await openForceDialogReadyToConfirm();
+ const items = [...dialog.querySelectorAll('li')].map((item) => item.textContent ?? '');
+ expect(items).toHaveLength(forceAffectedDocuments.length + 1);
+ expect(items.at(-1)).toBe('intermediates.dialog.affectedMore(count=200)');
+ });
+
it('never replays a force delete the user cancelled after its start failed', async () => {
const dialog = await openForceDialogReadyToConfirm();
expect(dialog.textContent).toContain('intermediates.dialog.affectedQuarantinedProject(count=1,name=Old sketch)');
@@ -567,10 +668,12 @@ describe('IntermediatesManager', () => {
expect(host.querySelectorAll('[role="list"] li')).toHaveLength(3);
expect(host.textContent).toContain('intermediates.list.used');
expect(host.textContent).toContain('intermediates.list.unused');
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(true);
+ expect(isDeleteUnavailable()).toBe(true);
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ expect(dependencies.createIntermediatesPreview).not.toHaveBeenCalled();
await act(() => checkbox('intermediates.list.selectRow(name=Portraits)').click());
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(isDeleteUnavailable()).toBe(false);
expect(host.textContent).toContain('count=1');
await act(() => checkbox('intermediates.list.selectAll').click());
@@ -586,7 +689,7 @@ describe('IntermediatesManager', () => {
)
);
// A search hides rows; hidden selections must not survive it.
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(true);
+ expect(isDeleteUnavailable()).toBe(true);
});
it('refreshes measured sizes while an open summary is still being measured', async () => {
@@ -627,12 +730,12 @@ describe('IntermediatesManager', () => {
);
const dialog = document.querySelector('[role="alertdialog"]');
expect(dialog).not.toBeNull();
- await vi.waitFor(() => expect(dialog!.textContent).toContain('intermediates.dialog.reclaim(size=4.0 MB)'));
+ await vi.waitFor(() => expect(dialog!.textContent).toContain('intermediates.dialog.reclaim(size=4.2 MB)'));
expect(dialog!.textContent).toContain('intermediates.dialog.kept(count=3)');
// The impact is the dialog's accessible description even though it arrives after the dialog opens.
const describedBy = dialog!.getAttribute('aria-describedby');
expect(describedBy).not.toBeNull();
- expect(document.getElementById(describedBy!)?.textContent).toContain('intermediates.dialog.reclaim(size=4.0 MB)');
+ expect(document.getElementById(describedBy!)?.textContent).toContain('intermediates.dialog.reclaim(size=4.2 MB)');
const confirm = buttonWithText('intermediates.dialog.confirm', dialog!);
expect(confirm.disabled).toBe(false);
@@ -683,7 +786,7 @@ describe('IntermediatesManager', () => {
const typed = dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])');
expect(typed).not.toBeNull();
- await act(() => setInputValue(typed!, 'CLEAR'));
+ await act(() => setInputValue(typed!, 'DELETE'));
expect(confirm().disabled).toBe(false);
});
@@ -705,11 +808,11 @@ describe('IntermediatesManager', () => {
expect(checkbox('intermediates.list.selectRow(name=Landscapes)').checked).toBe(true);
expect(checkbox('intermediates.list.selectRow(name=Portraits)').checked).toBe(false);
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(isDeleteUnavailable()).toBe(false);
expect(host.textContent).toContain('count=1');
});
- it('keeps the current page visible but inert while the next loads, and never shows stale rows for a new search', async () => {
+ it('keeps the current rows visible but inert while the next page or a new search loads', async () => {
const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
let releaseNextPage!: () => void;
const nextPageGate = new Promise<void>((resolve) => {
@@ -757,10 +860,18 @@ describe('IntermediatesManager', () => {
await act(() =>
setInputValue(host.querySelector<HTMLInputElement>('input[aria-label="intermediates.searchLabel"]')!, 'one')
);
- await vi.waitFor(() => expect(host.textContent).not.toContain('Project 55'));
- expect(host.querySelector('[role="list"]')).toBeNull();
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesSummary).toHaveBeenLastCalledWith(
+ expect.objectContaining({ search: 'one' }),
+ expect.anything()
+ )
+ );
+ expect(host.textContent).toContain('Project 55');
+ expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBe('true');
await act(() => releaseSearch());
- await vi.waitFor(() => expect(host.textContent).toContain('Project 1'));
+ await vi.waitFor(() => expect(host.textContent).not.toContain('Project 55'));
+ expect(host.textContent).toContain('Project 1');
+ expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBeNull();
});
it('keeps picks from another page in the estimate and the targets', async () => {
@@ -903,7 +1014,7 @@ describe('IntermediatesManager', () => {
await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.refresh"]')!.click());
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.selection.estimate(count=1,'));
expect(checkbox('intermediates.list.selectRow(name=Project 55)').checked).toBe(true);
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(isDeleteUnavailable()).toBe(false);
currentRows = [row('p1', 'Project 1', 1), row('p55', 'Project 55', 1)];
await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.refresh"]')!.click());
@@ -951,11 +1062,240 @@ describe('IntermediatesManager', () => {
await act(() => checkbox('intermediates.list.selectRow(name=Project 1)').click());
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.selection.tooManyRows'));
expect(dependencies.getIntermediatesSummary.mock.calls.filter(([params]) => params.limit === 1000)).toHaveLength(1);
- expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(isDeleteUnavailable()).toBe(false);
await act(() => buttonWithText('intermediates.list.delete', host).click());
await vi.waitFor(() =>
expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('intermediates.dialog.tooManyRows')
);
expect(dependencies.createIntermediatesPreview).not.toHaveBeenCalled();
});
+
+ it('debounces search into one request while keeping the input responsive', async () => {
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ const search = page.getByRole('textbox', { name: 'intermediates.searchLabel' });
+ const input = search.element() as HTMLInputElement;
+ const before = dependencies.getIntermediatesSummary.mock.calls.length;
+
+ for (const value of ['P', 'Po', 'Por', 'Port']) {
+ await act(() => setInputValue(input, value));
+ }
+ expect(input.value).toBe('Port');
+ expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBe('true');
+ await vi.waitFor(() => expect(host.querySelectorAll('[role="list"] li')).toHaveLength(1));
+ const searches = dependencies.getIntermediatesSummary.mock.calls
+ .slice(before)
+ .map(([params]) => (params as { search?: string }).search);
+ expect(searches).toEqual(['Port']);
+ });
+
+ it('resolves Select all under a search against every matching row, not only the loaded page', async () => {
+ const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Match ${index}`, 1));
+ dependencies.getIntermediatesSummary
+ .mockReset()
+ .mockImplementation((params: { offset?: number; limit?: number; search?: string }) => {
+ const matching = params.search?.trim() ? manyRows : [...manyRows, row('other', 'Other', 1)];
+ const offset = params.offset ?? 0;
+ return Promise.resolve({
+ ...summaryOf(matching),
+ items: matching.slice(offset, offset + (params.limit ?? 50)),
+ offset,
+ });
+ });
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Match 0'));
+ await act(() =>
+ setInputValue(
+ page.getByRole('textbox', { name: 'intermediates.searchLabel' }).element() as HTMLInputElement,
+ 'Match'
+ )
+ );
+ await vi.waitFor(() => expect(host.textContent).not.toContain('Other'));
+ await vi.waitFor(() => expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBeNull());
+ await act(() => checkbox('intermediates.list.selectAll').click());
+ await act(() => checkbox('intermediates.list.selectRow(name=Match 3)').click());
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
+ {
+ mode: 'safe',
+ scope: {
+ kind: 'selection',
+ targets: manyRows
+ .filter(({ projectId }) => projectId !== 'p3')
+ .map(({ projectId, userId }) => ({ projectId, userId })),
+ },
+ },
+ expect.anything()
+ )
+ );
+ expect(dependencies.getIntermediatesSummary).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 1000, offset: 0, search: 'Match' }),
+ expect.anything()
+ );
+ });
+
+ it('keeps keyboard focus on the paging controls while pages load and at the last page', async () => {
+ const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
+ let releaseNextPage!: () => void;
+ const nextPageGate = new Promise<void>((resolve) => {
+ releaseNextPage = resolve;
+ });
+ dependencies.getIntermediatesSummary.mockReset().mockImplementation(async (params: { offset?: number }) => {
+ const offset = params.offset ?? 0;
+ if (offset > 0) {
+ await nextPageGate;
+ }
+ return { ...summaryOf(manyRows.slice(offset, offset + 50)), offset, total: manyRows.length };
+ });
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 0'));
+ const next = page.getByRole('button', { name: 'common.nextPage' }).element() as HTMLButtonElement;
+ next.focus();
+ await act(() => next.click());
+ await vi.waitFor(() => expect(next.getAttribute('aria-disabled')).toBe('true'));
+ // A second activation while the page loads is ignored instead of skipping a page.
+ await act(() => next.click());
+ expect(document.activeElement).toBe(next);
+
+ await act(() => releaseNextPage());
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 55'));
+ expect(host.textContent).toContain('common.pageNumber(page=2)');
+ expect(next.getAttribute('aria-disabled')).toBe('true');
+ expect(document.activeElement).toBe(next);
+ expect(
+ dependencies.getIntermediatesSummary.mock.calls.filter(
+ ([params]) => (params as { offset?: number }).offset === 100
+ )
+ ).toHaveLength(0);
+ });
+
+ it('keeps Refresh focusable while it reloads', async () => {
+ let releaseRefresh!: () => void;
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ dependencies.getIntermediatesSummary.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ releaseRefresh = () => resolve(summaryOf([row('p1', 'Portraits', 4)]));
+ })
+ );
+ const refresh = page.getByRole('button', { name: 'intermediates.refresh' }).element() as HTMLButtonElement;
+ refresh.focus();
+ await act(() => refresh.click());
+ await vi.waitFor(() => expect(refresh.getAttribute('aria-busy')).toBe('true'));
+ expect(refresh.disabled).toBe(false);
+ expect(document.activeElement).toBe(refresh);
+ await act(() => releaseRefresh());
+ await vi.waitFor(() => expect(refresh.getAttribute('aria-busy')).toBeNull());
+ });
+
+ it('opens the confirmation on Cancel rather than the force toggle', async () => {
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ const dialog = await vi.waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+ await vi.waitFor(() => expect(document.activeElement).toBe(buttonWithText('common.cancel', dialog)));
+ const description = document.getElementById(dialog.getAttribute('aria-describedby')!)!;
+ expect(description.getAttribute('aria-live')).toBe('polite');
+ await vi.waitFor(() => expect(description.textContent).toContain('intermediates.dialog.reclaim'));
+ expect(description.getAttribute('aria-busy')).toBeNull();
+ });
+
+ it('holds Delete, focusable with its reason, until the followed cleanup settles', async () => {
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation('op-1');
+ const publish = await followOperation(operationOf('running'));
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
+ const deleteButton = buttonWithText('intermediates.list.delete', host);
+ expect(isDeleteUnavailable()).toBe(true);
+ deleteButton.focus();
+ expect(document.activeElement).toBe(deleteButton);
+ const reason = document.getElementById(deleteButton.getAttribute('aria-describedby')!);
+ expect(reason?.textContent).toBe('intermediates.list.deleteWaiting');
+ await act(() => deleteButton.click());
+ expect(dependencies.createIntermediatesPreview).not.toHaveBeenCalled();
+
+ await publish(operationOf('completed'));
+ expect(host.textContent).toContain('intermediates.operation.status.completed');
+ expect(isDeleteUnavailable()).toBe(false);
+ expect(deleteButton.hasAttribute('aria-describedby')).toBe(false);
+ expect(host.textContent).not.toContain('intermediates.list.deleteWaiting');
+ });
+
+ it('announces status changes and coarse progress into one live region that mounts empty', async () => {
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation('op-1');
+ const running = (processed: number): IntermediatesOperation => ({
+ ...operationOf('running'),
+ progress: { ...operationOf('running').progress, deletedImages: processed, processedImages: processed },
+ targetImages: 100,
+ });
+ let resolveFirst!: (operation: IntermediatesOperation) => void;
+ const publish = await followOperation(running(10));
+ dependencies.getIntermediatesOperation.mockImplementationOnce(
+ () =>
+ new Promise<IntermediatesOperation>((resolve) => {
+ resolveFirst = resolve;
+ })
+ );
+ await renderManager();
+ const regions = () => [...host.querySelectorAll('[role="status"][aria-live="polite"]')];
+ expect(regions()).toHaveLength(1);
+ expect(regions()[0]!.textContent).toBe('');
+ expect(host.querySelector('[role="alert"], .chakra-alert__root[aria-live]')).toBeNull();
+
+ await act(() => resolveFirst(running(10)));
+ await vi.waitFor(() =>
+ expect(regions()[0]!.textContent).toBe(
+ 'intermediates.operation.progressAnnouncement(percent=0,status=intermediates.operation.status.running)'
+ )
+ );
+ await publish(running(20));
+ expect(host.textContent).toContain('intermediates.operation.progress(done=20,total=100)');
+ expect(regions()[0]!.textContent).toBe(
+ 'intermediates.operation.progressAnnouncement(percent=0,status=intermediates.operation.status.running)'
+ );
+ await publish(running(60));
+ expect(regions()[0]!.textContent).toBe(
+ 'intermediates.operation.progressAnnouncement(percent=0.5,status=intermediates.operation.status.running)'
+ );
+ await publish({ ...running(100), completedAt: 'later', status: 'completed' });
+ expect(regions()).toHaveLength(1);
+ expect(regions()[0]!.textContent).toBe('intermediates.operation.status.completed');
+ });
+
+ it('replays a lost start once under StrictMode and consumes the entry point intent on commit', async () => {
+ const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
+ const { peekIntermediatesFocus } = await import('@features/intermediates/data/focus');
+ recordPendingIntermediatesStart({ idempotencyKey: 'strict-key', previewId: 'strict-preview' });
+
+ await renderManager({ focusProjectId: 'p2', strict: true });
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledOnce();
+ expect(checkbox('intermediates.list.selectRow(name=Landscapes)').checked).toBe(true);
+ expect(peekIntermediatesFocus()).toBeNull();
+ });
+
+ it('keeps a timed-out start receipt after the dialog closes, so the next visit follows it', async () => {
+ dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
+ const dialog = await openForceDialogReadyToConfirm();
+ await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.startTimedOut'));
+ await act(() => buttonWithText('common.cancel', dialog).click());
+ expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-force');
+
+ await act(() => root.unmount());
+ host.remove();
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
+ const [first, replay] = dependencies.startIntermediatesOperation.mock.calls;
+ expect(replay![0]).toEqual(first![0]);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
index e8378bc6af..7e50e46908 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
@@ -4,7 +4,6 @@ import type { IntermediatesSummaryParams } from '@features/intermediates/data/ke
import type { TFunction } from 'i18next';
import {
- Badge,
Box,
Center,
Checkbox,
@@ -16,29 +15,33 @@ import {
Spinner,
Stack,
Text,
+ VisuallyHidden,
} from '@chakra-ui/react';
import { isRowSelected, resolveScope } from '@features/intermediates/core/selection';
-import { takeIntermediatesFocus } from '@features/intermediates/data/focus';
+import { isOperationSettled } from '@features/intermediates/core/types';
+import { consumeIntermediatesFocus, peekIntermediatesFocus } from '@features/intermediates/data/focus';
import { intermediatesKeys } from '@features/intermediates/data/keys';
import {
INTERMEDIATES_MAX_ROWS,
INTERMEDIATES_PAGE_SIZE,
intermediatesSummaryQueryOptions,
} from '@features/intermediates/data/queries';
+import { formatBytes } from '@platform/i18n/languages';
+import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
import { EmptyState } from '@platform/ui/EmptyState';
+import { RemovableTag } from '@platform/ui/RemovableTag';
import { Scrollable } from '@platform/ui/Scrollable';
import { Tooltip } from '@platform/ui/Tooltip';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { BrushCleaningIcon, RefreshCwIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';
-import { useCallback, useMemo, useRef, useState } from 'react';
+import { BrushCleaningIcon, RefreshCwIcon, SearchIcon, Trash2Icon } from 'lucide-react';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ClearDialog } from './ClearDialog';
-import { formatBytes } from './format';
import { getOwnerLabel, IntermediatesList } from './IntermediatesList';
-import { OperationPanel } from './OperationPanel';
+import { getOperationAnnouncement, OperationPanel } from './OperationPanel';
import { useCleanupDialog } from './useCleanupDialog';
import { useFollowedOperation } from './useFollowedOperation';
import { useIntermediatesSelection } from './useIntermediatesSelection';
@@ -46,18 +49,22 @@ import { useIntermediatesSelection } from './useIntermediatesSelection';
export interface IntermediatesManagerProps {
/** The current account, or null in single-user mode where the install is the only account. */
currentUserId: string | null;
+ /** The current account's display name or email, for the account filter before its rows load. */
+ currentUserLabel?: string | null;
canClearOthersIntermediates: boolean;
}
const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;
const EMPTY_ROWS: readonly IntermediatesRow[] = [];
+const SEARCH_DEBOUNCE_MS = 250;
-const isSameListExceptOffset = (previous: unknown, next: IntermediatesSummaryParams): boolean => {
+/** Paging and refining the search keep the current rows on screen, inert, until the new ones arrive. */
+const isSameListExceptPageOrSearch = (previous: unknown, next: IntermediatesSummaryParams): boolean => {
if (typeof previous !== 'object' || previous === null) {
return false;
}
- const { offset: _previousOffset, ...previousRest } = previous as IntermediatesSummaryParams;
- const { offset: _nextOffset, ...nextRest } = next;
+ const { offset: _previousOffset, search: _previousSearch, ...previousRest } = previous as IntermediatesSummaryParams;
+ const { offset: _nextOffset, search: _nextSearch, ...nextRest } = next;
const keys = new Set([...Object.keys(previousRest), ...Object.keys(nextRest)]) as Set<keyof typeof nextRest>;
return [...keys].every((key) => previousRest[key] === nextRest[key]);
};
@@ -68,19 +75,43 @@ const formatSummarySize = (bytes: number, unknownCount: number, t: TFunction): s
: formatBytes(bytes);
/** The Settings section: search, a select-all row with the delete action, and one row per project. */
-export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserId }: IntermediatesManagerProps) => {
+export const IntermediatesManager = ({
+ canClearOthersIntermediates,
+ currentUserId,
+ currentUserLabel = null,
+}: IntermediatesManagerProps) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
- // An entry point's intent is read once, when the section mounts; a later visit starts clean.
- const [focus] = useState(takeIntermediatesFocus);
+ // An entry point's intent is read when the section first renders and consumed once that render commits.
+ const [focus] = useState(peekIntermediatesFocus);
const [search, setSearch] = useState('');
+ const [querySearch, setQuerySearch] = useState('');
+ const searchTimerRef = useRef<number | undefined>(undefined);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const refreshRequestRef = useRef(0);
+ const deleteReasonId = useId();
+ useMountEffect(() => {
+ consumeIntermediatesFocus(focus);
+ return () => window.clearTimeout(searchTimerRef.current);
+ });
const [ownerFilter, setOwnerFilter] = useState<string | null>(() =>
focus?.ownerId && canClearOthersIntermediates ? focus.ownerId : currentUserId
);
const [projectFilter, setProjectFilter] = useState<string | null>(focus?.projectId ?? null);
const [offset, setOffset] = useState(0);
const searchRef = useRef<HTMLInputElement | null>(null);
+ const operationRegionRef = useRef<HTMLDivElement | null>(null);
const operation = useFollowedOperation({ fallbackFocusRef: searchRef });
+ // The live region stays mounted and starts empty; screen readers skip text that arrives with its region.
+ const announcement = getOperationAnnouncement(
+ operation.operationId ? (operation.query.data ?? null) : null,
+ operation.operationId !== null && operation.query.isPending,
+ t
+ );
+ const [announced, setAnnounced] = useState({ source: announcement, text: '' });
+ if (announced.source !== announcement) {
+ setAnnounced({ source: announcement, text: announcement });
+ }
// Non-admins are confined to their own rows by the server whatever is sent.
const ownerId: string | null = canClearOthersIntermediates ? ownerFilter : currentUserId;
@@ -91,21 +122,21 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
order: 'desc',
ownerId,
projectId: projectFilter,
- search,
+ search: querySearch,
sort: 'reclaimable_bytes',
}),
- [offset, ownerId, projectFilter, search]
+ [offset, ownerId, projectFilter, querySearch]
);
- // Paging keeps the current rows on screen until the next page arrives; any other change is a different list.
const query = useQuery({
...intermediatesSummaryQueryOptions(params),
placeholderData: (previous, previousQuery) =>
- previousQuery && isSameListExceptOffset(previousQuery.queryKey.at(-1), params) ? previous : undefined,
+ previousQuery && isSameListExceptPageOrSearch(previousQuery.queryKey.at(-1), params) ? previous : undefined,
});
- const isPaging = query.isPlaceholderData;
+ // Rows on screen belong to an older request while a page or search loads, or while typing has not settled.
+ const isListBusy = query.isPlaceholderData || search !== querySearch;
const rows = query.data?.items ?? EMPTY_ROWS;
const totals = query.data?.totals;
- const hasSearch = search.trim().length > 0;
+ const hasSearch = querySearch.trim().length > 0;
const hasSubsetFilter = hasSearch || projectFilter !== null;
// Rows disappearing (a cleanup, a narrower search) can leave the offset past the end; step back to a valid page.
if (query.data && !query.isPlaceholderData && offset > 0 && offset >= query.data.total) {
@@ -119,12 +150,13 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
rows,
summary: query.data,
});
- const dialog = useCleanupDialog({ onStarted: selection.reset, params, selection: selection.effectiveSelection });
+ const dialog = useCleanupDialog({ onStarted: selection.reset });
const { reset: resetSelection } = selection;
- const handleSearchChange = useCallback(
+ const commitSearch = useCallback(
(value: string) => {
- setSearch(value);
+ window.clearTimeout(searchTimerRef.current);
+ setQuerySearch(value);
setProjectFilter(null);
setOffset(0);
// A filter change hides rows; hidden selections would act on what the user can no longer see.
@@ -132,6 +164,18 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
},
[resetSelection]
);
+ const handleSearchChange = useCallback(
+ (value: string) => {
+ setSearch(value);
+ window.clearTimeout(searchTimerRef.current);
+ searchTimerRef.current = window.setTimeout(() => commitSearch(value), SEARCH_DEBOUNCE_MS);
+ },
+ [commitSearch]
+ );
+ const clearSearch = useCallback(() => {
+ setSearch('');
+ commitSearch('');
+ }, [commitSearch]);
const clearOwnerFilter = useCallback(() => {
setOwnerFilter(null);
setOffset(0);
@@ -147,21 +191,40 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
setOffset(0);
resetSelection();
}, [resetSelection]);
+ // Another press restarts the reload, so the control never locks on a request that does not settle.
const handleRefresh = useCallback(() => {
- void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all });
+ const request = ++refreshRequestRef.current;
+ setIsRefreshing(true);
+ void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all }).finally(() => {
+ if (refreshRequestRef.current === request) {
+ setIsRefreshing(false);
+ }
+ });
}, [queryClient]);
- const selectedScope = resolveScope({
- hasSubsetFilter,
- loadedRows: rows,
- ownerId,
- selection: selection.effectiveSelection,
- });
const { selectionSummary } = selection;
- const filteredOwnerRow = ownerFilter ? rows[0] : undefined;
+ const filteredOwnerLabel = !ownerFilter
+ ? null
+ : rows[0]?.userId === ownerFilter
+ ? getOwnerLabel(rows[0], t)
+ : ownerFilter === focus?.ownerId && focus.ownerLabel
+ ? focus.ownerLabel
+ : ownerFilter === currentUserId && currentUserLabel
+ ? currentUserLabel
+ : t('intermediates.owner.unknownAccount');
const hasPreviousPage = offset > 0;
const hasNextPage = query.data !== undefined && offset + rows.length < query.data.total;
const showPagination = offset > 0 || (query.data?.total ?? 0) > INTERMEDIATES_PAGE_SIZE;
+ const followed = operation.query.data;
+ // A second cleanup would replace the panel reporting the first; wait until it settles (or cannot be looked up).
+ const isOperationActive =
+ operation.operationId !== null && !operation.query.isError && !(followed && isOperationSettled(followed));
+ const isDeleteUnavailable = !selection.hasSelection || isOperationActive;
+ const goToPage = (nextOffset: number) => {
+ if (!isListBusy && nextOffset >= 0 && (nextOffset < offset || hasNextPage)) {
+ setOffset(nextOffset);
+ }
+ };
return (
<Stack gap="3" h="full" minH="0">
@@ -176,14 +239,14 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Stack>
<Tooltip content={t('intermediates.refresh')}>
<IconButton
+ aria-busy={isRefreshing || undefined}
aria-label={t('intermediates.refresh')}
- disabled={query.isFetching}
flexShrink={0}
size="xs"
variant="outline"
onClick={handleRefresh}
>
- <RefreshCwIcon />
+ {isRefreshing ? <Spinner size="xs" /> : <RefreshCwIcon />}
</IconButton>
</Tooltip>
</HStack>
@@ -207,23 +270,10 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
onChange={(event) => handleSearchChange(event.currentTarget.value)}
/>
</InputGroup>
- {canClearOthersIntermediates && ownerFilter ? (
- <Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
- {t('intermediates.owner.filtered', {
- name: filteredOwnerRow ? getOwnerLabel(filteredOwnerRow) : ownerFilter,
- })}
- <Tooltip content={t('intermediates.owner.showEveryone')}>
- <IconButton
- aria-label={t('intermediates.owner.showEveryone')}
- minW="4"
- size="2xs"
- variant="ghost"
- onClick={clearOwnerFilter}
- >
- <Icon as={XIcon} boxSize="3" />
- </IconButton>
- </Tooltip>
- </Badge>
+ {canClearOthersIntermediates && filteredOwnerLabel ? (
+ <RemovableTag removeLabel={t('intermediates.owner.showEveryone')} onRemove={clearOwnerFilter}>
+ {t('intermediates.owner.filtered', { name: filteredOwnerLabel })}
+ </RemovableTag>
) : null}
{canClearOthersIntermediates && !ownerFilter && currentUserId ? (
<Button size="2xs" variant="outline" onClick={showOwnAccount}>
@@ -231,38 +281,40 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Button>
) : null}
{projectFilter ? (
- <Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
- {selection.focusedRow?.projectName ?? t('intermediates.owner.projectFilter')}
- <Tooltip content={t('intermediates.owner.showAllProjects')}>
- <IconButton
- aria-label={t('intermediates.owner.showAllProjects')}
- minW="4"
- size="2xs"
- variant="ghost"
- onClick={clearProjectFilter}
- >
- <Icon as={XIcon} boxSize="3" />
- </IconButton>
- </Tooltip>
- </Badge>
+ <RemovableTag removeLabel={t('intermediates.owner.showAllProjects')} onRemove={clearProjectFilter}>
+ {rows.find((row) => row.projectId === projectFilter)?.projectName ?? t('intermediates.owner.projectFilter')}
+ </RemovableTag>
) : null}
</HStack>
+ <VisuallyHidden aria-atomic="true" aria-live="polite" role="status">
+ {announced.text}
+ </VisuallyHidden>
{operation.operationId ? (
- <OperationPanel
- isLoading={operation.query.isPending}
- isRefetching={operation.query.isFetching}
- lookupError={
- operation.query.isError
- ? getApiErrorMessage(operation.query.error, t('intermediates.operation.lookupFailed'))
- : null
- }
- onRefetch={() => void operation.query.refetch()}
- isRetrying={operation.isRetrying}
- operation={operation.query.data ?? null}
- retryError={operation.retryError}
- onDismiss={operation.dismiss}
- onRetry={() => void operation.retry()}
- />
+ // Takes focus after a start, since the Delete control that opened the dialog has nothing left to act on.
+ <Box
+ ref={operationRegionRef}
+ aria-label={t('intermediates.operation.regionLabel')}
+ focusVisibleRing="outside"
+ role="group"
+ rounded="l2"
+ tabIndex={-1}
+ >
+ <OperationPanel
+ isLoading={operation.query.isPending}
+ isRefetching={operation.query.isFetching}
+ lookupError={
+ operation.query.isError
+ ? getApiErrorMessage(operation.query.error, t('intermediates.operation.lookupFailed'))
+ : null
+ }
+ onRefetch={() => void operation.query.refetch()}
+ isRetrying={operation.isRetrying}
+ operation={operation.query.data ?? null}
+ retryError={operation.retryError}
+ onDismiss={operation.dismiss}
+ onRetry={() => void operation.retry()}
+ />
+ </Box>
) : null}
<Stack flex="1" gap="0" minH="0" mt="-3">
{/* Keep the bar mounted so a selection never shifts the rows beneath it. */}
@@ -273,7 +325,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
selection.selectionState === 'all' ? true : selection.selectionState === 'some' ? 'indeterminate' : false
}
colorPalette="accent"
- disabled={rows.length === 0 || isPaging}
+ disabled={rows.length === 0 || isListBusy}
size="xs"
onCheckedChange={selection.toggleAll}
pl="2"
@@ -284,23 +336,25 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
{t('intermediates.list.selectAll')}
</Checkbox.Label>
</Checkbox.Root>
- <Text color="fg.muted" flex="1" fontSize="2xs" minW="0" textAlign="end" truncate>
- {selection.estimateState && selectionSummary === null
- ? t(`intermediates.selection.${selection.estimateState}`, { count: INTERMEDIATES_MAX_ROWS })
- : selection.hasSelection && selectionSummary
- ? t('intermediates.selection.estimate', {
- count: selectionSummary.rows,
- images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),
- size: formatSummarySize(selectionSummary.reclaimableBytes, selectionSummary.unknownSizeCount, t),
- videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),
- })
- : totals
- ? t('intermediates.selection.available', {
- images: t('intermediates.counts.images', { count: totals.safeImages }),
- size: formatSummarySize(totals.reclaimableBytes, totals.unknownSizeCount, t),
- videos: t('intermediates.counts.videos', { count: totals.safeVideos }),
+ <Text color="fg.muted" flex="1" fontSize="2xs" id={deleteReasonId} minW="0" textAlign="end" truncate>
+ {isOperationActive && selection.hasSelection
+ ? t('intermediates.list.deleteWaiting')
+ : selection.estimateState && selectionSummary === null
+ ? t(`intermediates.selection.${selection.estimateState}`, { count: INTERMEDIATES_MAX_ROWS })
+ : selection.hasSelection && selectionSummary
+ ? t('intermediates.selection.estimate', {
+ count: selectionSummary.rows,
+ images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),
+ size: formatSummarySize(selectionSummary.reclaimableBytes, selectionSummary.unknownSizeCount, t),
+ videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),
})
- : ''}
+ : totals
+ ? t('intermediates.selection.available', {
+ images: t('intermediates.counts.images', { count: totals.safeImages }),
+ size: formatSummarySize(totals.reclaimableBytes, totals.unknownSizeCount, t),
+ videos: t('intermediates.counts.videos', { count: totals.safeVideos }),
+ })
+ : ''}
</Text>
{query.data?.measuring ? (
<Tooltip content={t('intermediates.stats.measuringNote')}>
@@ -308,14 +362,23 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Tooltip>
) : null}
<Separator borderColor="border.subtle" h="4" orientation="vertical" />
+ {/* `aria-disabled` keeps it focusable, so the reason it waits is announced on focus. */}
<Button
+ aria-describedby={isOperationActive && selection.hasSelection ? deleteReasonId : undefined}
+ aria-disabled={isDeleteUnavailable}
colorPalette="red"
- disabled={!selection.hasSelection}
size="2xs"
variant="ghost"
onClick={(event) => {
+ if (isDeleteUnavailable) {
+ return;
+ }
operation.clearRetryError();
- dialog.open(selectedScope, event.currentTarget);
+ dialog.open(
+ resolveScope({ hasSubsetFilter, ownerId, selection: selection.effectiveSelection }),
+ params,
+ event.currentTarget
+ );
}}
>
<Icon as={Trash2Icon} boxSize="3" />
@@ -348,7 +411,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
title={hasSearch ? t('intermediates.empty.noMatches') : t('intermediates.empty.title')}
>
{hasSearch ? (
- <Button size="xs" variant="outline" onClick={() => handleSearchChange('')}>
+ <Button size="xs" variant="outline" onClick={clearSearch}>
{t('common.clearSearch')}
</Button>
) : null}
@@ -358,7 +421,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
<Scrollable flex="1" h="full" label={t('intermediates.title')} minH="0">
<Box py="1">
<IntermediatesList
- isBusy={isPaging}
+ isBusy={isListBusy}
isSelected={(row) => isRowSelected(selection.effectiveSelection, row)}
rows={rows}
showOwner={canClearOthersIntermediates && ownerId === null}
@@ -369,12 +432,12 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
)}
{showPagination ? (
<HStack borderColor="border.subtle" borderTopWidth="1px" flexShrink={0} justify="center" minH="8">
+ {/* `aria-disabled`, not `disabled`: a disabled button drops the keyboard focus it holds. */}
<Button
- aria-label={t('common.previousPage')}
- disabled={!hasPreviousPage || query.isFetching}
+ aria-disabled={!hasPreviousPage || isListBusy}
size="2xs"
variant="ghost"
- onClick={() => setOffset((current) => Math.max(0, current - INTERMEDIATES_PAGE_SIZE))}
+ onClick={() => goToPage(offset - INTERMEDIATES_PAGE_SIZE)}
>
{t('common.previousPage')}
</Button>
@@ -384,11 +447,10 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
})}
</Text>
<Button
- aria-label={t('common.nextPage')}
- disabled={!hasNextPage || query.isFetching}
+ aria-disabled={!hasNextPage || isListBusy}
size="2xs"
variant="ghost"
- onClick={() => setOffset((current) => current + INTERMEDIATES_PAGE_SIZE)}
+ onClick={() => goToPage(offset + INTERMEDIATES_PAGE_SIZE)}
>
{t('common.nextPage')}
</Button>
@@ -398,8 +460,9 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
<ClearDialog
canManageEveryone={canClearOthersIntermediates}
currentUserId={currentUserId}
- fallbackFocusRef={searchRef}
- finalFocusRef={dialog.triggerRef}
+ getFinalFocus={() =>
+ (dialog.hasStarted() ? operationRegionRef.current : dialog.triggerRef.current) ?? searchRef.current
+ }
state={dialog.state}
onClose={dialog.close}
onConfirm={() => void dialog.confirm()}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx
index 3290ba8ada..6c4b25687a 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx
@@ -9,11 +9,15 @@ import { IntermediatesManager } from './IntermediatesManager';
export const IntermediatesSettingsField = (_props: SettingFieldProps) => {
const session = useAuthSession();
const { canClearOthersIntermediates } = useCapabilities();
- const currentUserId = session.phase === 'ready' ? (session.user?.user_id ?? null) : null;
+ const user = session.phase === 'ready' ? session.user : null;
return (
<Box display="flex" flex="1" flexDirection="column" minH="0">
- <IntermediatesManager canClearOthersIntermediates={canClearOthersIntermediates} currentUserId={currentUserId} />
+ <IntermediatesManager
+ canClearOthersIntermediates={canClearOthersIntermediates}
+ currentUserId={user?.user_id ?? null}
+ currentUserLabel={user ? user.display_name || user.email : null}
+ />
</Box>
);
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
index b6f048a4dd..d5476f34fe 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
@@ -1,4 +1,5 @@
import type { IntermediatesOperation } from '@features/intermediates/core/types';
+import type { TFunction } from 'i18next';
import { Alert, HStack, Progress, Stack, Text } from '@chakra-ui/react';
import {
@@ -7,11 +8,10 @@ import {
isOperationRetryable,
isOperationSettled,
} from '@features/intermediates/core/types';
+import { formatBytes, formatCount } from '@platform/i18n/languages';
import { Button } from '@platform/ui/Button';
import { useTranslation } from 'react-i18next';
-import { formatBytes, formatCount } from './format';
-
export interface OperationPanelProps {
operation: IntermediatesOperation | null;
isLoading: boolean;
@@ -35,6 +35,34 @@ const Stat = ({ label, value }: { label: string; value: string }) => (
</Stack>
);
+const ANNOUNCED_PROGRESS_STEP = 25;
+
+/**
+ * The sentence screen readers hear. It changes with the status and at most every quarter of the progress, so a 2s poll
+ * or a socket update that only moves the counters stays silent; the progress bar exposes the exact value on demand.
+ */
+export const getOperationAnnouncement = (
+ operation: IntermediatesOperation | null,
+ isLoading: boolean,
+ t: TFunction
+): string => {
+ if (!operation) {
+ return isLoading ? t('intermediates.operation.pending') : '';
+ }
+ const statusLabel = t(`intermediates.operation.status.${operation.status}`);
+ if (isOperationSettled(operation) || operation.status === 'pending') {
+ return statusLabel;
+ }
+ const steps = Math.floor(
+ (getOperationProcessed(operation) / Math.max(getOperationTotalTargets(operation), 1)) *
+ (100 / ANNOUNCED_PROGRESS_STEP)
+ );
+ return t('intermediates.operation.progressAnnouncement', {
+ percent: (steps * ANNOUNCED_PROGRESS_STEP) / 100,
+ status: statusLabel,
+ });
+};
+
/** The active or most recent cleanup: progress while it runs, a breakdown once it stops, retry for what failed. */
export const OperationPanel = ({
isLoading,
@@ -86,8 +114,6 @@ export const OperationPanel = ({
return (
<Alert.Root
- aria-live="polite"
- role="status"
size="sm"
status={operation.status === 'failed' ? 'error' : operation.status === 'completed' ? 'success' : 'info'}
variant="surface"
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts
deleted file mode 100644
index c7e2323526..0000000000
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
-
-/** Binary units, one decimal from KB up, so a summary card and a confirmation quote the same figure. */
-export const formatBytes = (bytes: number): string => {
- if (!Number.isFinite(bytes) || bytes < 1) {
- return '0 B';
- }
-
- let value = bytes;
- let unit = 0;
-
- while (value >= 1024 && unit < UNITS.length - 1) {
- value /= 1024;
- unit += 1;
- }
-
- return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${UNITS[unit]}`;
-};
-
-export const formatCount = (count: number): string => new Intl.NumberFormat().format(count);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
index 63c671d247..81a3db61e5 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
@@ -1,24 +1,25 @@
-import type { IntermediatesSelection } from '@features/intermediates/core/selection';
+import type { IntermediatesScopeRequest } from '@features/intermediates/core/selection';
import type { IntermediatesCleanupMode, IntermediatesScope } from '@features/intermediates/core/types';
import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
-import { isRowSelected } from '@features/intermediates/core/selection';
+import { resolveMatchingTargets } from '@features/intermediates/core/selection';
import {
createIntermediatesPreview,
getIntermediatesSummary,
startIntermediatesOperation,
} from '@features/intermediates/data/api';
-import { intermediatesKeys } from '@features/intermediates/data/keys';
import {
+ adoptIntermediatesOperation,
clearPendingIntermediatesStart,
- followIntermediatesOperation,
recordPendingIntermediatesStart,
} from '@features/intermediates/data/operationStore';
import { INTERMEDIATES_MAX_ROWS } from '@features/intermediates/data/queries';
+import { createUuid } from '@platform/browser/randomUuid';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
+ type AccountScope,
} from '@platform/state/accountLifecycle';
import { ApiError, getApiErrorMessage } from '@platform/transport/http';
import { useQueryClient } from '@tanstack/react-query';
@@ -27,32 +28,46 @@ import { useTranslation } from 'react-i18next';
import type { ClearDialogState } from './ClearDialog';
-let nextIdempotencyKey = 1;
-const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;
+interface DialogRequest {
+ scope: IntermediatesScopeRequest;
+ /** The filters the request was made under; a `matching` scope resolves against them. */
+ params: IntermediatesSummaryParams;
+}
/** The confirmation flow: preview a scope, optionally switch to force, and start the operation it froze. */
-export const useCleanupDialog = ({
- onStarted,
- params,
- selection,
-}: {
- onStarted: () => void;
- params: IntermediatesSummaryParams;
- selection: IntermediatesSelection;
-}) => {
+export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
const [dialog, setDialog] = useState<ClearDialogState | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ const startedRef = useRef(false);
const requestRef = useRef(0);
- const scopeRef = useRef<IntermediatesScope | null>(null);
+ const dialogRequestRef = useRef<DialogRequest | null>(null);
+
+ const resolveScope = useCallback(
+ async ({ params, scope }: DialogRequest, owner: AccountScope): Promise<IntermediatesScope> => {
+ if (scope.kind !== 'matching') {
+ return scope;
+ }
+ const matching = await getIntermediatesSummary(
+ { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
+ if (matching.total > matching.items.length) {
+ throw new Error(t('intermediates.dialog.tooManyRows', { count: matching.items.length }));
+ }
+ return { kind: 'selection', targets: resolveMatchingTargets(scope.excluded, matching.items) };
+ },
+ [t]
+ );
const loadPreview = useCallback(
- async (mode: IntermediatesCleanupMode, scope: IntermediatesScope) => {
+ async (mode: IntermediatesCleanupMode, request: DialogRequest) => {
const requestId = ++requestRef.current;
const owner = captureAccountScope();
setDialog((current) => ({
- idempotencyKey: current?.idempotencyKey ?? createIdempotencyKey(),
+ idempotencyKey: current?.idempotencyKey ?? createUuid(),
isStarting: false,
mode,
preview: null,
@@ -60,30 +75,13 @@ export const useCleanupDialog = ({
startError: null,
}));
try {
- let resolvedScope = scope;
- // Filters and exclusions cannot be expressed by the cleanup scope; resolve them to explicit rows.
- if (selection.mode === 'all-matching' && scope.kind === 'selection') {
- const everything = await getIntermediatesSummary(
- { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
- owner.signal
- );
- assertAccountScopeCurrent(owner);
- if (everything.total > everything.items.length) {
- throw new Error(t('intermediates.dialog.tooManyRows', { count: everything.items.length }));
- }
- resolvedScope = {
- kind: 'selection',
- targets: everything.items
- .filter((row) => isRowSelected(selection, row))
- .map(({ projectId, userId }) => ({ projectId, userId })),
- };
- }
- const preview = await createIntermediatesPreview({ mode, scope: resolvedScope }, owner.signal);
+ const scope = await resolveScope(request, owner);
+ const preview = await createIntermediatesPreview({ mode, scope }, owner.signal);
assertAccountScopeCurrent(owner);
if (requestRef.current === requestId) {
// One key per preview: every Confirm of this preview replays the same operation, and a later preview
// (mode switch, retry) starts clean instead of colliding with a key the server already settled.
- setDialog((current) => (current ? { ...current, idempotencyKey: createIdempotencyKey(), preview } : current));
+ setDialog((current) => (current ? { ...current, idempotencyKey: createUuid(), preview } : current));
}
} catch (error) {
if (requestRef.current === requestId && isAccountScopeCurrent(owner)) {
@@ -95,33 +93,33 @@ export const useCleanupDialog = ({
}
}
},
- [params, selection, t]
+ [resolveScope, t]
);
const open = useCallback(
- (scope: IntermediatesScope, trigger: HTMLElement | null) => {
+ (scope: IntermediatesScopeRequest, params: IntermediatesSummaryParams, trigger: HTMLElement | null) => {
triggerRef.current = trigger;
- scopeRef.current = scope;
+ startedRef.current = false;
+ dialogRequestRef.current = { params, scope };
setDialog(null);
- void loadPreview('safe', scope);
+ void loadPreview('safe', dialogRequestRef.current);
},
[loadPreview]
);
+ // A timed-out start keeps its receipt: the server may have accepted it, and the next visit replays the same key.
const close = useCallback(() => {
requestRef.current += 1;
- // Walking away from a failed start must not let a later visit replay it.
- clearPendingIntermediatesStart();
setDialog(null);
}, []);
const retryPreview = useCallback(() => {
- if (dialog && scopeRef.current) {
- void loadPreview(dialog.mode, scopeRef.current);
+ if (dialog && dialogRequestRef.current) {
+ void loadPreview(dialog.mode, dialogRequestRef.current);
}
}, [dialog, loadPreview]);
const changeMode = useCallback(
(mode: IntermediatesCleanupMode) => {
- if (scopeRef.current) {
- void loadPreview(mode, scopeRef.current);
+ if (dialogRequestRef.current) {
+ void loadPreview(mode, dialogRequestRef.current);
}
},
[loadPreview]
@@ -138,13 +136,16 @@ export const useCleanupDialog = ({
try {
const operation = await startIntermediatesOperation(start, owner.signal);
assertAccountScopeCurrent(owner);
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
+ adoptIntermediatesOperation(queryClient, owner, operation);
+ startedRef.current = true;
onStarted();
setDialog(null);
} catch (error) {
- // Whatever settled it, this start is over; nothing may replay it, including after signing back in.
- clearPendingIntermediatesStart(owner);
+ const timedOut = error instanceof DOMException && error.name === 'TimeoutError';
+ // Any other outcome settles this start; nothing may replay it, including after signing back in.
+ if (!timedOut) {
+ clearPendingIntermediatesStart(owner);
+ }
if (!isAccountScopeCurrent(owner) || (error instanceof DOMException && error.name === 'AbortError')) {
setDialog((current) => (current ? { ...current, isStarting: false } : current));
return;
@@ -152,7 +153,6 @@ export const useCleanupDialog = ({
// A 404 means the preview expired or was consumed by a request whose response was lost; only a new
// preview can move forward, so offer that instead of a dead Confirm.
const previewGone = error instanceof ApiError && error.status === 404;
- const timedOut = error instanceof DOMException && error.name === 'TimeoutError';
setDialog((current) =>
current
? {
@@ -163,7 +163,11 @@ export const useCleanupDialog = ({
startError: previewGone
? null
: timedOut
- ? t('intermediates.dialog.startTimedOut')
+ ? t('intermediates.dialog.startTimedOut', {
+ action: t(
+ current.mode === 'force' ? 'intermediates.dialog.forceConfirm' : 'intermediates.dialog.confirm'
+ ),
+ })
: getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
}
: current
@@ -171,5 +175,7 @@ export const useCleanupDialog = ({
}
}, [dialog, onStarted, queryClient, t]);
- return { changeMode, close, confirm, open, retryPreview, state: dialog, triggerRef };
+ const hasStarted = useCallback(() => startedRef.current, []);
+
+ return { changeMode, close, confirm, hasStarted, open, retryPreview, state: dialog, triggerRef };
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
index 2f1d180caa..bb6a001575 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
@@ -1,22 +1,14 @@
-import type { IntermediatesOperation } from '@features/intermediates/core/types';
-import type { AccountScope } from '@platform/state/accountLifecycle';
import type { RefObject } from 'react';
-import {
- getIntermediatesOperation,
- retryIntermediatesOperation,
- startIntermediatesOperation,
-} from '@features/intermediates/data/api';
-import { intermediatesKeys } from '@features/intermediates/data/keys';
+import { retryIntermediatesOperation } from '@features/intermediates/data/api';
import {
activeOperationStore,
- clearPendingIntermediatesStart,
+ adoptIntermediatesOperation,
+ attachIntermediatesManager,
+ findLatestIntermediatesRetry,
followIntermediatesOperation,
- isPendingIntermediatesStartCurrent,
- restoreIntermediatesReceipt,
} from '@features/intermediates/data/operationStore';
import { intermediatesOperationQueryOptions } from '@features/intermediates/data/queries';
-import { attachIntermediatesRealtime } from '@features/intermediates/data/realtime';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
assertAccountScopeCurrent,
@@ -28,78 +20,17 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-const getLatestRetry = async (operationId: string, signal: AbortSignal): Promise<IntermediatesOperation> => {
- let operation = await getIntermediatesOperation(operationId, signal);
- const visited = new Set<string>([operationId]);
- while (operation.retriedByOperationId && !visited.has(operation.retriedByOperationId)) {
- visited.add(operation.retriedByOperationId);
- operation = await getIntermediatesOperation(operation.retriedByOperationId, signal);
- }
- return operation;
-};
-
-/**
- * The operation the section follows, kept across visits. On mount it attaches realtime updates, replays a Confirm
- * whose response was lost, and otherwise catches up with a retry started elsewhere.
- */
+/** The operation the section follows, kept across visits by the operation store, which this hook subscribes to. */
export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: RefObject<HTMLElement | null> }) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
const operationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
+ const recoveryError = activeOperationStore.useSelector((snapshot) => snapshot.recoveryError);
const [retryError, setRetryError] = useState<string | null>(null);
- const [recoveryError, setRecoveryError] = useState<string | null>(null);
const [isRetrying, setIsRetrying] = useState(false);
const query = useQuery({ ...intermediatesOperationQueryOptions(operationId ?? ''), enabled: operationId !== null });
- const follow = useCallback(
- (owner: AccountScope, operation: IntermediatesOperation) => {
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
- },
- [queryClient]
- );
-
- useMountEffect(() => {
- let mounted = true;
- const detach = attachIntermediatesRealtime(queryClient);
- const owner = captureAccountScope();
- const pending = restoreIntermediatesReceipt();
- if (pending) {
- void startIntermediatesOperation(pending, owner.signal)
- .then((operation) => {
- if (isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
- follow(owner, operation);
- }
- })
- .catch((error: unknown) => {
- if (isPendingIntermediatesStartCurrent(pending, owner)) {
- clearPendingIntermediatesStart(owner);
- if (mounted && isAccountScopeCurrent(owner)) {
- setRecoveryError(getApiErrorMessage(error, t('intermediates.dialog.startFailed')));
- }
- }
- });
- } else {
- const followed = activeOperationStore.getSnapshot().operationId;
- if (followed) {
- void getLatestRetry(followed, owner.signal)
- .then((operation) => {
- if (
- isAccountScopeCurrent(owner) &&
- activeOperationStore.getSnapshot().operationId === followed &&
- operation.operationId !== followed
- ) {
- follow(owner, operation);
- }
- })
- .catch(() => undefined); // The operation query reports lookup failures in the panel.
- }
- }
- return () => {
- mounted = false;
- detach();
- };
- });
+ useMountEffect(() => attachIntermediatesManager(queryClient));
const retry = useCallback(async () => {
if (!operationId) {
@@ -111,17 +42,17 @@ export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: R
try {
const operation = await retryIntermediatesOperation(operationId, owner.signal);
assertAccountScopeCurrent(owner);
- follow(owner, operation);
+ adoptIntermediatesOperation(queryClient, owner, operation);
} catch (error) {
if (isAccountScopeCurrent(owner)) {
try {
- const latest = await getLatestRetry(operationId, owner.signal);
+ const latest = await findLatestIntermediatesRetry(operationId, owner.signal);
if (
latest.operationId !== operationId &&
isAccountScopeCurrent(owner) &&
activeOperationStore.getSnapshot().operationId === operationId
) {
- follow(owner, latest);
+ adoptIntermediatesOperation(queryClient, owner, latest);
return;
}
} catch {
@@ -134,7 +65,7 @@ export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: R
setIsRetrying(false);
}
}
- }, [follow, operationId, t]);
+ }, [operationId, queryClient, t]);
const dismiss = useCallback(() => {
followIntermediatesOperation(null);
setRetryError(null);
@@ -143,5 +74,14 @@ export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: R
}, [fallbackFocusRef]);
const clearRetryError = useCallback(() => setRetryError(null), []);
- return { clearRetryError, dismiss, isRetrying, operationId, query, recoveryError, retry, retryError };
+ return {
+ clearRetryError,
+ dismiss,
+ isRetrying,
+ operationId,
+ query,
+ recoveryError: recoveryError ? getApiErrorMessage(recoveryError, t('intermediates.dialog.startFailed')) : null,
+ retry,
+ retryError,
+ };
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
index 2f7e5ff7df..cb11149c6d 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
@@ -31,7 +31,7 @@ export const useIntermediatesSelection = ({
summary: IntermediatesSummary | undefined;
}) => {
const [selection, setSelection] = useState<IntermediatesSelection>(EMPTY_SELECTION);
- // The focused project is queried directly, so pagination cannot hide the entry point's selection.
+ // The manager filters to the focused project, so pagination cannot hide the entry point's selection.
const [pendingProjectId, setPendingProjectId] = useState<string | null>(initialProjectId);
const totals = summary?.totals;
const focusedRow = pendingProjectId ? rows.find((row) => row.projectId === pendingProjectId) : undefined;
@@ -86,7 +86,6 @@ export const useIntermediatesSelection = ({
: matchingSnapshotQuery.isError
? ('estimateFailed' as const)
: ('checking' as const),
- focusedRow,
hasSelection,
reset,
selectionState: hasSelection ? (isComplete ? ('all' as const) : ('some' as const)) : ('none' as const),
diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts
index c44e556442..931a0d8de0 100644
--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts
@@ -3,30 +3,12 @@ import { describe, expect, it } from 'vitest';
import {
EDITABLE_MODEL_FORMATS,
getModelSourceHref,
- formatBytes,
getModelFormatLabel,
getModelTypeLabel,
getModelVariantLabel,
getVariantOptionsFor,
} from './taxonomy';
-describe('formatBytes', () => {
- it('renders a dash for missing or invalid sizes', () => {
- expect(formatBytes(null)).toBe('—');
- expect(formatBytes(undefined)).toBe('—');
- expect(formatBytes(-1)).toBe('—');
- expect(formatBytes(Number.NaN)).toBe('—');
- });
-
- it('scales across unit boundaries', () => {
- expect(formatBytes(0)).toBe('0 B');
- expect(formatBytes(1023)).toBe('1023 B');
- expect(formatBytes(1024)).toBe('1.0 KB');
- expect(formatBytes(1024 * 1024)).toBe('1.0 MB');
- expect(formatBytes(1.5 * 1024 * 1024 * 1024)).toBe('1.5 GB');
- });
-});
-
describe('label fallbacks', () => {
it('title-cases unknown open-union values', () => {
expect(getModelTypeLabel('some_new_type')).toBe('Some New Type');
diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts
index a183ed6092..d2975e2b71 100644
--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts
@@ -192,21 +192,3 @@ export const getVariantOptionsFor = (base: string, type: string): readonly strin
return VARIANTS_BY_TYPE[type] ?? [];
};
-
-const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
-
-export const formatBytes = (bytes: number | null | undefined): string => {
- if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) {
- return '—';
- }
-
- let value = bytes;
- let unitIndex = 0;
-
- while (value >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
- value /= 1024;
- unitIndex += 1;
- }
-
- return `${unitIndex === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[unitIndex]}`;
-};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
index fd85d942fa..7c47f68e6c 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx
@@ -5,11 +5,12 @@ import type { PickerGroup, PickerOptionState } from '@platform/ui/Picker';
import { Badge, Box, HStack, Icon, Image, Popover, Portal, Spacer, Stack, Text } from '@chakra-ui/react';
import { getModelBaseColorPalette, getModelBaseLabel, getModelBaseLongLabel } from '@features/models/core/baseIdentity';
import { getModelPickerGroups, hasModelPickerCandidates } from '@features/models/core/library';
-import { formatBytes, getModelTypeLabel, getModelTypePluralLabel } from '@features/models/core/taxonomy';
+import { getModelTypeLabel, getModelTypePluralLabel } from '@features/models/core/taxonomy';
import { getModelImageUrl } from '@features/models/data/api';
import { ensureModelsLoaded, useModelsSelector } from '@features/models/data/modelsStore';
import { useModelsUi } from '@features/models/ui/ModelsUiContext';
import { setPickerBaseFilters, setPickerCompactView, useModelsUiSelector } from '@features/models/ui/uiStore';
+import { formatBytes } from '@platform/i18n/languages';
import { useMountEffect } from '@platform/react/useMountEffect';
import { areArraysEqual } from '@platform/state/selectors';
import { Button, CloseButton, IconButton, PopoverContent, Tooltip } from '@platform/ui';
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
index 5b24c2c767..2ec8173e36 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
@@ -6,7 +6,7 @@ import { chakra, DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text }
import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';
import { isLinkableType } from '@features/models/core/relationships';
import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';
-import { formatBytes, getModelSourceHref } from '@features/models/core/taxonomy';
+import { getModelSourceHref } from '@features/models/core/taxonomy';
import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';
import {
ModelActionConfirmDialog,
@@ -14,6 +14,7 @@ import {
type PendingModelAction,
} from '@features/models/ui/shared/ModelActionsMenu';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { formatBytes } from '@platform/i18n/languages';
import { areArraysEqual } from '@platform/state/selectors';
import { Button, IconButton, MenuContent } from '@platform/ui';
import { HuggingFaceIcon } from '@platform/ui/VendoredIcon';
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallProgressCell.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallProgressCell.tsx
index 564f8070bc..23e904c3e5 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallProgressCell.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallProgressCell.tsx
@@ -1,5 +1,5 @@
import { Progress, Stack, Text } from '@chakra-ui/react';
-import { formatBytes } from '@features/models/core/taxonomy';
+import { formatBytes } from '@platform/i18n/languages';
import { useTranslation } from 'react-i18next';
import type { InstallByteProgress, InstallRowStatus } from './queueModel';
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
index 0e8a513e17..22cb40d80a 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.browser.test.tsx
@@ -203,16 +203,16 @@ describe('InstallQueueBar', () => {
expect(rowByStatus('downloading')?.textContent).toContain(
'vantagewithai/Krea-2-Turbo-GGUF :: krea2_turbo-Q4_K_M.gguf'
);
- expect(rowByStatus('queued')?.textContent).toContain('Waiting · #1 in queue · 6.3 GB');
+ expect(rowByStatus('queued')?.textContent).toContain('Waiting · #1 in queue · 6.8 GB');
expect(rowByStatus('failed')?.textContent).toContain('DuplicateModelException');
expect(rowByStatus('failed')?.textContent).toContain('A model with this path is already installed.');
- expect(rowByStatus('failed')?.textContent).toContain('Stopped · 0 B copied');
+ expect(rowByStatus('failed')?.textContent).toContain('Stopped · 0 bytes copied');
expect(rowByStatus('unauthorized')?.textContent).toContain(
'This repo is gated. Add a Hugging Face token to continue.'
);
- expect(rowByStatus('unauthorized')?.textContent).toContain('Not started · 319.5 MB');
+ expect(rowByStatus('unauthorized')?.textContent).toContain('Not started · 335.0 MB');
expect(rowByStatus('installed')?.textContent).toContain('Done · LoRA');
- expect(rowByStatus('cancelled')?.textContent).toContain('Cancelled · 11.4 MB copied');
+ expect(rowByStatus('cancelled')?.textContent).toContain('Cancelled · 12.0 MB copied');
expect(await auditAccessibility(host!)).toEqual([]);
});
@@ -241,7 +241,7 @@ describe('InstallQueueBar', () => {
await settle();
const caption = rowByStatus('downloading')?.textContent ?? '';
- expect(caption).toContain('38% · 2.5 GB / 6.5 GB');
+ expect(caption).toContain('38% · 2.7 GB / 7.0 GB');
expect(caption).toMatch(/MB\/s · ~\d+ (s|min|h) left/);
await click('Install Queue');
@@ -249,7 +249,7 @@ describe('InstallQueueBar', () => {
expect(rows()).toHaveLength(0);
const bar = host?.textContent ?? '';
expect(bar).toContain('krea2_turbo-Q4_K_M.gguf');
- expect(bar).toContain('38% · 2.5 GB / 6.5 GB');
+ expect(bar).toContain('38% · 2.7 GB / 7.0 GB');
expect(bar).toContain('+1 queued');
expect(bar).toContain('2 need attention');
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
index d783376f02..f2d3539b78 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
@@ -6,11 +6,11 @@ import {
groupModelsByType,
type ModelLibraryFilters,
} from '@features/models/core/library';
-import { formatBytes } from '@features/models/core/taxonomy';
import { getModelImageUrl } from '@features/models/data/api';
import { useModelsSelector } from '@features/models/data/modelsStore';
import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from '@features/models/ui/detail/ModelBadges';
import { getLibraryScrollOffset, openModelManagerTab, saveLibraryScrollOffset } from '@features/models/ui/uiStore';
+import { formatBytes } from '@platform/i18n/languages';
import { Button, Row } from '@platform/ui';
import { EmptyState } from '@platform/ui/EmptyState';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
index d925fd7c0a..378a6e7de7 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx
@@ -2,10 +2,10 @@
import type { OrphanedModelInfo } from '@features/models/core/types';
import { Checkbox, Dialog, Flex, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
-import { formatBytes } from '@features/models/core/taxonomy';
import { deleteOrphanedModels, getOrphanedModels } from '@features/models/data/api';
import { refreshModels } from '@features/models/data/modelsStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { formatBytes } from '@platform/i18n/languages';
import { useMountEffect } from '@platform/react/useMountEffect';
import { useScopedAction } from '@platform/react/useScopedAction';
import {
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
index 4b10cd0f8a..78ba02d9b5 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
@@ -61,7 +61,7 @@ describe('model cache stats helpers', () => {
it('reports whether clear cache actually cleared models', () => {
expect(getModelCacheClearToast({ bytes_freed: 1024, models_cleared: 2 }, t)).toEqual({
- description: 'Cleared 2 cached models and freed 1.0 KB.',
+ description: 'Cleared 2 cached models and freed 1.0\u00a0KiB.',
status: 'success',
title: 'Model cache cleared',
});
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
index 548f5a3dd5..220774df63 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
@@ -1,5 +1,6 @@
import type { TFunction } from 'i18next';
+import { formatBytes } from '@platform/i18n/languages';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -9,23 +10,8 @@ import {
import { createExternalStore } from '@platform/state/externalStore';
import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';
-const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
-
-export const formatModelCacheBytes = (bytes: number | null | undefined): string => {
- if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) {
- return '—';
- }
-
- let value = bytes;
- let unitIndex = 0;
-
- while (value >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
- value /= 1024;
- unitIndex += 1;
- }
-
- return `${unitIndex === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[unitIndex]}`;
-};
+/** The backend sizes the model cache in binary gigabytes (GiB). */
+export const formatModelCacheBytes = (bytes: number | null | undefined): string => formatBytes(bytes, { binary: true });
/** Cache statistics have no socket stream; refresh on mount, model load, and clear. */
diff --git a/invokeai/frontend/webv2/src/platform/i18n/languages.test.ts b/invokeai/frontend/webv2/src/platform/i18n/languages.test.ts
new file mode 100644
index 0000000000..f8235b2f6e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/i18n/languages.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatBytes, formatCount } from './languages';
+
+describe('formatBytes', () => {
+ it('renders a dash for missing or invalid sizes', () => {
+ expect(formatBytes(null)).toBe('—');
+ expect(formatBytes(undefined)).toBe('—');
+ expect(formatBytes(-1)).toBe('—');
+ expect(formatBytes(Number.NaN)).toBe('—');
+ });
+
+ it('scales across decimal unit boundaries', () => {
+ expect(formatBytes(0, { locale: 'en' })).toBe('0 bytes');
+ expect(formatBytes(999, { locale: 'en' })).toBe('999 bytes');
+ expect(formatBytes(1000, { locale: 'en' })).toBe('1.0 kB');
+ expect(formatBytes(999_960, { locale: 'en' })).toBe('1.0 MB');
+ expect(formatBytes(1_500_000_000, { locale: 'en' })).toBe('1.5 GB');
+ });
+
+ it('follows the locale for separators and unit names', () => {
+ expect(formatBytes(1_500_000, { locale: 'de' })).toBe('1,5 MB');
+ expect(formatBytes(1_500_000, { locale: 'fr' }).replace(/\s/gu, ' ')).toBe('1,5 Mo');
+ });
+
+ it('scales binary sizes by 1024 under IEC labels, with localized digits', () => {
+ expect(formatBytes(512, { binary: true, locale: 'en' })).toBe('512\u00a0B');
+ expect(formatBytes(1024, { binary: true, locale: 'en' })).toBe('1.0\u00a0KiB');
+ expect(formatBytes(24 * 2 ** 30, { binary: true, locale: 'en' })).toBe('24.0\u00a0GiB');
+ expect(formatBytes(1.5 * 2 ** 20, { binary: true, locale: 'de' })).toBe('1,5\u00a0MiB');
+ });
+});
+
+describe('formatCount', () => {
+ it('groups digits for the locale', () => {
+ expect(formatCount(12_345, 'en')).toBe('12,345');
+ expect(formatCount(12_345, 'de')).toBe('12.345');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/i18n/languages.ts b/invokeai/frontend/webv2/src/platform/i18n/languages.ts
index ff4a5850fc..73f19f0719 100644
--- a/invokeai/frontend/webv2/src/platform/i18n/languages.ts
+++ b/invokeai/frontend/webv2/src/platform/i18n/languages.ts
@@ -46,3 +46,60 @@ export const normalizeWorkbenchLanguage = (value: unknown): WorkbenchLanguage |
export const getWorkbenchLanguageDirection = (language: WorkbenchLanguage): WorkbenchLanguageDirection =>
WORKBENCH_LANGUAGE_OPTIONS.find((option) => option.value === language)?.direction ?? 'ltr';
+
+const BYTE_UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte'] as const;
+const BINARY_BYTE_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'] as const;
+
+const documentLocale = (): string | undefined => globalThis.document?.documentElement.lang || undefined;
+
+// Constructing a NumberFormat costs far more than formatting with one, and these run per row in lists.
+const numberFormats = new Map<string, Intl.NumberFormat>();
+const getNumberFormat = (locale: string | undefined, options: Intl.NumberFormatOptions): Intl.NumberFormat => {
+ const key = `${locale ?? ''}\u0000${JSON.stringify(options)}`;
+ let format = numberFormats.get(key);
+ if (!format) {
+ format = new Intl.NumberFormat(locale, options);
+ numberFormats.set(key, format);
+ }
+ return format;
+};
+
+/** A whole count in the document language's digits and grouping. */
+export const formatCount = (count: number, locale: string | undefined = documentLocale()): string =>
+ getNumberFormat(locale, {}).format(count);
+
+/**
+ * A byte size with one decimal from kilobytes up, in the document language by default. Decimal (SI) units are the
+ * ones Intl can name; `binary` scales by 1024 and appends IEC labels (KiB, GiB) that Intl lacks. Missing, negative or
+ * non-finite sizes render as a dash.
+ */
+export const formatBytes = (
+ bytes: number | null | undefined,
+ { binary = false, locale = documentLocale() }: { binary?: boolean; locale?: string } = {}
+): string => {
+ if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) {
+ return '—';
+ }
+
+ const base = binary ? 1024 : 1000;
+ let value = bytes;
+ let unit = 0;
+
+ while (Math.round(value * 10) / 10 >= base && unit < BYTE_UNITS.length - 1) {
+ value /= base;
+ unit += 1;
+ }
+
+ const digits = unit === 0 ? 0 : 1;
+ if (binary) {
+ const number = getNumberFormat(locale, { maximumFractionDigits: digits, minimumFractionDigits: digits });
+ return `${number.format(value)}\u00a0${BINARY_BYTE_UNITS[unit]}`;
+ }
+ return getNumberFormat(locale, {
+ maximumFractionDigits: digits,
+ minimumFractionDigits: digits,
+ style: 'unit',
+ unit: BYTE_UNITS[unit],
+ unitDisplay: unit === 0 ? 'long' : 'short',
+ }).format(value);
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/RemovableTag.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/RemovableTag.browser.test.tsx
new file mode 100644
index 0000000000..b912adf216
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/RemovableTag.browser.test.tsx
@@ -0,0 +1,60 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { RemovableTag } from './RemovableTag';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+const noop = (): void => undefined;
+
+const renderTag = async (label: string): Promise<HTMLElement> => {
+ host = document.createElement('div');
+ host.style.cssText = 'display:flex;width:160px;';
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <RemovableTag removeLabel="Show everyone" onRemove={noop}>
+ {label}
+ </RemovableTag>
+ </ChakraProvider>
+ );
+ });
+ return [...host.querySelectorAll<HTMLElement>('span')].find((node) => node.textContent === label)!;
+};
+
+const tooltipWith = (text: string) =>
+ [...document.querySelectorAll('[role="tooltip"]')].find((node) => node.textContent?.includes(text));
+
+it('reveals a truncated label in full on hover and keeps the remove control named', async () => {
+ const label = 'Account: [email protected]';
+ const element = await renderTag(label);
+ expect(element.scrollWidth).toBeGreaterThan(element.clientWidth);
+ expect(host!.querySelector('button[aria-label="Show everyone"]')).not.toBeNull();
+
+ await userEvent.hover(element);
+ await expect.poll(() => tooltipWith(label)).toBeDefined();
+});
+
+it('shows no tooltip for a label that fits', async () => {
+ const element = await renderTag('Mine');
+ await userEvent.hover(element);
+ await new Promise((resolve) => {
+ setTimeout(resolve, 800);
+ });
+ expect(tooltipWith('Mine')).toBeUndefined();
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/RemovableTag.tsx b/invokeai/frontend/webv2/src/platform/ui/RemovableTag.tsx
new file mode 100644
index 0000000000..498122a75c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/RemovableTag.tsx
@@ -0,0 +1,40 @@
+import type { ReactNode } from 'react';
+
+import { Tag } from '@chakra-ui/react';
+import { useCallback, useRef, useState } from 'react';
+
+import { Tooltip } from './Tooltip';
+
+export interface RemovableTagProps {
+ children: ReactNode;
+ /** Names the remove control and its tooltip, e.g. "Show all projects". */
+ removeLabel: string;
+ onRemove: () => void;
+ disabled?: boolean;
+}
+
+/** A compact chip for an applied filter or value, with an icon-only remove control. */
+export const RemovableTag = ({ children, disabled, onRemove, removeLabel }: RemovableTagProps) => {
+ const labelRef = useRef<HTMLSpanElement | null>(null);
+ const [isLabelTipOpen, setIsLabelTipOpen] = useState(false);
+ // Only a truncated label needs its full text on hover.
+ const handleLabelTipChange = useCallback(({ open }: { open: boolean }) => {
+ const label = labelRef.current;
+ setIsLabelTipOpen(open && label !== null && label.scrollWidth > label.clientWidth);
+ }, []);
+
+ return (
+ <Tag.Root flexShrink={0} maxW="full" minW="0" size="sm" variant="surface">
+ <Tooltip content={children} open={isLabelTipOpen} onOpenChange={handleLabelTipChange}>
+ <Tag.Label ref={labelRef} truncate>
+ {children}
+ </Tag.Label>
+ </Tooltip>
+ <Tag.EndElement>
+ <Tooltip content={removeLabel}>
+ <Tag.CloseTrigger aria-label={removeLabel} disabled={disabled} onClick={onRemove} />
+ </Tooltip>
+ </Tag.EndElement>
+ </Tag.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index bd7f7179ad..d58654c42b 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -18,7 +18,11 @@ import { createExtensionRegistry, type ExtensionRegistry } from './extensions/ex
import { clearLayerPanelStates } from './layerPanelState';
import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';
import { createOpenProjectBroker } from './projects/openProjectBroker';
-import { createOpenProjectsHeldMediaReader } from './projects/projectAssets';
+import {
+ createCanvasHeldMediaSources,
+ createOpenProjectsHeldMediaReader,
+ type CanvasHeldMediaSources,
+} from './projects/projectAssets';
import { describeRefusedProjects } from './projects/projectLoadRefusal';
import {
createSyncedWorkbenchPersistence,
@@ -41,6 +45,7 @@ type WorkbenchSelector<T> = (snapshot: WorkbenchSnapshot) => T;
const WorkbenchStoreContext = createContext<WorkbenchInternalStore | null>(null);
const WorkbenchPersistenceContext = createContext<SyncedWorkbenchPersistence | null>(null);
const WorkbenchExtensionsContext = createContext<ExtensionRegistry | null>(null);
+const WorkbenchCanvasHeldMediaContext = createContext<CanvasHeldMediaSources | null>(null);
const subscribeToNothing = (): (() => void) => () => {};
const getNullSnapshot = (): null => null;
@@ -59,6 +64,7 @@ export const WorkbenchProvider = ({
const { t } = useTranslation();
const [persistence] = useState(() => createSyncedWorkbenchPersistence(owner));
const [extensions] = useState(createExtensionRegistry);
+ const [canvasHeldMedia] = useState(createCanvasHeldMediaSources);
const [loadUnavailable, setLoadUnavailable] = useState<{ message: string; retry(): void } | null>(null);
const hasHydrated = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot).hasHydrated;
@@ -138,16 +144,21 @@ export const WorkbenchProvider = ({
persistenceRuntime.start();
const releaseIntermediateHold = startIntermediatesHoldLease({
owner,
- read: createOpenProjectsHeldMediaReader(() => store.getSnapshot().projects),
+ read: createOpenProjectsHeldMediaReader(() => store.getSnapshot().projects, canvasHeldMedia.read),
subscribe: (onChange) => {
let projects = store.getSnapshot().projects;
- return store.subscribe(() => {
+ const unsubscribeProjects = store.subscribe(() => {
const next = store.getSnapshot().projects;
if (next !== projects) {
projects = next;
onChange();
}
});
+ const unsubscribeCanvas = canvasHeldMedia.subscribe(onChange);
+ return () => {
+ unsubscribeProjects();
+ unsubscribeCanvas();
+ };
},
});
@@ -162,21 +173,23 @@ export const WorkbenchProvider = ({
return (
<WorkbenchPersistenceContext value={persistence}>
- <WorkbenchExtensionsContext value={extensions}>
- <WorkbenchStoreContext value={store}>
- {loadUnavailable ? (
- <WorkbenchUnavailableScreen
- message={loadUnavailable.message}
- onRetry={loadUnavailable.retry}
- persistence={persistence}
- />
- ) : hasHydrated ? (
- children
- ) : (
- <WorkbenchSplashScreen messageKey="splash.openingProject" />
- )}
- </WorkbenchStoreContext>
- </WorkbenchExtensionsContext>
+ <WorkbenchCanvasHeldMediaContext value={canvasHeldMedia}>
+ <WorkbenchExtensionsContext value={extensions}>
+ <WorkbenchStoreContext value={store}>
+ {loadUnavailable ? (
+ <WorkbenchUnavailableScreen
+ message={loadUnavailable.message}
+ onRetry={loadUnavailable.retry}
+ persistence={persistence}
+ />
+ ) : hasHydrated ? (
+ children
+ ) : (
+ <WorkbenchSplashScreen messageKey="splash.openingProject" />
+ )}
+ </WorkbenchStoreContext>
+ </WorkbenchExtensionsContext>
+ </WorkbenchCanvasHeldMediaContext>
</WorkbenchPersistenceContext>
);
};
@@ -302,6 +315,15 @@ export const useWorkbenchPersistenceService = (): SyncedWorkbenchPersistence =>
export const useOptionalWorkbenchPersistenceService = (): SyncedWorkbenchPersistence | null =>
use(WorkbenchPersistenceContext);
+/** Where live Canvas engines register the undo state the hold lease must keep. */
+export const useWorkbenchCanvasHeldMedia = (): CanvasHeldMediaSources => {
+ const heldMedia = use(WorkbenchCanvasHeldMediaContext);
+ if (!heldMedia) {
+ throw new Error('useWorkbenchCanvasHeldMedia must be used within a WorkbenchProvider.');
+ }
+ return heldMedia;
+};
+
export const useWorkbenchExtensions = (): ExtensionRegistry => {
const extensions = use(WorkbenchExtensionsContext);
if (!extensions) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts
new file mode 100644
index 0000000000..c9697529d6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts
@@ -0,0 +1,312 @@
+import type { CanvasLayerContract, CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';
+import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { createCanvasEngine, type CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import { createInitialWorkbenchState, type WorkbenchAction, workbenchReducer } from '@workbench/workbenchState.testing';
+import { describe, expect, it } from 'vitest';
+
+const imageLayer = (id: string, imageName: string): CanvasLayerContract => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { image: { height: 10, imageName, width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+});
+
+const maskLayer = (id: string, imageName: string): CanvasLayerContract => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: { height: 10, imageName, width: 10 }, fill: { color: '#e07575', style: 'diagonal' } },
+ name: id,
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'inpaint_mask',
+});
+
+const stagedCandidate: CanvasStagingCandidateContract = {
+ height: 10,
+ imageName: 'staged-result.png',
+ imageUrl: '/staged-result.png',
+ placement: { height: 10, opacity: 1, width: 10, x: 0, y: 0 },
+ queuedAt: '2026-07-16T00:00:00.000Z',
+ sourceQueueItemId: 'queue-staged',
+ thumbnailUrl: '/staged-result-thumb.png',
+ width: 10,
+};
+
+const createHarness = (layers: CanvasLayerContract[]) => {
+ let state = createInitialWorkbenchState();
+ const projectId = state.projects[0]!.id;
+ const listeners = new Set<() => void>();
+ const dispatch = (action: WorkbenchAction): void => {
+ state = workbenchReducer(state, action);
+ for (const listener of listeners) {
+ listener();
+ }
+ };
+ const apply = (mutation: CanvasProjectMutation): void =>
+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' });
+ apply({
+ document: {
+ background: 'transparent',
+ bbox: { height: 6, width: 6, x: 2, y: 2 },
+ height: 100,
+ selectedLayerId: layers[0]?.id ?? null,
+ stacks: stacksFrom(layers),
+ version: 3,
+ width: 100,
+ },
+ type: 'replaceCanvasDocument',
+ });
+ const getCanvasState = () => state.projects.find((project) => project.id === projectId)?.canvas ?? null;
+ const mutationPort: CanvasProjectMutationPort = {
+ commitEdit: () => undefined,
+ dispatch: (mutation) => {
+ const before = getCanvasState();
+ apply(mutation);
+ return getCanvasState() !== before;
+ },
+ getCanvasState,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ ensureProjectOnServer: () => Promise.resolve(),
+ getMainModelBase: () => null,
+ imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort,
+ projectId,
+ reportError: () => undefined,
+ });
+ return { dispatch, engine, projectId };
+};
+
+type Harness = ReturnType<typeof createHarness>;
+
+const guardFor = async (engine: CanvasEngine, layerId: string) => {
+ const exported = await engine.exports.exportLayerPixels(layerId);
+ if (exported.status !== 'ok') {
+ throw new Error(`expected exportable ${layerId}, got ${exported.status}`);
+ }
+ return exported.guard;
+};
+
+const warmCaches = async (engine: CanvasEngine, layerIds: readonly string[]): Promise<void> => {
+ for (const layerId of layerIds) {
+ expect(await engine.previews.requestLayerThumbnail(layerId)).toBe('ready');
+ }
+};
+
+const resultImage = (imageName: string) => ({ height: 10, imageName, width: 10 });
+const resultRect = { height: 10, width: 10, x: 1, y: 1 };
+
+interface HeldCase {
+ name: string;
+ layers: CanvasLayerContract[];
+ act(harness: Harness): unknown;
+ /** Names Canvas must hold after the operation (the replaced sources). */
+ heldAfterOp: string[];
+ /** Names Canvas must hold after undoing it (what redo would restore). */
+ heldAfterUndo: string[];
+}
+
+const cases: HeldCase[] = [
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['a']);
+ return engine.layers.cropLayerToBbox('a');
+ },
+ heldAfterOp: ['original-crop.png'],
+ heldAfterUndo: ['original-crop.png'],
+ layers: [imageLayer('a', 'original-crop.png')],
+ name: 'crop',
+ },
+ {
+ act: async ({ engine }) =>
+ engine.layers.commitRasterFilterResult({
+ guard: await guardFor(engine, 'a'),
+ image: resultImage('filter-replace-result.png'),
+ mode: 'replace',
+ rect: resultRect,
+ }),
+ heldAfterOp: ['original-filter-replace.png'],
+ heldAfterUndo: ['filter-replace-result.png'],
+ layers: [imageLayer('a', 'original-filter-replace.png')],
+ name: 'filter result replace',
+ },
+ {
+ act: async ({ engine }) =>
+ engine.layers.commitRasterFilterResult({
+ guard: await guardFor(engine, 'a'),
+ image: resultImage('filter-copy-result.png'),
+ mode: 'copy',
+ rect: resultRect,
+ }),
+ heldAfterOp: ['filter-copy-result.png'],
+ heldAfterUndo: ['filter-copy-result.png'],
+ layers: [imageLayer('a', 'original-filter-copy.png')],
+ name: 'filter result copy',
+ },
+ {
+ act: async ({ engine }) =>
+ engine.layers.commitGeneratedImageResult({
+ guard: await guardFor(engine, 'a'),
+ image: resultImage('generated-replace-result.png'),
+ origin: { x: 1, y: 1 },
+ target: 'replace',
+ }),
+ heldAfterOp: ['original-generated-replace.png'],
+ heldAfterUndo: ['generated-replace-result.png'],
+ layers: [imageLayer('a', 'original-generated-replace.png')],
+ name: 'generated result replace',
+ },
+ {
+ act: async ({ engine }) =>
+ engine.layers.commitGeneratedImageResult({
+ guard: await guardFor(engine, 'a'),
+ image: resultImage('generated-copy-result.png'),
+ origin: { x: 1, y: 1 },
+ target: 'copy-raster',
+ }),
+ heldAfterOp: ['generated-copy-result.png'],
+ heldAfterUndo: ['generated-copy-result.png'],
+ layers: [imageLayer('a', 'original-generated-copy.png')],
+ name: 'generated result copy',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['upper', 'below']);
+ return engine.layers.mergeSelectedRasterLayers(['upper', 'below']);
+ },
+ heldAfterOp: ['original-merge-selected-upper.png', 'original-merge-selected-below.png'],
+ heldAfterUndo: ['original-merge-selected-upper.png', 'original-merge-selected-below.png'],
+ layers: [
+ imageLayer('upper', 'original-merge-selected-upper.png'),
+ imageLayer('below', 'original-merge-selected-below.png'),
+ ],
+ name: 'merge selected',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['upper', 'below']);
+ return engine.layers.mergeVisibleRasterLayers();
+ },
+ heldAfterOp: ['original-merge-visible-upper.png', 'original-merge-visible-below.png'],
+ heldAfterUndo: ['original-merge-visible-upper.png', 'original-merge-visible-below.png'],
+ layers: [
+ imageLayer('upper', 'original-merge-visible-upper.png'),
+ imageLayer('below', 'original-merge-visible-below.png'),
+ ],
+ name: 'merge visible',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['a']);
+ const live = getDocumentLeaves(engine.document.getDocument()!)[0]!;
+ if (live.type !== 'raster') {
+ throw new Error('expected a raster conversion source');
+ }
+ return engine.layers.commitLayerConversion('Convert layer', live, {
+ ...live,
+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
+ type: 'control',
+ withTransparencyEffect: false,
+ });
+ },
+ heldAfterOp: ['original-convert.png'],
+ heldAfterUndo: ['original-convert.png'],
+ layers: [imageLayer('a', 'original-convert.png')],
+ name: 'convert layer type',
+ },
+ {
+ act: ({ dispatch, engine, projectId }) => {
+ dispatch({ candidate: stagedCandidate, projectId, type: 'appendCanvasStagingCandidate' });
+ return engine.layers.commitStagedImage({ candidate: stagedCandidate, selectedImageIndex: 0 });
+ },
+ heldAfterOp: ['staged-result.png'],
+ heldAfterUndo: ['staged-result.png'],
+ layers: [imageLayer('a', 'original-staged.png')],
+ name: 'staged result accept',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['mask']);
+ return engine.layers.clearMask('mask');
+ },
+ heldAfterOp: ['original-mask-clear.png'],
+ heldAfterUndo: ['original-mask-clear.png'],
+ layers: [maskLayer('mask', 'original-mask-clear.png')],
+ name: 'mask clear',
+ },
+ {
+ act: async ({ engine }) =>
+ engine.layers.commitMaskImageResult({
+ guard: await guardFor(engine, 'a'),
+ image: resultImage('mask-result.png'),
+ rect: resultRect,
+ target: 'inpaint_mask',
+ }),
+ heldAfterOp: ['mask-result.png'],
+ heldAfterUndo: ['mask-result.png'],
+ layers: [imageLayer('a', 'original-mask-result.png')],
+ name: 'mask result',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['a']);
+ const source = getDocumentLeaves(engine.document.getDocument()!)[0]!;
+ return engine.layers.commitLayerCopy(
+ 'Copy layer',
+ 'a',
+ { ...structuredClone(source), id: 'a-copy', name: 'a copy' },
+ engine.document.captureInsertionAnchor('raster', 'a')
+ );
+ },
+ heldAfterOp: ['original-copy.png'],
+ heldAfterUndo: ['original-copy.png'],
+ layers: [imageLayer('a', 'original-copy.png')],
+ name: 'copy layer',
+ },
+ {
+ act: async ({ engine }) => {
+ await warmCaches(engine, ['a']);
+ return engine.layers.duplicateLayers(['a']);
+ },
+ heldAfterOp: ['original-duplicate.png'],
+ heldAfterUndo: ['original-duplicate.png'],
+ layers: [imageLayer('a', 'original-duplicate.png')],
+ name: 'duplicate layer',
+ },
+];
+
+describe('Canvas history holds resurrectable media', () => {
+ it.each(cases)('$name', async ({ act, heldAfterOp, heldAfterUndo, layers }) => {
+ const harness = createHarness(layers);
+ const { engine } = harness;
+
+ await act(harness);
+ expect(engine.stores.canUndo.get()).toBe(true);
+ expect(engine.history.getHeldAssetRefs().images).toEqual(expect.arrayContaining(heldAfterOp));
+
+ engine.history.undo();
+ expect(engine.stores.canRedo.get()).toBe(true);
+ expect(engine.history.getHeldAssetRefs().images).toEqual(expect.arrayContaining(heldAfterUndo));
+
+ engine.history.clearHistory();
+ expect(engine.history.getHeldAssetRefs().images).toEqual([]);
+ engine.lifecycle.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
index 5db9ff2667..995bf22aec 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
@@ -4,7 +4,7 @@
* recording and `push` is a no-op, avoiding recursive history.
*/
-import { collectRestorableAssetRefs } from '@workbench/projects/projectAssets';
+import { collectRestorableAssetRefs } from '@workbench/mediaReferences';
/** Max number of undo entries retained before the oldest is evicted. */
export const HISTORY_MAX_ENTRIES = 64;
@@ -96,7 +96,7 @@ export interface History {
*/
entries(): { past: readonly string[]; future: readonly string[] };
/** Union of media references retained by undo and redo entries. */
- heldAssetRefs(): { images: string[]; videos: string[] };
+ heldAssetRefs(): HeldAssetRefs;
/** Subscribes to every stack mutation (push, amend, undo, redo, clear, eviction). Returns an unsubscribe function. */
subscribe(listener: () => void): () => void;
}
@@ -168,14 +168,25 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {
past: undoStack.map((entry) => entry.label),
});
- const heldAssetRefs = (): { images: string[]; videos: string[] } => {
+ // Reused while the stacks hold the same entries, so an unchanged union keeps its identity for the hold lease.
+ let heldUnion: { parts: HeldAssetRefs[]; refs: HeldAssetRefs } | null = null;
+ const heldAssetRefs = (): HeldAssetRefs => {
+ const parts = [...undoStack, ...redoStack].map((entry) => entry.heldAssetRefs);
+ if (
+ heldUnion &&
+ heldUnion.parts.length === parts.length &&
+ parts.every((part, i) => part === heldUnion!.parts[i])
+ ) {
+ return heldUnion.refs;
+ }
const images = new Set<string>();
const videos = new Set<string>();
- for (const entry of [...undoStack, ...redoStack]) {
- entry.heldAssetRefs.images.forEach((name) => images.add(name));
- entry.heldAssetRefs.videos.forEach((name) => videos.add(name));
+ for (const part of parts) {
+ part.images.forEach((name) => images.add(name));
+ part.videos.forEach((name) => videos.add(name));
}
- return { images: [...images], videos: [...videos] };
+ heldUnion = { parts, refs: { images: [...images], videos: [...videos] } };
+ return heldUnion.refs;
};
const push = (entry: HistoryEntry): void => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
index dcea68d725..d73f776cb2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
@@ -51,6 +51,19 @@ export class CanvasImageUploadError extends Error {
}
}
+/** The server's refusal of a `project_id` it has no record of for this account (`assert_project_owned`). */
+export const isUploadProjectNotFound = (error: unknown): boolean => {
+ if (!(error instanceof CanvasImageUploadError) || error.status !== 404) {
+ return false;
+ }
+ try {
+ const body: unknown = JSON.parse(error.message);
+ return typeof body === 'object' && body !== null && 'detail' in body && body.detail === 'Project not found';
+ } catch {
+ return false;
+ }
+};
+
export const uploadCanvasImage = async (
blob: Blob,
options: UploadCanvasImageOptions = {}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
index ca65f4560c..c92f73125a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
@@ -9,6 +9,7 @@ import type { BackendGraphContract } from '@workbench/graphContracts';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { createCanvasEngine as createCanvasEngineCore } from '@workbench/canvas-engine/engine';
import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';
+import { isUploadProjectNotFound } from '@workbench/canvas-operations/backend/canvasImages';
import { createBoundedCompositeDedupeCache } from '@workbench/canvas-operations/compositeForGeneration';
import { composeForGeneration } from '@workbench/canvas-operations/generationComposite';
@@ -45,6 +46,18 @@ export interface CanvasEngineOptions extends Omit<
}
export type CanvasOperationsCapability = CanvasOperationCapability;
+
+/** Settles with `promise`, or rejects with the abort reason as soon as `signal` aborts. */
+const raceAbort = <T>(promise: Promise<T>, signal: AbortSignal): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
+ const onAbort = (): void => reject(signal.reason);
+ signal.addEventListener('abort', onAbort, { once: true });
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
+ });
+
+/** How long uploads skip provenance after the server reported the project missing, before trying it again. */
+const MISSING_PROJECT_REUSE_MS = 60_000;
+
/** Private application composition shape; public callers receive the capability-only handle from the registry API. */
export type CanvasEngine = CoreCanvasEngineImplementation;
@@ -53,10 +66,11 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
const { ensureProjectOnServer, filterDeps, selectObjectDeps, ...coreOptions } = options;
const owner = captureAccountScope();
const uploadLifetime = new AbortController();
+ let projectMissingAt = -Infinity;
const resolveUploadProjectId = async (): Promise<string | undefined> => {
try {
await ensureProjectOnServer();
- return options.projectId;
+ return Date.now() - projectMissingAt < MISSING_PROJECT_REUSE_MS ? undefined : options.projectId;
} catch (error) {
// A project the server has not accepted (offline, conflicted, deleted elsewhere) costs the upload its
// provenance, never the edit; only a closed project stops it.
@@ -74,10 +88,24 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
...(uploadOptions?.signal ? [uploadOptions.signal] : []),
]);
signal.throwIfAborted();
- const projectId = await resolveUploadProjectId();
- assertAccountScopeCurrent(owner);
+ let projectId: string | undefined;
+ try {
+ projectId = await raceAbort(resolveUploadProjectId(), signal);
+ } finally {
+ assertAccountScopeCurrent(owner);
+ }
signal.throwIfAborted();
- return canvasApplicationPort.uploadImage(blob, { ...uploadOptions, projectId, signal });
+ try {
+ return await canvasApplicationPort.uploadImage(blob, { ...uploadOptions, projectId, signal });
+ } catch (error) {
+ // Deleted elsewhere before this editor noticed: the upload still lands, without provenance.
+ if (projectId === undefined || !isUploadProjectNotFound(error)) {
+ throw error;
+ }
+ assertAccountScopeCurrent(owner);
+ projectMissingAt = Date.now();
+ return canvasApplicationPort.uploadImage(blob, { ...uploadOptions, projectId: undefined, signal });
+ }
};
const composition = createCanvasEngineCore({
...coreOptions,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
index c24e7189a0..38ba777bb1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
@@ -21,7 +21,7 @@ import {
} from '@workbench/canvas-operations/generationCompositePlan';
import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
-import { getCanvasHeldAssetRefs } from '@workbench/projects/projectAssets';
+import { createCanvasHeldMediaSources } from '@workbench/projects/projectAssets';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { describe, expect, it, vi } from 'vitest';
@@ -147,17 +147,57 @@ const createFakeTimers = (): { timers: RegistryTimers; flush: () => void; pendin
describe('createEngineRegistry', () => {
it('disposes the process registry synchronously when its account expires', () => {
accountLifecycle.activate('user-a');
- const engine = getOrCreateEngine('shared-project-id', createFakeDeps());
+ const heldMedia = createCanvasHeldMediaSources();
+ const engine = getOrCreateEngine('shared-project-id', { ...createFakeDeps(), heldMedia });
const dispose = vi.spyOn(engine.lifecycle, 'dispose');
- expect(getCanvasHeldAssetRefs('shared-project-id')).toEqual({ images: [], videos: [] });
+ expect(heldMedia.read('shared-project-id')).toEqual({ images: [], videos: [] });
accountLifecycle.invalidate();
expect(getCanvasEngine('shared-project-id')).toBeUndefined();
- expect(getCanvasHeldAssetRefs('shared-project-id')).toBeUndefined();
+ expect(heldMedia.read('shared-project-id')).toBeUndefined();
expect(dispose).toHaveBeenCalledOnce();
});
+ it('keeps a released engine for its own Workbench but replaces it for a remounted one', () => {
+ const { flush, timers } = createFakeTimers();
+ const registry = createEngineRegistry({ timers });
+ const first = createCanvasHeldMediaSources();
+ const second = createCanvasHeldMediaSources();
+ const onHeldChange = vi.fn();
+ first.subscribe(onHeldChange);
+
+ const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first });
+ registry.releaseEngine('p1');
+ expect(registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first })).toBe(engine);
+ registry.releaseEngine('p1');
+ const dispose = vi.spyOn(engine.lifecycle, 'dispose');
+ onHeldChange.mockClear();
+
+ const replacement = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: second });
+ expect(replacement).not.toBe(engine);
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(first.read('p1')).toBeUndefined();
+ expect(onHeldChange).toHaveBeenCalled();
+ expect(second.read('p1')).toEqual({ images: [], videos: [] });
+ flush();
+ expect(registry.getEngine('p1')).toBe(replacement);
+ registry.disposeAll();
+ });
+
+ it('refuses an engine another Workbench still uses instead of sharing or replacing it', () => {
+ const registry = createEngineRegistry();
+ const first = createCanvasHeldMediaSources();
+ const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first });
+
+ expect(() =>
+ registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: createCanvasHeldMediaSources() })
+ ).toThrow(/another Workbench/);
+ expect(registry.getEngine('p1')).toBe(engine);
+ expect(first.read('p1')).toEqual({ images: [], videos: [] });
+ registry.disposeAll();
+ });
+
it('returns the same instance per project id and distinct instances across ids', () => {
const registry = createEngineRegistry();
const deps = createFakeDeps();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
index 657972f941..1518d73a9f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
@@ -4,6 +4,7 @@
*/
import type { CanvasEngine as PublicCanvasEngine } from '@workbench/canvas-engine/api';
+import type { CanvasHeldMediaSources } from '@workbench/projects/projectAssets';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import {
@@ -11,10 +12,15 @@ import {
type CanvasEngine,
type CanvasEngineOptions,
} from '@workbench/canvas-operations/createCanvasEngine';
-import { registerCanvasHeldAssetRefs } from '@workbench/projects/projectAssets';
/** Engine creation dependencies, minus the project id the registry supplies. */
-export type EngineDeps = Omit<CanvasEngineOptions, 'projectId'>;
+export type EngineDeps = Omit<CanvasEngineOptions, 'projectId'> & {
+ /**
+ * The mounted Workbench's held-media registry. It also identifies that Workbench: an engine is bound to the one
+ * that created it, so a released engine is replaced rather than reused by the next Workbench.
+ */
+ heldMedia?: CanvasHeldMediaSources;
+};
/** Default grace period before a released engine is disposed (30s). */
export const DEFAULT_GRACE_PERIOD_MS = 30_000;
@@ -39,7 +45,8 @@ export interface EngineRegistry {
interface RegistryEntry {
engine: CanvasEngine;
- releaseHeldAssetRefs: () => void;
+ heldMedia: CanvasHeldMediaSources | undefined;
+ releaseHeldMedia: () => void;
refCount: number;
disposeHandle: number | null;
generation: number;
@@ -55,7 +62,6 @@ const defaultTimers: RegistryTimers = {
export const createEngineRegistry = (
options: {
gracePeriodMs?: number;
- registerHeldAssetRefs?: typeof registerCanvasHeldAssetRefs;
timers?: RegistryTimers;
} = {}
): EngineRegistry => {
@@ -83,7 +89,7 @@ export const createEngineRegistry = (
return;
}
entries.delete(projectId);
- entry.releaseHeldAssetRefs();
+ entry.releaseHeldMedia();
entry.engine.lifecycle.dispose();
});
}, gracePeriodMs);
@@ -97,7 +103,7 @@ export const createEngineRegistry = (
entries.clear();
for (const entry of ownedEntries) {
cancelDisposal(entry);
- entry.releaseHeldAssetRefs();
+ entry.releaseHeldMedia();
try {
entry.engine.lifecycle.dispose();
} catch (error) {
@@ -112,9 +118,13 @@ export const createEngineRegistry = (
}
},
getEngine: (projectId) => entries.get(projectId)?.engine,
- getOrCreateEngine: (projectId, deps) => {
+ getOrCreateEngine: (projectId, { heldMedia, ...deps }) => {
const existing = entries.get(projectId);
- if (existing) {
+ if (existing && existing.heldMedia !== heldMedia && existing.refCount > 0) {
+ // Its edits and held media belong to the Workbench still using it; sharing it would cross that boundary.
+ throw new Error(`The canvas engine for project ${projectId} is still in use by another Workbench.`);
+ }
+ if (existing && existing.heldMedia === heldMedia) {
cancelDisposal(existing);
existing.generation += 1;
existing.refCount += 1;
@@ -122,16 +132,27 @@ export const createEngineRegistry = (
existing.cooldown = null;
return existing.engine;
}
+ if (existing) {
+ // A released engine still writes through the Workbench that created it; a new Workbench gets its own.
+ entries.delete(projectId);
+ cancelDisposal(existing);
+ existing.releaseHeldMedia();
+ existing.engine.lifecycle.dispose();
+ }
const engine = createCanvasEngine({ projectId, ...deps });
- const releaseHeldAssetRefs =
- options.registerHeldAssetRefs?.(projectId, () => engine.history.getHeldAssetRefs()) ?? (() => undefined);
+ const releaseHeldMedia =
+ heldMedia?.register(projectId, {
+ read: () => engine.history.getHeldAssetRefs(),
+ subscribe: (listener) => engine.interaction.subscribe('historyEpoch', listener),
+ }) ?? (() => undefined);
entries.set(projectId, {
cooldown: null,
disposeHandle: null,
engine,
generation: 0,
+ heldMedia,
refCount: 1,
- releaseHeldAssetRefs,
+ releaseHeldMedia,
});
return engine;
},
@@ -153,7 +174,7 @@ export const createEngineRegistry = (
};
/** The process-wide default registry shared by all widget surfaces. */
-const defaultRegistry = createEngineRegistry({ registerHeldAssetRefs: registerCanvasHeldAssetRefs });
+const defaultRegistry = createEngineRegistry();
registerAccountOwnedResource({
clear: defaultRegistry.disposeAll,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/projectUploads.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/projectUploads.test.ts
index 1ae36b0672..757db7fe69 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/projectUploads.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/projectUploads.test.ts
@@ -5,6 +5,7 @@ import { createWorkbenchStore } from '@workbench/workbenchStore';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { canvasApplicationPort } from './applicationPort';
+import { CanvasImageUploadError } from './backend/canvasImages';
import { createCanvasEngine } from './createCanvasEngine';
import { getCanvasOperations } from './operationAccess';
@@ -75,6 +76,51 @@ describe('project-owned canvas uploads', () => {
}
});
+ it('retries without provenance only when the server no longer knows the project', async () => {
+ const engine = createEngine(() => Promise.resolve());
+ const upload = vi
+ .spyOn(canvasApplicationPort, 'uploadImage')
+ .mockRejectedValueOnce(new CanvasImageUploadError('{"detail":"Project not found"}', 404))
+ .mockResolvedValueOnce({ height: 8, imageName: 'unowned.png', width: 8 })
+ .mockRejectedValueOnce(new CanvasImageUploadError('{"detail":"Board not found"}', 404));
+ try {
+ await expect(getCanvasOperations(engine).uploadIntermediate(new Blob())).resolves.toMatchObject({
+ imageName: 'unowned.png',
+ });
+ expect(upload.mock.calls.map(([, options]) => options?.projectId)).toEqual([engine.projectId, undefined]);
+
+ await expect(getCanvasOperations(engine).uploadIntermediate(new Blob())).rejects.toMatchObject({ status: 404 });
+ expect(upload).toHaveBeenCalledTimes(3);
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
+ it('sends later uploads once without provenance after a missing project, and tries it again later', async () => {
+ let now = 1_000_000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const engine = createEngine(() => Promise.resolve());
+ const upload = vi
+ .spyOn(canvasApplicationPort, 'uploadImage')
+ .mockRejectedValueOnce(new CanvasImageUploadError('{"detail":"Project not found"}', 404))
+ .mockResolvedValue({ height: 8, imageName: 'unowned.png', width: 8 });
+ try {
+ await getCanvasOperations(engine).uploadIntermediate(new Blob());
+ await getCanvasOperations(engine).uploadIntermediate(new Blob());
+ expect(upload.mock.calls.map(([, options]) => options?.projectId)).toEqual([
+ engine.projectId,
+ undefined,
+ undefined,
+ ]);
+
+ now += 60_000;
+ await getCanvasOperations(engine).uploadIntermediate(new Blob());
+ expect(upload.mock.calls.at(-1)![1]).toMatchObject({ projectId: engine.projectId });
+ } finally {
+ engine.lifecycle.dispose();
+ }
+ });
+
it('does not upload for a project that closed while it waited', async () => {
const engine = createEngine(() =>
Promise.reject(new DOMException('The canvas project is no longer open.', 'AbortError'))
@@ -91,7 +137,7 @@ describe('project-owned canvas uploads', () => {
});
it.each(['account change', 'engine disposal', 'operation cancellation'] as const)(
- 'does not start a waiting upload after %s',
+ 'stops waiting for the project and never uploads after %s',
async (cancellation) => {
let acknowledge!: () => void;
const ready = new Promise<void>((resolve) => {
@@ -112,8 +158,9 @@ describe('project-owned canvas uploads', () => {
} else {
controller.abort();
}
- acknowledge();
await rejected;
+ acknowledge();
+ await Promise.resolve();
expect(upload).not.toHaveBeenCalled();
} finally {
engine.lifecycle.dispose();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
index 883cf2a651..99b5754394 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
@@ -9,6 +9,7 @@ import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/con
import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';
import {
useActiveProjectId,
+ useWorkbenchCanvasHeldMedia,
useWorkbenchCommands,
useWorkbenchInternalStore,
useWorkbenchPersistenceService,
@@ -68,6 +69,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {
const fonts = useFontRuntime();
const store = useWorkbenchInternalStore();
const persistence = useWorkbenchPersistenceService();
+ const heldMedia = useWorkbenchCanvasHeldMedia();
const { notifications } = useWorkbenchCommands();
const projectId = useActiveProjectId();
const resource = useMemo(
@@ -83,6 +85,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {
throw new DOMException('The canvas project is no longer open.', 'AbortError');
}
},
+ heldMedia,
getDefaultControlModel: (base) => resolveDefaultControlModelForBase(getModelsSnapshot().models, base),
getMainModelBase: () => {
const project = store.getState().projects.find((candidate) => candidate.id === projectId);
@@ -99,7 +102,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {
mutationPort: createCanvasProjectMutationPort(store, projectId),
reportError: notifications.reportError,
}),
- [fonts, notifications.reportError, persistence, projectId, store]
+ [fonts, heldMedia, notifications.reportError, persistence, projectId, store]
);
return useSyncExternalStore(resource.subscribe, resource.getSnapshot, resource.getSnapshot);
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
index 89a29b85b4..45bd7f520c 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
@@ -76,8 +76,8 @@ const getActiveSectionId = (
? requestedSectionId
: DEFAULT_SECTION_ID;
-const manageIntermediatesOf = (userId: string): void => {
- requestIntermediatesFocus({ ownerId: userId });
+const manageIntermediatesOf = (userId: string, label: string): void => {
+ requestIntermediatesFocus({ ownerId: userId, ownerLabel: label });
openWorkbenchSettings('intermediates');
};
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
index 688e1243ec..88bad8344a 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
@@ -20,7 +20,7 @@ import { useTranslation } from 'react-i18next';
export const ProjectActionsMenuBody = ({
isCompatible,
isPinned,
- onClearIntermediates,
+ onDeleteIntermediates,
onDelete,
onDuplicate,
onExport,
@@ -31,7 +31,7 @@ export const ProjectActionsMenuBody = ({
isCompatible: boolean;
isPinned: boolean;
projectSearch: { project: string };
- onClearIntermediates: () => void;
+ onDeleteIntermediates: () => void;
onDelete: () => void;
onDuplicate: () => void;
onExport: () => void;
@@ -72,9 +72,9 @@ export const ProjectActionsMenuBody = ({
<Icon as={FileDownIcon} boxSize="3.5" />
{t('common.export')}
</Menu.Item>
- <Menu.Item value="intermediates" onClick={onClearIntermediates}>
+ <Menu.Item value="intermediates" onClick={onDeleteIntermediates}>
<Icon as={BrushCleaningIcon} boxSize="3.5" />
- {t('projects.clearIntermediates')}
+ {t('projects.deleteIntermediates')}
</Menu.Item>
<Menu.Separator />
<Menu.Item data-danger="" value="delete" onClick={onDelete}>
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
index 9cbd61f61a..f3dff57a00 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
@@ -209,7 +209,7 @@ const HostedProjectActionsMenu = ({
() => onRequestDialog({ actions, kind: 'rename', name: request.summary.name }),
[actions, onRequestDialog, request.summary.name]
);
- const handleClearIntermediates = useCallback(() => {
+ const handleDeleteIntermediates = useCallback(() => {
// The manager lives in Settings; it reads this intent once when its section mounts.
requestIntermediatesFocus({ projectId: request.summary.id });
openWorkbenchSettings('intermediates', request.returnFocus ?? undefined);
@@ -231,7 +231,7 @@ const HostedProjectActionsMenu = ({
isPinned={request.isPinned}
isCompatible={isCompatible}
projectSearch={projectSearch}
- onClearIntermediates={handleClearIntermediates}
+ onDeleteIntermediates={handleDeleteIntermediates}
onDelete={handleDelete}
onDuplicate={handleDuplicate}
onExport={handleExport}
diff --git a/invokeai/frontend/webv2/src/workbench/mediaReferences.ts b/invokeai/frontend/webv2/src/workbench/mediaReferences.ts
new file mode 100644
index 0000000000..f5b29e1759
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/mediaReferences.ts
@@ -0,0 +1,61 @@
+/** Media names referenced by persisted and in-memory Workbench state, matched by key like the server's extractor. */
+
+/** Keys whose string values name an image; the server's `media_references` extractor uses the same set. */
+export const IMAGE_NAME_KEYS: ReadonlySet<string> = new Set(['imageName', 'image_name']);
+
+/** Keys whose string values name a video; the server's `media_references` extractor uses the same set. */
+export const VIDEO_NAME_KEYS: ReadonlySet<string> = new Set(['videoName', 'video_name', 'source_video_name']);
+
+/** Server-side names are generated filenames; the cleanup index ignores anything longer. */
+export const MAX_HELD_NAME_LENGTH = 255;
+
+export interface MediaNameRefs {
+ images: Set<string>;
+ videos: Set<string>;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** Every name under a media-name key, at any depth, except subtrees whose key `skipKey` rejects. */
+export const collectMediaNames = (
+ roots: readonly unknown[],
+ skipKey: (key: string) => boolean,
+ maxLength = Number.POSITIVE_INFINITY
+): MediaNameRefs => {
+ const refs: MediaNameRefs = { images: new Set<string>(), videos: new Set<string>() };
+ const pending = [...roots];
+ while (pending.length > 0) {
+ const node = pending.pop();
+ if (Array.isArray(node)) {
+ for (const item of node) {
+ pending.push(item);
+ }
+ continue;
+ }
+ if (!isRecord(node)) {
+ continue;
+ }
+ for (const [key, value] of Object.entries(node)) {
+ if (skipKey(key)) {
+ continue;
+ }
+ if (typeof value === 'string') {
+ if (value !== '' && value.length <= maxLength) {
+ if (IMAGE_NAME_KEYS.has(key)) {
+ refs.images.add(value);
+ } else if (VIDEO_NAME_KEYS.has(key)) {
+ refs.videos.add(value);
+ }
+ }
+ } else if (typeof value === 'object' && value !== null) {
+ pending.push(value);
+ }
+ }
+ }
+ return refs;
+};
+
+/** Every media name in `values`, history included: what an undo entry can restore. */
+export const collectRestorableAssetRefs = (...values: unknown[]): MediaNameRefs =>
+ collectMediaNames(values, () => false, MAX_HELD_NAME_LENGTH);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.md
index 5a6b0792ba..1fa5cc4e8f 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/README.md
+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md
@@ -4,7 +4,7 @@ The backend project record is authoritative. Writes use `expected_revision`; a d
`ProjectDocumentV2` allowlists editable document fields. Queue runs, events, graph history, and undo are not project documents. Documents are limited to 32 MiB of UTF-8 JSON on both sides of the API. The workflow library is the durable home for saved workflows; undo and capped events are session-only.
-Canvas uploads carrying a project id await that identity’s acknowledged server creation through the mounted persistence service. Concurrent initial uploads share its serialized creation; later uploads use the acknowledged identity without flushing unrelated edits. Failed creation, project deletion, account changes, and engine disposal prevent the upload from proceeding.
+Canvas uploads carrying a project id await that identity’s acknowledged server creation through the mounted persistence service. Uploads waiting on an unacknowledged project share one serialized creation attempt, and a failed attempt answers further uploads for a few seconds before another is made; later uploads use the acknowledged identity without flushing unrelated edits. Only a closed project, an account change, engine disposal or the operation's own cancellation stops an upload, and those stop the wait immediately. Any other outcome (creation failed or offline, a conflict, or a server that no longer knows the project and refuses the id) sends the upload without a project id. Such uploads are never re-associated with the project later, so the project's intermediates cleanup does not see them.
Project links are consumed after a successful open, so reloading restores the saved active project rather than replaying an earlier link. A new-project startup selects the newly created draft before saving the session.
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index 79bb5fb290..7a8616f8cb 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -228,15 +228,33 @@ describe('durable project persistence', () => {
await rejected;
});
- it('requires a successful acknowledgement after an initial project creation failure', async () => {
+ it('shares one failed creation across waiting and following uploads, then retries after a pause', async () => {
const api = createApi();
const project = createDraftProject([]);
const service = createService(captureAccountScope(), api);
- vi.mocked(api.createProject).mockRejectedValueOnce(new Error('offline'));
-
- await expect(service.ensureProjectOnServer(project)).rejects.toMatchObject({ reason: 'unsynced' });
- await service.ensureProjectOnServer(project);
- expect(api.createProject).toHaveBeenCalledTimes(2);
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ let fail!: (error: Error) => void;
+ vi.mocked(api.createProject).mockReturnValueOnce(
+ new Promise((_resolve, reject) => {
+ fail = reject;
+ })
+ );
+ try {
+ const waiting = [service.ensureProjectOnServer(project), service.ensureProjectOnServer(project)];
+ await vi.waitFor(() => expect(api.createProject).toHaveBeenCalledOnce());
+ fail(new Error('offline'));
+ for (const upload of waiting) {
+ await expect(upload).rejects.toMatchObject({ reason: 'unsynced' });
+ }
+ await expect(service.ensureProjectOnServer(project)).rejects.toMatchObject({ reason: 'unsynced' });
+ expect(api.createProject).toHaveBeenCalledOnce();
+
+ clock.mockReturnValue(10_000);
+ await service.ensureProjectOnServer(project);
+ expect(api.createProject).toHaveBeenCalledTimes(2);
+ } finally {
+ clock.mockRestore();
+ }
});
it('rejects deleted projects and expired accounts even after their creation was acknowledged', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
index 4796dd7f0f..ade2a6a7b9 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
@@ -109,6 +109,9 @@ export interface SaveDraftAsNewInput {
export type SaveDraftAsNew = (input: SaveDraftAsNewInput) => Promise<ProjectRecordDTO>;
+/** How long a failed upload-provenance creation answers later uploads before another attempt is made. */
+const PROJECT_ENSURE_FAILURE_REUSE_MS = 5_000;
+
const saveDraftAsNew: SaveDraftAsNew = (input) => {
return createProjectSettled(
{
@@ -467,6 +470,8 @@ export const createDurableSyncedWorkbenchPersistence = (
const deleteDatabase = dependencies.deleteDatabase ?? deleteWorkbenchDatabase;
const databaseDeleteTimeoutMs = dependencies.databaseDeleteTimeoutMs ?? 5_000;
const syncEntries = new Map<string, SyncEntry>();
+ const projectEnsures = new Map<string, Promise<void>>();
+ const projectEnsureFailures = new Map<string, { at: number; error: unknown }>();
const conflicts = new Map<string, ProjectConflictInfo>();
const schemaRefusals = new Map<string, ProjectSchemaRefusal>();
const generations = new Map<string, number>();
@@ -1886,13 +1891,36 @@ export const createDurableSyncedWorkbenchPersistence = (
if (syncEntries.has(project.id)) {
return Promise.resolve().then(assertProjectIdentityCurrent);
}
- return enqueue(async () => {
- assertProjectIdentityCurrent();
- if (!syncEntries.has(project.id)) {
- assertProjectFlushed(await pushProject(project));
- }
- assertProjectIdentityCurrent();
- });
+ // Uploads share one creation attempt, and fall back at once while a recent attempt's failure is fresh.
+ const failure = projectEnsureFailures.get(project.id);
+ if (failure && Date.now() - failure.at < PROJECT_ENSURE_FAILURE_REUSE_MS) {
+ return Promise.resolve().then(() => {
+ assertProjectIdentityCurrent();
+ throw failure.error;
+ });
+ }
+ projectEnsureFailures.delete(project.id);
+ let ensure = projectEnsures.get(project.id);
+ if (!ensure) {
+ ensure = enqueue(async () => {
+ assertProjectIdentityCurrent();
+ if (!syncEntries.has(project.id)) {
+ assertProjectFlushed(await pushProject(project));
+ }
+ }).then(
+ () => {
+ projectEnsures.delete(project.id);
+ projectEnsureFailures.delete(project.id);
+ },
+ (error: unknown) => {
+ projectEnsures.delete(project.id);
+ projectEnsureFailures.set(project.id, { at: Date.now(), error });
+ throw error;
+ }
+ );
+ projectEnsures.set(project.id, ensure);
+ }
+ return ensure.then(assertProjectIdentityCurrent);
},
flushProjectToServer: (project) => {
if (isTerminallyCleared) {
@@ -2750,6 +2778,7 @@ export const createDurableSyncedWorkbenchPersistence = (
});
},
releaseProjectSync: (projectId) => {
+ projectEnsureFailures.delete(projectId);
if ([...pendingRetargetHandoffs.values()].some((handoff) => handoff.targetProjectId === projectId)) {
closedRetargetTargetsAwaitingAck.add(projectId);
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
index 28df817ebe..2cd847ca32 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
@@ -1,8 +1,9 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
collectHeldAssetRefs,
collectLiveAssetRefs,
+ createCanvasHeldMediaSources,
createOpenProjectsHeldMediaReader,
remapAssetRefs,
selectCoverImageName,
@@ -67,6 +68,59 @@ it('holds names Canvas undo retains after the project stops naming them, and dro
expect(read()).toEqual({ images: [], videos: [] });
});
+it('keeps the held result while edits touch only name-free subtrees, and sees names nested edits add', () => {
+ const document = { stacks: { raster: [{ source: { image: { imageName: 'layer.png' } } }] } };
+ const undoEntry = { project: { widgetInstances: { w: { imageName: 'undo.png' } } } };
+ let project = {
+ canvas: { document, snapshots: [{ document: { imageName: 'snapshot.png' } }] },
+ id: 'project-1',
+ layout: { size: 1 },
+ undoRedo: { future: [], past: [undoEntry] },
+ };
+ const read = createOpenProjectsHeldMediaReader(
+ () => [project],
+ () => undefined
+ );
+ const first = read();
+ expect(new Set(first.images)).toEqual(new Set(['layer.png', 'snapshot.png', 'undo.png']));
+
+ project = { ...project, layout: { size: 2 } };
+ expect(read()).toBe(first);
+ project = { ...project, canvas: { ...project.canvas, document: { ...document } } };
+ const rescanned = read();
+ expect(new Set(rescanned.images)).toEqual(new Set(first.images));
+ expect(read()).toBe(rescanned);
+
+ project = {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ document: { stacks: { raster: [{ source: { image: { imageName: 'stroke.png' } } }] } },
+ },
+ undoRedo: { future: [], past: [undoEntry, { project: { widgetInstances: { w: { imageName: 'next.png' } } } }] },
+ };
+ expect(new Set(read().images)).toEqual(new Set(['stroke.png', 'snapshot.png', 'undo.png', 'next.png']));
+});
+
+it('announces engines registering and releasing their held media', () => {
+ const sources = createCanvasHeldMediaSources();
+ const onChange = vi.fn();
+ sources.subscribe(onChange);
+ let notifyEngine = () => undefined as void;
+ const release = sources.register('project-1', {
+ read: () => ({ images: ['undo.png'], videos: [] }),
+ subscribe: (listener) => {
+ notifyEngine = listener;
+ return () => undefined;
+ },
+ });
+ expect(sources.read('project-1')).toEqual({ images: ['undo.png'], videos: [] });
+ notifyEngine();
+ release();
+ expect(sources.read('project-1')).toBeUndefined();
+ expect(onChange).toHaveBeenCalledTimes(3);
+});
+
const projectDocument = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
canvas: {
document: { stacks: { raster: [imageLayer('layer-1', 'live-image.png')] }, version: 3 },
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index 0f4bd9206c..a4818dffe5 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -3,14 +3,13 @@
* includes it.
*/
-/** Keys whose string values name an image; the server's `media_references` extractor uses the same set. */
-const IMAGE_NAME_KEYS: ReadonlySet<string> = new Set(['imageName', 'image_name']);
-
-/** Keys whose string values name a video; the server's `media_references` extractor uses the same set. */
-const VIDEO_NAME_KEYS: ReadonlySet<string> = new Set(['videoName', 'video_name']);
-
-/** Server-side names are generated filenames; the cleanup index ignores anything longer. */
-const MAX_HELD_NAME_LENGTH = 255;
+import {
+ collectMediaNames,
+ IMAGE_NAME_KEYS,
+ MAX_HELD_NAME_LENGTH,
+ type MediaNameRefs,
+ VIDEO_NAME_KEYS,
+} from '@workbench/mediaReferences';
/** Top-level document keys that are history rather than live content. */
export const PROJECT_HISTORY_ROOT_KEYS: ReadonlySet<string> = new Set(['events', 'graphHistory', 'queue']);
@@ -41,69 +40,54 @@ const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([
/** Blank cached URLs instead of deleting keys, preserving entries while forcing URL derivation from remapped names. */
const DERIVED_URL_KEYS: ReadonlySet<string> = new Set(['imageUrl', 'thumbnailUrl', 'videoUrl']);
-export interface ProjectAssetRefs {
- images: Set<string>;
- videos: Set<string>;
+export type ProjectAssetRefs = MediaNameRefs;
+
+export interface CanvasHeldAssetRefs {
+ readonly images: readonly string[];
+ readonly videos: readonly string[];
}
-type CanvasHeldAssetRefs = { images: readonly string[]; videos: readonly string[] };
-const canvasHeldAssetReaders = new Map<string, () => CanvasHeldAssetRefs>();
+/** What a live Canvas engine's undo state retains, and when that changes. */
+export interface CanvasHeldMediaSource {
+ read(): CanvasHeldAssetRefs;
+ subscribe(listener: () => void): () => void;
+}
-/** Canvas owns each reader for as long as its engine remains alive. */
-export const registerCanvasHeldAssetRefs = (projectId: string, read: () => CanvasHeldAssetRefs): (() => void) => {
- canvasHeldAssetReaders.set(projectId, read);
- return () => {
- if (canvasHeldAssetReaders.get(projectId) === read) {
- canvasHeldAssetReaders.delete(projectId);
- }
+/** One mounted Workbench's live Canvas engines, each registered for as long as its undo state survives. */
+export interface CanvasHeldMediaSources {
+ read(projectId: string): CanvasHeldAssetRefs | undefined;
+ register(projectId: string, source: CanvasHeldMediaSource): () => void;
+ subscribe(listener: () => void): () => void;
+}
+
+export const createCanvasHeldMediaSources = (): CanvasHeldMediaSources => {
+ const sources = new Map<string, CanvasHeldMediaSource>();
+ const listeners = new Set<() => void>();
+ const notify = (): void => listeners.forEach((listener) => listener());
+ return {
+ read: (projectId) => sources.get(projectId)?.read(),
+ register: (projectId, source) => {
+ sources.set(projectId, source);
+ const unsubscribe = source.subscribe(notify);
+ notify();
+ return () => {
+ unsubscribe();
+ if (sources.get(projectId) === source) {
+ sources.delete(projectId);
+ notify();
+ }
+ };
+ },
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
};
};
-export const getCanvasHeldAssetRefs = (projectId: string): CanvasHeldAssetRefs | undefined =>
- canvasHeldAssetReaders.get(projectId)?.();
-
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
-/** Every name under a media-name key, at any depth, except subtrees whose key `skipKey` rejects. */
-const collectMediaNames = (
- roots: readonly unknown[],
- skipKey: (key: string) => boolean,
- maxLength = Number.POSITIVE_INFINITY
-): ProjectAssetRefs => {
- const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };
- const pending = [...roots];
- while (pending.length > 0) {
- const node = pending.pop();
- if (Array.isArray(node)) {
- for (const item of node) {
- pending.push(item);
- }
- continue;
- }
- if (!isRecord(node)) {
- continue;
- }
- for (const [key, value] of Object.entries(node)) {
- if (skipKey(key)) {
- continue;
- }
- if (typeof value === 'string') {
- if (value !== '' && value.length <= maxLength) {
- if (IMAGE_NAME_KEYS.has(key)) {
- refs.images.add(value);
- } else if (VIDEO_NAME_KEYS.has(key)) {
- refs.videos.add(value);
- }
- }
- } else if (typeof value === 'object' && value !== null) {
- pending.push(value);
- }
- }
- }
- return refs;
-};
-
const withoutHistoryRoots = (projectDocument: object): unknown[] =>
Object.entries(projectDocument).flatMap(([key, value]) => (PROJECT_HISTORY_ROOT_KEYS.has(key) ? [] : [value]));
@@ -113,50 +97,92 @@ export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>):
(key) => PROJECT_HISTORY_KEYS.has(key) || GALLERY_SELECTION_KEYS.has(key)
);
+const isHeldSkipKey = (key: string): boolean => key === 'recentImages' || GALLERY_SELECTION_KEYS.has(key);
+
/** Open editors hold live content and undo state, but not completed queue/event or gallery history. */
export const collectHeldAssetRefs = (projects: readonly object[]): ProjectAssetRefs =>
- collectMediaNames(
- projects.flatMap(withoutHistoryRoots),
- (key) => key === 'recentImages' || GALLERY_SELECTION_KEYS.has(key),
- MAX_HELD_NAME_LENGTH
- );
+ collectMediaNames(projects.flatMap(withoutHistoryRoots), isHeldSkipKey, MAX_HELD_NAME_LENGTH);
+
+/** Containers whose children an edit replaces independently: the canvas, its snapshots and undo stacks. */
+const SPLIT_HELD_KEYS: ReadonlySet<string> = new Set(['canvas', 'snapshots', 'undoRedo', 'past', 'future']);
-/** Every media name in `values`, history included: what an undo entry can restore. */
-export const collectRestorableAssetRefs = (...values: unknown[]): ProjectAssetRefs =>
- collectMediaNames(values, () => false, MAX_HELD_NAME_LENGTH);
+type HeldPart = ProjectAssetRefs | CanvasHeldAssetRefs;
+
+const scanHeld = (node: object): ProjectAssetRefs => collectMediaNames([node], isHeldSkipKey, MAX_HELD_NAME_LENGTH);
+
+// Edits that replace name-free subtrees (the project root, layout, settings) then leave the parts unchanged.
+const pushNamed = (refs: ProjectAssetRefs, parts: HeldPart[]): void => {
+ if (refs.images.size || refs.videos.size) {
+ parts.push(refs);
+ }
+};
/**
- * Reads what open editors hold: each project's live content plus the undo state its Canvas engine retains. Project
- * snapshots are immutable, so a project's scan is reused until its object changes.
+ * Reads what open editors hold: each project's live content plus the undo state its Canvas engine retains. Edits
+ * replace the canvas, its snapshots and undo stacks child by child, so the project is split there; every other subtree
+ * is immutable and scanned once per identity, as are the primitive fields of each split node. When no part changed
+ * identity the previous result is returned as is; equal name sets under new identities are left to the lease.
*/
export const createOpenProjectsHeldMediaReader = (
getProjects: () => readonly (object & { id: string })[],
- getCanvasRefs: (projectId: string) => CanvasHeldAssetRefs | undefined = getCanvasHeldAssetRefs
+ getCanvasRefs: (projectId: string) => CanvasHeldAssetRefs | undefined
): (() => { images: string[]; videos: string[] }) => {
- const scans = new Map<string, { project: object; refs: ProjectAssetRefs }>();
+ const scans = new WeakMap<object, ProjectAssetRefs>();
+ const residueScans = new WeakMap<object, ProjectAssetRefs>();
+ let last: { parts: HeldPart[]; result: { images: string[]; videos: string[] } } | null = null;
+
+ const collectParts = (node: object, isRoot: boolean, parts: HeldPart[]): void => {
+ const entries = Array.isArray(node)
+ ? node.map((value, index) => [String(index), value] as const)
+ : Object.entries(node);
+ let residue: Record<string, unknown> | null = null;
+ for (const [key, value] of entries) {
+ if (isHeldSkipKey(key) || (isRoot && PROJECT_HISTORY_ROOT_KEYS.has(key))) {
+ continue;
+ }
+ if (typeof value !== 'object' || value === null) {
+ (residue ??= {})[key] = value;
+ } else if (SPLIT_HELD_KEYS.has(key)) {
+ collectParts(value, false, parts);
+ } else {
+ let refs = scans.get(value);
+ if (!refs) {
+ refs = scanHeld(value);
+ scans.set(value, refs);
+ }
+ pushNamed(refs, parts);
+ }
+ }
+ if (residue) {
+ let refs = residueScans.get(node);
+ if (!refs) {
+ refs = scanHeld(residue);
+ residueScans.set(node, refs);
+ }
+ pushNamed(refs, parts);
+ }
+ };
+
return () => {
- const images = new Set<string>();
- const videos = new Set<string>();
- const open = new Set<string>();
+ const parts: HeldPart[] = [];
for (const project of getProjects()) {
- open.add(project.id);
- let scan = scans.get(project.id);
- if (scan?.project !== project) {
- scan = { project, refs: collectHeldAssetRefs([project]) };
- scans.set(project.id, scan);
- }
- scan.refs.images.forEach((name) => images.add(name));
- scan.refs.videos.forEach((name) => videos.add(name));
+ collectParts(project, true, parts);
const retained = getCanvasRefs(project.id);
- retained?.images.forEach((name) => images.add(name));
- retained?.videos.forEach((name) => videos.add(name));
- }
- for (const projectId of scans.keys()) {
- if (!open.has(projectId)) {
- scans.delete(projectId);
+ if (retained) {
+ parts.push(retained);
}
}
- return { images: [...images], videos: [...videos] };
+ if (last && last.parts.length === parts.length && parts.every((part, index) => part === last!.parts[index])) {
+ return last.result;
+ }
+ const images = new Set<string>();
+ const videos = new Set<string>();
+ for (const part of parts) {
+ part.images.forEach((name) => images.add(name));
+ part.videos.forEach((name) => videos.add(name));
+ }
+ last = { parts, result: { images: [...images], videos: [...videos] } };
+ return last.result;
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
index 364801838d..f3109b44bf 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
@@ -8,6 +8,7 @@ import { useScopedAction } from '@platform/react/useScopedAction';
import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, Field } from '@platform/ui';
+import { RemovableTag } from '@platform/ui/RemovableTag';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { imageMapStore, refreshImageIndexStatus } from '@workbench/image-map/imageMapStore';
import { describeIndexProgress, isIndexing } from '@workbench/image-map/indexProgress';
@@ -213,25 +214,26 @@ export const ImageMapVocabularySettings = () => {
)}
{vocab.terms.length > 0 ? (
<Wrap gap="1">
- {vocab.terms.map((term) => (
- <Tag.Root key={term} size="sm" variant="surface">
- <Tag.Label>{term}</Tag.Label>
- {canManageImageMapVocabulary ? (
- <Tag.EndElement>
- <Tag.CloseTrigger
- aria-label={t('settings.imageMapVocabulary.removeTerm', { term })}
- // Disabled while a save is in flight: the busy guard would
- // silently drop a second removal, resurrecting the chip
- // with no feedback.
- disabled={isSaving}
- onClick={() => {
- void persist(vocab.terms.filter((existing) => existing !== term));
- }}
- />
- </Tag.EndElement>
- ) : null}
- </Tag.Root>
- ))}
+ {vocab.terms.map((term) =>
+ canManageImageMapVocabulary ? (
+ <RemovableTag
+ key={term}
+ // Disabled while a save is in flight: the busy guard would silently drop a second removal,
+ // resurrecting the chip with no feedback.
+ disabled={isSaving}
+ removeLabel={t('settings.imageMapVocabulary.removeTerm', { term })}
+ onRemove={() => {
+ void persist(vocab.terms.filter((existing) => existing !== term));
+ }}
+ >
+ {term}
+ </RemovableTag>
+ ) : (
+ <Tag.Root key={term} size="sm" variant="surface">
+ <Tag.Label>{term}</Tag.Label>
+ </Tag.Root>
+ )
+ )}
</Wrap>
) : (
<Text color="fg.muted" fontSize="2xs">
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 05e61bed95..7ff8b119a1 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -50,6 +50,7 @@ const ROUTE_SHARED_MODULES = [
'/workbench/launchpad/formatRelativeTime.ts',
// Without this the editor pulls the whole Launchpad chunk for one lookup table.
'/workbench/launchpad/intents.ts',
+ '/workbench/mediaReferences.ts',
'/workbench/palette/settingsEntryDeps.ts',
'/workbench/projects/covers.ts',
'/workbench/projects/components/ProjectFileOptionsProvider.tsx',
@@ -189,6 +190,7 @@ const getLegacyChunkName = (id: string): string | null => {
if (
matchesAnySuffix(id, [
'/platform/i18n/client.ts',
+ '/platform/i18n/languages.ts',
'/platform/react/useMountEffect.ts',
'/platform/ui/theme/system.ts',
'/workbench/hotkeys/resolve.ts',
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index fb96d97585..a54b24154c 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -235,6 +235,7 @@ def mock_services(image_index_service: FakeImageIndexService, tmp_path: Path) ->
gallery=None, # type: ignore
image_index_records=(index_records := ImageIndexRecordsSqlite(db=db)),
image_index=image_index_service,
+ intermediates=None, # type: ignore
external_generation=None, # type: ignore
)
image_index_service.index_records = index_records
diff --git a/tests/app/routers/test_image_moves.py b/tests/app/routers/test_image_moves.py
index 4dbff168e2..f753c95fb2 100644
--- a/tests/app/routers/test_image_moves.py
+++ b/tests/app/routers/test_image_moves.py
@@ -92,6 +92,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
image_moves=image_moves,
system_prompt_records=None, # type: ignore
)
diff --git a/tests/app/routers/test_intermediates.py b/tests/app/routers/test_intermediates.py
index 904020ea7c..18373a4e23 100644
--- a/tests/app/routers/test_intermediates.py
+++ b/tests/app/routers/test_intermediates.py
@@ -224,6 +224,22 @@ def test_hold_is_account_scoped_at_the_http_boundary(
assert summary["items"][0]["images"]["active"] == 1
+def test_hold_lease_ids_name_one_editor_and_an_optional_part(
+ storage_ready: None, client: TestClient, user1_token: str
+) -> None:
+ for lease_id in ("tab.0-0", "tab"):
+ assert (
+ client.put(f"/api/v1/intermediates/holds/{lease_id}", json={}, headers=_auth(user1_token)).status_code
+ == 204
+ )
+ for lease_id in (".0-0", "tab x", "tab/.."):
+ assert (
+ client.put(f"/api/v1/intermediates/holds/{lease_id}", json={}, headers=_auth(user1_token)).status_code
+ != 204
+ ), lease_id
+ assert client.delete(f"/api/v1/intermediates/holds/{lease_id}", headers=_auth(user1_token)).status_code != 204
+
+
def test_legacy_clear_keeps_its_shape_and_the_safety_policy(
storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str, admin_token: str
) -> None:
diff --git a/tests/app/routers/test_media_upload_provenance.py b/tests/app/routers/test_media_upload_provenance.py
index 7c8db27cb0..3e50149472 100644
--- a/tests/app/routers/test_media_upload_provenance.py
+++ b/tests/app/routers/test_media_upload_provenance.py
@@ -86,6 +86,8 @@ def test_image_upload_refuses_a_project_the_caller_does_not_own(
headers=_auth(token),
)
assert response.status_code == 404, response.text
+ # The webv2 upload fallback matches this exact detail.
+ assert response.json()["detail"] == "Project not found"
mock_invoker.services.images.create.assert_not_called()
diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.py
index 6f0e9741de..52e0673bba 100644
--- a/tests/app/routers/test_multiuser_authorization.py
+++ b/tests/app/routers/test_multiuser_authorization.py
@@ -23,7 +23,7 @@ from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.project_records.project_records_sqlite import ProjectRecordsSqlite
-from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
+from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem, SessionQueueItemSummary
from invokeai.app.services.users.users_common import UserCreateRequest
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
from invokeai.backend.util.logging import InvokeAILogger
@@ -146,6 +146,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
@@ -1973,6 +1974,7 @@ class TestSessionQueueSanitization:
completed_at=None,
queue_id="default",
user_id="owner-user",
+ project_id="owner-project",
user_display_name="Owner Display",
user_email="[email protected]",
field_values=None,
@@ -2024,6 +2026,7 @@ class TestSessionQueueSanitization:
assert result.user_id == "redacted"
assert result.user_display_name is None
assert result.user_email is None
+ assert result.project_id is None
# Stripped: generation metadata
assert result.batch_id == "redacted"
@@ -2037,6 +2040,24 @@ class TestSessionQueueSanitization:
assert result.session.id == "redacted"
assert len(result.session.graph.nodes) == 0
+ @pytest.mark.parametrize("model", [SessionQueueItem, SessionQueueItemSummary])
+ def test_every_queue_item_field_is_redacted_or_deliberately_public(self, model: type):
+ from invokeai.app.api.routers.session_queue import _REDACTIONS
+
+ # A field added to either projection must choose a side here, or it leaks to other accounts.
+ public = {
+ "item_id",
+ "queue_id",
+ "status",
+ "status_sequence",
+ "device",
+ "created_at",
+ "updated_at",
+ "started_at",
+ "completed_at",
+ }
+ assert set(model.model_fields) - public - set(_REDACTIONS) == set()
+
def test_sanitization_does_not_mutate_original(self, _sample_queue_item: SessionQueueItem):
from invokeai.app.api.routers.session_queue import sanitize_queue_item_for_user
diff --git a/tests/app/routers/test_privilege_revocation.py b/tests/app/routers/test_privilege_revocation.py
index 1a43e77292..5eaaa8ce90 100644
--- a/tests/app/routers/test_privilege_revocation.py
+++ b/tests/app/routers/test_privilege_revocation.py
@@ -115,6 +115,7 @@ def mock_services() -> InvocationServices:
project_records=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
diff --git a/tests/app/routers/test_session_queue_workflow_call.py b/tests/app/routers/test_session_queue_workflow_call.py
index c88cbedef9..d3da2fe19d 100644
--- a/tests/app/routers/test_session_queue_workflow_call.py
+++ b/tests/app/routers/test_session_queue_workflow_call.py
@@ -107,6 +107,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
diff --git a/tests/app/routers/test_system_prompts_multiuser.py b/tests/app/routers/test_system_prompts_multiuser.py
index 18e188242f..f708572e46 100644
--- a/tests/app/routers/test_system_prompts_multiuser.py
+++ b/tests/app/routers/test_system_prompts_multiuser.py
@@ -108,6 +108,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
diff --git a/tests/app/routers/test_system_prompts_single_user.py b/tests/app/routers/test_system_prompts_single_user.py
index c90b006897..f23c59327d 100644
--- a/tests/app/routers/test_system_prompts_single_user.py
+++ b/tests/app/routers/test_system_prompts_single_user.py
@@ -97,6 +97,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
diff --git a/tests/app/routers/test_workflows_multiuser.py b/tests/app/routers/test_workflows_multiuser.py
index 7f716f8510..c6563d43d1 100644
--- a/tests/app/routers/test_workflows_multiuser.py
+++ b/tests/app/routers/test_workflows_multiuser.py
@@ -124,6 +124,7 @@ def mock_services() -> InvocationServices:
gallery=None, # type: ignore
image_index_records=None, # type: ignore
image_index=None, # type: ignore
+ intermediates=None, # type: ignore
)
diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.py
index 586f46f719..76a24e9f0e 100644
--- a/tests/app/services/intermediates/test_intermediates_service.py
+++ b/tests/app/services/intermediates/test_intermediates_service.py
@@ -629,6 +629,52 @@ def test_a_demoted_admin_stops_at_the_next_batch(
assert sum(_exists(invoker, f"bob-{i}.png") for i in range(3)) == 2
+def test_a_demoted_admin_keeps_media_other_accounts_documents_name_in_its_own_scope(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _seed_image(invoker, "admin-own.png", user_id="admin")
+ invoker.services.workflow_records.create(_workflow_naming("admin-own.png"), user_id="bob")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("admin")), ADMIN)
+ assert preview.impact.delete_images == 1
+ assert [doc.user_id for doc in preview.affected_documents] == ["bob"]
+ real_get = invoker.services.users.get
+
+ def demoted(user_id: str):
+ user = real_get(user_id)
+ return user.model_copy(update={"is_admin": False}) if user is not None and user_id == "admin" else user
+
+ monkeypatch.setattr(invoker.services.users, "get", demoted)
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ADMIN
+ )
+ operation = _wait(service, started.operation_id, ADMIN)
+
+ assert operation.status == "completed"
+ assert operation.progress.retained_images == 1
+ assert _exists(invoker, "admin-own.png")
+
+
+def test_a_retry_by_a_demoted_admin_keeps_media_other_accounts_documents_name(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _seed_image(invoker, "admin-own.png", user_id="admin")
+ invoker.services.workflow_records.create(_workflow_naming("admin-own.png"), user_id="bob")
+ real_delete = invoker.services.images.delete_intermediates_by_names
+ monkeypatch.setattr(
+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))
+ )
+ _, failed = _run(service, ADMIN, _owner("admin"), mode="force")
+ assert failed.progress.unresolved_images == 1
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
+
+ retry = service.retry_operation(failed.operation_id, IntermediatesCaller(user_id="admin", is_admin=False))
+ retried = _wait(service, retry.operation_id, ADMIN)
+
+ assert retried.progress.retained_images == 1
+ assert _exists(invoker, "admin-own.png")
+
+
# ── operations: idempotency, retry, availability ──
@@ -1078,6 +1124,65 @@ def test_force_clear_keeps_a_newly_referenced_target(invoker: Invoker, service:
assert _exists(invoker, "force-race.png")
+def test_an_account_holds_media_for_a_bounded_number_of_editors(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ from invokeai.app.services.intermediates.intermediates_common import (
+ MAX_BROWSER_HOLD_EDITORS_PER_USER,
+ IntermediatesBrowserHoldRequest,
+ )
+
+ _seed_image(invoker, "bobs-held.png", user_id="bob")
+ service.replace_browser_hold(BOB, "bob-tab", IntermediatesBrowserHoldRequest(images=["bobs-held.png"]))
+ # Each editor splits its hold into two leases; the cap counts editors, not leases.
+ for editor in range(MAX_BROWSER_HOLD_EDITORS_PER_USER + 1):
+ for part in range(2):
+ _seed_image(invoker, f"held-{editor}-{part}.png")
+ service.replace_browser_hold(
+ ALICE, f"tab-{editor}.{part}-0", IntermediatesBrowserHoldRequest(images=[f"held-{editor}-{part}.png"])
+ )
+ # Refresh order decides which editor lapses; stagger it so the first editor is the stalest.
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "UPDATE intermediates_browser_holds SET expires_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', ?)"
+ " WHERE user_id = 'alice' AND lease_id LIKE ?;",
+ (f"+{60 + editor} seconds", f"tab-{editor}.%"),
+ )
+
+ alice, operation = _run(service, ALICE, _owner("alice"))
+ assert (alice.impact.keep_active_images, alice.impact.delete_images) == (
+ 2 * MAX_BROWSER_HOLD_EDITORS_PER_USER,
+ 2,
+ )
+ assert operation.progress.deleted_images == 2
+ survivors = {
+ f"held-{editor}-{part}.png"
+ for editor in range(MAX_BROWSER_HOLD_EDITORS_PER_USER + 1)
+ for part in range(2)
+ if _exists(invoker, f"held-{editor}-{part}.png")
+ }
+ assert survivors == {
+ f"held-{editor}-{part}.png" for editor in range(1, MAX_BROWSER_HOLD_EDITORS_PER_USER + 1) for part in range(2)
+ }
+ bob = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), BOB)
+ assert (bob.impact.keep_active_images, bob.impact.delete_images) == (1, 0)
+
+
+def test_force_preview_lists_a_bounded_number_of_broken_documents(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "MAX_AFFECTED_DOCUMENTS", 2)
+ for index in range(3):
+ _seed_image(invoker, f"doc-{index}.png")
+ _project(invoker, "alice", f"Doc {index}", {"imageName": f"doc-{index}.png"})
+
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+
+ assert [doc.name for doc in preview.affected_documents] == ["Doc 0", "Doc 1"]
+ assert preview.affected_documents_total == 3
+ assert preview.impact.delete_images == 3
+
+
def test_browser_hold_protects_unsaved_and_undo_references(invoker: Invoker, service: IntermediatesService) -> None:
from invokeai.app.services.intermediates.intermediates_common import IntermediatesBrowserHoldRequest
@@ -1133,7 +1238,7 @@ def test_operation_receipt_and_retry_survive_restart(
def test_receipt_pruning_keeps_unresolved_targets_retryable(
invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS", 2)
+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 2)
_seed_image(invoker, "flaky.png")
real_delete = invoker.services.images.delete_intermediates_by_names
monkeypatch.setattr(
@@ -1144,37 +1249,150 @@ def test_receipt_pruning_keeps_unresolved_targets_retryable(
monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
# New successful receipts may be pruned; the failed operation's exact target must not be.
+ empty = IntermediatesScope(
+ kind="selection",
+ targets=[IntermediatesScopeTarget(user_id="alice", project_id=_project(invoker, "alice", "E", {}))],
+ )
+ _, oldest_settled = _run(service, ALICE, empty)
for _ in range(2):
- _run(service, ADMIN, _owner("bob"))
+ _run(service, ALICE, empty)
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ service.get_operation(oldest_settled.operation_id, ALICE)
assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1
retry = service.retry_operation(failed.operation_id, ALICE)
assert _wait(service, retry.operation_id).progress.deleted_images == 1
-def test_recovery_capacity_refuses_new_work_but_allows_the_unresolved_retry(
+def test_pruning_another_accounts_retry_prunes_the_operation_it_retried(
invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS", 1)
+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 2)
_seed_image(invoker, "flaky.png")
real_delete = invoker.services.images.delete_intermediates_by_names
monkeypatch.setattr(
invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))
)
_, failed = _run(service, ALICE, _owner("alice"))
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
+ retry = service.retry_operation(failed.operation_id, ADMIN)
+ assert _wait(service, retry.operation_id, ADMIN).progress.deleted_images == 1
+
+ # The admin's later cleanups push its retry out of its budget; Alice's original goes with it
+ # rather than pointing at a receipt that no longer exists.
+ for _ in range(3):
+ _run(service, ADMIN, _owner("admin"))
+
+ for operation_id in (retry.operation_id, failed.operation_id):
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ service.get_operation(operation_id, ADMIN)
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ service.retry_operation(failed.operation_id, ALICE)
+
+
+def test_one_account_cannot_fill_the_cleanup_queue(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import threading
+
+ _seed_image(invoker, "alice.png")
+ _seed_image(invoker, "bob.png", user_id="bob")
+ release = threading.Event()
+ real_delete = invoker.services.images.delete_intermediates_by_names
+
+ def blocked_delete(names, guard=None):
+ release.wait(10)
+ return real_delete(names, guard)
+
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", blocked_delete)
+
+ def start(caller: IntermediatesCaller) -> IntermediatesOperation:
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner(caller.user_id)), caller)
+ return service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=uuid.uuid4().hex), caller
+ )
+
+ try:
+ started = [start(ALICE) for _ in range(intermediates_default.MAX_ACTIVE_OPERATIONS_PER_CALLER)]
+ with pytest.raises(IntermediatesUnavailableError, match="your running deletions"):
+ start(ALICE)
+ started.append(start(BOB))
+ finally:
+ release.set()
+ for operation in started:
+ assert _wait(service, operation.operation_id, ADMIN).status == "completed"
+ assert not _exists(invoker, "alice.png") and not _exists(invoker, "bob.png")
+
+
+def test_a_preview_classifies_its_counts_and_targets_at_one_instant(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from datetime import datetime, timedelta, timezone
+
+ from invokeai.app.services.intermediates import intermediates_records_sqlite
+ from invokeai.app.services.intermediates.intermediates_common import RECENT_GRACE_SECONDS
+
+ start = datetime(2030, 1, 1, tzinfo=timezone.utc)
+ readings = iter([start] + [start + timedelta(hours=1)] * 100)
+ monkeypatch.setattr(intermediates_records_sqlite, "_utc_now", lambda: next(readings))
+ crossing = start - timedelta(seconds=RECENT_GRACE_SECONDS - 1)
+ _seed_image(invoker, "crossing.png", created_at=crossing.strftime("%Y-%m-%d %H:%M:%S.000"))
+
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+
+ # Still inside the grace window at the preview's single instant; an hour later it would be safe.
+ assert (preview.impact.keep_recent_images, preview.impact.delete_images) == (1, 0)
+
+
+def test_unresolved_work_blocks_only_its_own_accounts_new_cleanups(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 1)
+ _seed_image(invoker, "flaky.png")
+ _seed_image(invoker, "bobs.png", user_id="bob")
+ real_delete = invoker.services.images.delete_intermediates_by_names
+ monkeypatch.setattr(
+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))
+ )
+ _, failed = _run(service, ALICE, _owner("alice"))
assert failed.progress.unresolved_images == 1
monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
- preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), ADMIN)
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
with pytest.raises(IntermediatesUnavailableError, match="Retry unresolved"):
service.start_operation(
- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="another"), ADMIN
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="another"), ALICE
)
+ _, bobs = _run(service, BOB, _owner("bob"))
+ assert bobs.progress.deleted_images == 1
+
assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1
retry = service.retry_operation(failed.operation_id, ALICE)
assert _wait(service, retry.operation_id).progress.deleted_images == 1
+def test_an_unreadable_operation_receipt_does_not_stop_startup(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "a.png")
+ _, finished = _run(service, ALICE, _owner("alice"))
+ service.stop()
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.executemany(
+ "INSERT INTO intermediates_operations (operation_id, caller_user_id, state_json, created_at)"
+ " VALUES (?, 'alice', ?, '2020-01-01T00:00:00Z');",
+ [("not-json", "{truncated"), ("not-a-receipt", '{"dto": {}}')],
+ )
+
+ restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))
+ invoker.services.intermediates = restored
+ restored.start(invoker)
+ try:
+ assert restored.get_operation(finished.operation_id, ALICE).status == "completed"
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ restored.get_operation("not-json", ALICE)
+ finally:
+ restored.stop()
+
+
def test_force_confirmation_guard_survives_failed_batch_and_restart(
invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -1532,7 +1750,7 @@ def test_child_protection_does_not_scan_unrelated_completed_history(
db._conn.set_progress_handler(count_instructions, 100)
try:
- candidates = service._records.list_candidates("image", user_id="alice", targets=None)
+ candidates, _ = service._records.page_intermediates("image", after_rowid=0, limit=10)
assert [(item.name, item.classification) for item in candidates] == [("produced.png", "active")]
return instructions
finally:
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py
index 260ca46f32..4279a17b4f 100644
--- a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py
@@ -32,7 +32,8 @@ def cursor() -> sqlite3.Cursor:
)
connection.execute(
"CREATE TABLE workflow_library (workflow_id TEXT NOT NULL PRIMARY KEY, workflow TEXT NOT NULL,"
- " user_id TEXT DEFAULT 'system');"
+ " user_id TEXT DEFAULT 'system',"
+ " category TEXT GENERATED ALWAYS AS (json_extract(workflow, '$.meta.category')) VIRTUAL NOT NULL);"
)
return connection.cursor()
@@ -82,10 +83,16 @@ def test_backfills_references_from_projects_and_workflows(cursor: sqlite3.Cursor
"video": {"clips": [{"video_name": "clip.mp4"}]},
"unrelated": {"imageName": "", "name": "not-a-ref.png"},
}
- workflow = {"nodes": [{"data": {"inputs": {"image": {"value": {"image_name": "input.png"}}}}}]}
+ workflow = {
+ "meta": {"category": "user"},
+ "nodes": [{"data": {"inputs": {"image": {"value": {"image_name": "input.png"}}}}}],
+ }
+ default_workflow = {"meta": {"category": "default"}, "nodes": [{"data": {"image_name": "bundled.png"}}]}
cursor.execute("INSERT INTO projects VALUES ('p1', 'u1', ?);", (json.dumps(project),))
cursor.execute("INSERT INTO projects VALUES ('p2', 'u2', 'not json');")
cursor.execute("INSERT INTO workflow_library VALUES ('w1', ?, 'u1');", (json.dumps(workflow),))
+ # Default workflows are synced from bundled files; runtime never indexes them, so neither does the backfill.
+ cursor.execute("INSERT INTO workflow_library VALUES ('d1', ?, 'system');", (json.dumps(default_workflow),))
_run(cursor)
diff --git a/tests/app/services/shared/test_media_references.py b/tests/app/services/shared/test_media_references.py
index 9043bc56f3..43ca396862 100644
--- a/tests/app/services/shared/test_media_references.py
+++ b/tests/app/services/shared/test_media_references.py
@@ -18,13 +18,14 @@ def test_collects_names_under_image_and_video_keys_at_any_depth() -> None:
"layers": [{"image": {"image_name": "layer.png"}}, {"reference": {"imageName": "ref.png"}}],
"queue": {"items": [{"outputs": [{"imageName": "staged.png"}, {"videoName": "clip.mp4"}]}]},
"video": {"video_name": "source.mp4", "poster": {"image_name": "poster.png"}},
+ "soundtrack": {"source_video_name": "soundtrack-source.mp4"},
"ignored": {"name": "not-a-ref.png", "image_name": "", "video_name": "x" * 300, "imageName": 12},
}
references = extract_media_references(document)
assert references.images == {"layer.png", "ref.png", "staged.png", "poster.png"}
- assert references.videos == {"clip.mp4", "source.mp4"}
+ assert references.videos == {"clip.mp4", "source.mp4", "soundtrack-source.mp4"}
def test_non_object_documents_reference_nothing() -> None:
diff --git a/tests/app/services/test_image_move_startup_safety.py b/tests/app/services/test_image_move_startup_safety.py
index 56fe720d0d..bfe848cfa7 100644
--- a/tests/app/services/test_image_move_startup_safety.py
+++ b/tests/app/services/test_image_move_startup_safety.py
@@ -47,6 +47,7 @@ def _services(**overrides):
"gallery": object(),
"image_index_records": object(),
"image_index": object(),
+ "intermediates": object(),
"image_moves": None,
"system_prompt_records": object(),
}