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): make cleanup durable and scope-safe

Josh Corbett165b92ad0017
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdx
index f0525622af..1f7a687f76 100644
--- a/docs/src/content/docs/features/intermediates.mdx
+++ b/docs/src/content/docs/features/intermediates.mdx
@@ -11,7 +11,7 @@ Each row is one of your projects, or **Unassigned** for intermediates without a
Select rows, or **Select all**, and press **Delete**. The confirmation explains why kept items are kept: referenced by a saved project or workflow, used by queued or running work, or created recently.
-Administrators see every account's projects, can search accounts as well as project names, and can filter to one account from the Users page.
+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
@@ -19,16 +19,23 @@ A normal clear deletes only safe items. It always keeps:
- anything a pending, waiting or running job produced or uses as an input;
- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected;
+- anything the open webv2 editor has used, including unsaved edits and canvas undo history; the browser refreshes this temporary hold while it is open;
- anything a saved project or library workflow still names, such as canvas staging candidates or cropped reference images;
- 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. Those projects will show missing images and undo may no longer restore them. Force clearing never touches active or recent work and cannot be undone; it asks for an acknowledgement and for the word `CLEAR` to be typed.
+The advanced option in the confirmation, **also delete items that saved projects or workflows still reference**, turns the delete into a force clear. 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 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.
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. The hold expires one day after the last refresh if the tab closes or crashes. If you have an unsaved browser-only draft that has stayed closed longer than a day, reopen it before clearing 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. Failed items can be retried without widening the original request.
+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.
## Permissions
diff --git a/invokeai/app/api/routers/intermediates.py b/invokeai/app/api/routers/intermediates.py
index 3daf07f576..7b84020da1 100644
--- a/invokeai/app/api/routers/intermediates.py
+++ b/invokeai/app/api/routers/intermediates.py
@@ -2,13 +2,13 @@
from typing import Literal, Optional
-from fastapi import APIRouter, Body, HTTPException, Path, Query, status
+from fastapi import APIRouter, Body, HTTPException, Path, Query, Response, status
from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
-from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller
from invokeai.app.services.intermediates.intermediates_common import (
+ IntermediatesBrowserHoldRequest,
IntermediatesIdempotencyConflictError,
IntermediatesOperation,
IntermediatesOperationNotFoundError,
@@ -27,6 +27,26 @@ 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)
@@ -49,6 +69,7 @@ def get_intermediates_summary(
owner_id: Optional[str] = Query(
default=None, min_length=1, max_length=255, description="Admins only: restrict rows to one account"
),
+ project_id: Optional[str] = Query(default=None, min_length=1, max_length=255),
search: Optional[str] = Query(default=None, max_length=200, description="Project (and, for admins, owner) filter"),
sort: IntermediatesSummarySort = Query(default="reclaimable_bytes"),
order: Literal["asc", "desc"] = Query(default="desc"),
@@ -65,6 +86,7 @@ def get_intermediates_summary(
descending=order == "desc",
offset=offset,
limit=limit,
+ project_id=project_id,
)
except IntermediatesScopeForbiddenError as error:
raise _translate(error)
@@ -83,7 +105,7 @@ def create_intermediates_preview(
"""Freezes the targets a cleanup would act on and reports its impact. Previews expire unused."""
try:
return ApiDependencies.invoker.services.intermediates.create_preview(request, _caller(current_user))
- except (IntermediatesScopeForbiddenError, IntermediatesScopeInvalidError) as error:
+ except (IntermediatesScopeForbiddenError, IntermediatesScopeInvalidError, IntermediatesUnavailableError) as error:
raise _translate(error)
@@ -98,7 +120,6 @@ def start_intermediates_operation(
request: IntermediatesOperationRequest = Body(description="The confirmed preview"),
) -> IntermediatesOperation:
"""Starts the cleanup a preview described. Repeating a request with its idempotency key returns the same operation."""
- assert_image_move_maintenance_inactive()
try:
return ApiDependencies.invoker.services.intermediates.start_operation(request, _caller(current_user))
except (
@@ -133,7 +154,6 @@ def retry_intermediates_operation(
operation_id: str = Path(min_length=1, max_length=64),
) -> IntermediatesOperation:
"""Retries exactly the targets a finished operation left unresolved, as a new operation."""
- assert_image_move_maintenance_inactive()
try:
return ApiDependencies.invoker.services.intermediates.retry_operation(operation_id, _caller(current_user))
except (
diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.py
index 83fcf0a56a..6cf368bc95 100644
--- a/invokeai/app/services/intermediates/intermediates_base.py
+++ b/invokeai/app/services/intermediates/intermediates_base.py
@@ -3,6 +3,7 @@ from dataclasses import dataclass
from typing import Optional
from invokeai.app.services.intermediates.intermediates_common import (
+ IntermediatesBrowserHoldRequest,
IntermediatesOperation,
IntermediatesOperationRequest,
IntermediatesPreview,
@@ -23,6 +24,16 @@ class IntermediatesCaller:
class IntermediatesServiceBase(ABC):
"""Scoped cleanup of intermediate images and videos under one eligibility policy."""
+ @abstractmethod
+ def replace_browser_hold(
+ self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequest
+ ) -> None:
+ pass
+
+ @abstractmethod
+ def release_browser_hold(self, caller: IntermediatesCaller, lease_id: str) -> None:
+ pass
+
@abstractmethod
def get_summary(
self,
@@ -34,6 +45,7 @@ class IntermediatesServiceBase(ABC):
descending: bool,
offset: int,
limit: int,
+ project_id: Optional[str] = None,
) -> IntermediatesSummary:
pass
diff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.py
index ea3a29834f..3b46ccadb4 100644
--- a/invokeai/app/services/intermediates/intermediates_common.py
+++ b/invokeai/app/services/intermediates/intermediates_common.py
@@ -1,7 +1,7 @@
"""Contracts of the intermediates manager: summaries, previews and cleanup operations."""
from datetime import datetime
-from typing import Literal, Optional
+from typing import Annotated, Literal, Optional
from pydantic import BaseModel, Field
@@ -20,6 +20,13 @@ RECENT_GRACE_SECONDS = 30 * 60
PREVIEW_TTL_SECONDS = 10 * 60
+MediaName = Annotated[str, Field(min_length=1, max_length=255)]
+
+
+class IntermediatesBrowserHoldRequest(BaseModel):
+ images: list[MediaName] = Field(default_factory=list, max_length=50_000)
+ videos: list[MediaName] = Field(default_factory=list, max_length=50_000)
+
class IntermediatesScopeTarget(BaseModel):
"""One row of the manager: an owner's project, or their unassigned intermediates."""
@@ -131,6 +138,9 @@ class IntermediatesPreview(BaseModel):
created_at: datetime
expires_at: datetime
target_rows: int = Field(description="Rows the scope resolved to")
+ has_more_eligible: bool = Field(
+ default=False, description="More eligible intermediates remain outside this bounded preview batch"
+ )
impact: IntermediatesImpact
affected_documents: list[IntermediatesAffectedDocument] = Field(
default_factory=list,
diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.py
index f0374acd4d..5438cf7d8c 100644
--- a/invokeai/app/services/intermediates/intermediates_default.py
+++ b/invokeai/app/services/intermediates/intermediates_default.py
@@ -3,14 +3,14 @@
Previews freeze the exact targets a confirmation will act on; nothing created afterwards can join
an operation. Operations run on one background worker in bounded batches, and every batch
re-applies the policy on the deleting transaction, so a target that became active, referenced or
-durable since the preview is kept. Operation state lives in this process: a restart abandons an
-in-flight operation part-way, which cannot broaden it (the targets were frozen) and cannot lose a
-file (the image delete journal finishes any purge the crash interrupted).
+durable since the preview is kept. Operation receipts and unresolved targets persist; a restart
+makes interrupted work retryable.
Lock order, for anyone adding a caller: image mutation lock (image service) → database lock. The
queue and document writers take only the database lock, so no cycle is possible.
"""
+import json
import logging
import queue
import threading
@@ -25,6 +25,7 @@ from invokeai.app.services.intermediates.intermediates_common import (
PREVIEW_TTL_SECONDS,
RECENT_GRACE_SECONDS,
IntermediatesAffectedDocument,
+ IntermediatesBrowserHoldRequest,
IntermediatesCleanupMode,
IntermediatesIdempotencyConflictError,
IntermediatesImpact,
@@ -46,9 +47,11 @@ from invokeai.app.services.intermediates.intermediates_common import (
IntermediatesUnavailableError,
)
from invokeai.app.services.intermediates.intermediates_records_sqlite import (
+ AffectedReference,
IntermediateCandidate,
IntermediatesRecordsSqlite,
MediaKind,
+ ScopeCounts,
)
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
@@ -58,6 +61,9 @@ MEASURE_BATCH_SIZE = 200
# A row is written before its file; measuring it a moment later would record a missing file.
MEASURE_MIN_AGE_SECONDS = 10
MAX_RETAINED_OPERATIONS = 100
+MAX_RETAINED_TARGETS = 500_000
+MAX_ACTIVE_OPERATIONS = 8
+MAX_OPERATION_TARGETS = 50_000
MAX_PREVIEWS = 200
# Frozen (name, size) pairs held across every live preview; the oldest previews expire first.
MAX_FROZEN_PREVIEW_TARGETS = 500_000
@@ -76,6 +82,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]]]]
@dataclass
@@ -84,6 +91,9 @@ 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": {}}
+ )
# 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
@@ -101,9 +111,6 @@ class IntermediatesService(IntermediatesServiceBase):
self._idempotency: dict[tuple[str, str], tuple[str, str]] = {}
self._pending: "queue.Queue[str]" = queue.Queue()
self._measure_requested = threading.Event()
- # Rows a measurement raised on; skipped for the rest of the process so one bad file cannot
- # stall every later row.
- self._measure_skipped: set[str] = set()
self._stop = threading.Event()
self._worker: Optional[threading.Thread] = None
@@ -112,6 +119,36 @@ class IntermediatesService(IntermediatesServiceBase):
def start(self, invoker: Invoker) -> None:
self._invoker = invoker
self._stop.clear()
+ 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")}
+ operation = _Operation(
+ dto=dto,
+ caller=IntermediatesCaller(user_id=user_id, is_admin=bool(state["caller_is_admin"])),
+ targets={"image": [], "video": []},
+ allowed_user_ids=(
+ frozenset(state["allowed_user_ids"]) if state["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,
+ )
+ 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._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)
+ self._prune_operations_locked()
def stop(self, invoker: Optional[Invoker] = None) -> None:
self._stop.set()
@@ -143,6 +180,14 @@ class IntermediatesService(IntermediatesServiceBase):
# region summary
+ def replace_browser_hold(
+ self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequest
+ ) -> None:
+ self._records.replace_browser_hold(caller.user_id, lease_id, request.images, request.videos)
+
+ def release_browser_hold(self, caller: IntermediatesCaller, lease_id: str) -> None:
+ self._records.release_browser_hold(caller.user_id, lease_id)
+
def get_summary(
self,
caller: IntermediatesCaller,
@@ -153,6 +198,7 @@ class IntermediatesService(IntermediatesServiceBase):
descending: bool,
offset: int,
limit: int,
+ project_id: Optional[str] = None,
) -> IntermediatesSummary:
owner_filter = self._resolve_owner_filter(caller, owner_id)
aggregated = self._records.summarize(owner_filter)
@@ -160,13 +206,13 @@ class IntermediatesService(IntermediatesServiceBase):
users = self._services.users.get_many([user_id for user_id, _ in aggregated])
rows: list[IntermediatesRow] = []
- for (user_id, project_id), kinds in aggregated.items():
+ for (user_id, row_project_id), kinds in aggregated.items():
user = users.get(user_id)
- project = projects.get((user_id, project_id)) if project_id is not None else None
+ project = projects.get((user_id, row_project_id)) if row_project_id is not None else None
rows.append(
IntermediatesRow(
user_id=user_id,
- project_id=project_id,
+ project_id=row_project_id,
user_display_name=user.display_name if user is not None else None,
user_email=user.email if user is not None else None,
project_name=project[0] if project is not None else None,
@@ -179,6 +225,8 @@ class IntermediatesService(IntermediatesServiceBase):
)
)
+ if project_id is not None:
+ rows = [row for row in rows if row.project_id == project_id]
if search:
needle = search.casefold()
rows = [row for row in rows if self._matches(row, needle, include_owner=caller.is_admin)]
@@ -236,19 +284,41 @@ class IntermediatesService(IntermediatesServiceBase):
def create_preview(self, request: IntermediatesPreviewRequest, caller: IntermediatesCaller) -> IntermediatesPreview:
scope = request.scope
allowed = self._authorize_scope(scope, caller)
- candidates = self._collect_candidates(scope)
+ candidates, has_more_eligible = self._collect_candidates(scope, request.mode)
+ counts = self._records.summarize(scope.user_id if scope.kind == "owner" else 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}
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,
+ )
targets: dict[MediaKind, list[tuple[str, Optional[int]]]] = {"image": [], "video": []}
for kind in ("image", "video"):
media_kind = cast(MediaKind, kind)
for candidate in candidates[media_kind]:
self._tally(impact, media_kind, candidate, request.mode, targets)
+ confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]] = {"image": {}, "video": {}}
affected: list[IntermediatesAffectedDocument] = []
hidden = 0
if request.mode == "force":
- affected, hidden = self._describe_affected(candidates, caller)
+ for kind in ("image", "video"):
+ media_kind = cast(MediaKind, kind)
+ confirmed_references[media_kind] = self._records.reference_owners(
+ media_kind, [name for name, _ in targets[media_kind]]
+ )
+ affected, hidden = self._describe_affected(confirmed_references, caller)
created = _now()
dto = IntermediatesPreview(
@@ -257,14 +327,19 @@ class IntermediatesService(IntermediatesServiceBase):
scope=scope,
created_at=created,
expires_at=created + timedelta(seconds=PREVIEW_TTL_SECONDS),
- target_rows=self._count_target_rows(scope, candidates),
+ target_rows=self._count_target_rows(scope, counts),
impact=impact,
+ has_more_eligible=has_more_eligible,
affected_documents=affected,
affected_documents_hidden=hidden,
)
with self._lock:
self._previews[dto.preview_id] = _Preview(
- dto=dto, caller_user_id=caller.user_id, targets=targets, allowed_user_ids=allowed
+ dto=dto,
+ caller_user_id=caller.user_id,
+ targets=targets,
+ allowed_user_ids=allowed,
+ confirmed_references=confirmed_references,
)
self._expire_previews_locked(created)
return dto
@@ -288,7 +363,9 @@ class IntermediatesService(IntermediatesServiceBase):
raise IntermediatesScopeForbiddenError("Only administrators can clear another account's intermediates")
return owners
- def _collect_candidates(self, scope: IntermediatesScope) -> dict[MediaKind, list[IntermediateCandidate]]:
+ 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":
@@ -296,17 +373,26 @@ class IntermediatesService(IntermediatesServiceBase):
targets = list({(t.user_id, t.project_id): t for t in scope.targets}.values())
elif scope.kind == "owner":
user_id = scope.user_id
- return {
- "image": self._records.list_candidates("image", user_id=user_id, targets=targets),
- "video": self._records.list_candidates("video", user_id=user_id, targets=targets),
- }
+ 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, candidates: dict[MediaKind, list[IntermediateCandidate]]) -> int:
+ 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({(candidate.user_id, candidate.project_id) for kind in candidates.values() for candidate in kind})
+ return len(counts)
@staticmethod
def _tally(
@@ -330,13 +416,18 @@ class IntermediatesService(IntermediatesServiceBase):
setattr(impact, attribute, getattr(impact, attribute) + 1)
def _describe_affected(
- self, candidates: dict[MediaKind, list[IntermediateCandidate]], caller: IntermediatesCaller
+ self,
+ confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]],
+ caller: IntermediatesCaller,
) -> tuple[list[IntermediatesAffectedDocument], int]:
- refs = []
- for kind in ("image", "video"):
- media_kind = cast(MediaKind, kind)
- names = [c.name for c in candidates[media_kind] if c.classification == "referenced"]
- refs.extend(self._records.affected_references(media_kind, names))
+ counts: dict[tuple[str, str, str], 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)
visible: list[IntermediatesAffectedDocument] = []
hidden = 0
@@ -385,6 +476,11 @@ 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._expire_previews_locked(_now())
preview = self._previews.get(request.preview_id)
if preview is None or preview.caller_user_id != caller.user_id:
@@ -398,9 +494,25 @@ class IntermediatesService(IntermediatesServiceBase):
scope=preview.dto.scope,
targets=preview.targets,
allowed_user_ids=preview.allowed_user_ids,
+ confirmed_references=preview.confirmed_references,
retried_from=None,
)
+ try:
+ self._records.save_operation(
+ operation.dto.operation_id,
+ caller.user_id,
+ self._operation_state(operation),
+ preview_id=request.preview_id,
+ idempotency_key=request.idempotency_key,
+ targets=self._operation_target_rows(operation),
+ )
+ except Exception:
+ self._operations.pop(operation.dto.operation_id)
+ self._operation_order.remove(operation.dto.operation_id)
+ self._previews[request.preview_id] = preview
+ raise
self._idempotency[key] = (request.preview_id, operation.dto.operation_id)
+ self._prune_operations_locked()
self._enqueue(operation)
return operation.dto.model_copy(deep=True)
@@ -412,7 +524,6 @@ class IntermediatesService(IntermediatesServiceBase):
return operation.dto.model_copy(deep=True)
def retry_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:
- self._require_cleanup_available()
with self._lock:
original = self._operations.get(operation_id)
if original is None or (original.caller.user_id != caller.user_id and not caller.is_admin):
@@ -422,7 +533,16 @@ class IntermediatesService(IntermediatesServiceBase):
if original.dto.retried_by_operation_id 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.
- return self._operations[original.dto.retried_by_operation_id].dto.model_copy(deep=True)
+ 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")
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")
@@ -434,9 +554,26 @@ class IntermediatesService(IntermediatesServiceBase):
scope=original.dto.scope,
targets=unresolved,
allowed_user_ids=original.allowed_user_ids,
+ confirmed_references=original.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)),
+ targets=self._operation_target_rows(operation),
+ )
+ except Exception:
+ self._operations.pop(operation.dto.operation_id)
+ self._operation_order.remove(operation.dto.operation_id)
+ original.dto.retried_by_operation_id = None
+ raise
+ original.unresolved = {"image": {}, "video": {}}
+ original.confirmed_references = {"image": {}, "video": {}}
+ self._prune_operations_locked()
self._enqueue(operation)
return operation.dto.model_copy(deep=True)
@@ -448,6 +585,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]]]],
retried_from: Optional[str],
) -> _Operation:
dto = IntermediatesOperation(
@@ -469,19 +607,64 @@ class IntermediatesService(IntermediatesServiceBase):
caller=caller,
targets={"image": list(targets["image"]), "video": list(targets["video"])},
allowed_user_ids=allowed_user_ids,
+ confirmed_references={kind: dict(owners) for kind, owners in confirmed_references.items()},
unresolved={"image": dict(targets["image"]), "video": dict(targets["video"])},
)
self._operations[dto.operation_id] = operation
self._operation_order.append(dto.operation_id)
- while len(self._operation_order) > MAX_RETAINED_OPERATIONS:
- oldest = self._operation_order[0]
- if self._operations[oldest].dto.status in ("pending", "running"):
- break
- self._operation_order.pop(0)
- self._operations.pop(oldest, None)
- self._idempotency = {k: v for k, v in self._idempotency.items() if v[1] != oldest}
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,
+ }
+
+ @staticmethod
+ def _operation_target_rows(operation: _Operation) -> list[tuple[str, str, Optional[int], str]]:
+ return [
+ (kind, name, size, json.dumps(sorted(operation.confirmed_references[kind].get(name, set()))))
+ for kind, names in operation.unresolved.items()
+ for name, size in names.items()
+ ]
+
+ def _prune_operations_locked(self) -> None:
+ 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]
+ retry_id = candidate.dto.retried_by_operation_id
+ retry = self._operations.get(retry_id) if retry_id is not None else None
+ if candidate.dto.status in ("completed", "failed") and (
+ retry is None or retry.dto.status not in ("pending", "running")
+ ):
+ oldest = operation_id
+ 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)
+ 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
+ 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:
self._ensure_worker()
self._pending.put(operation.dto.operation_id)
@@ -532,12 +715,23 @@ class IntermediatesService(IntermediatesServiceBase):
self._run(operation)
except Exception as error: # pragma: no cover - defensive: the worker must survive
self._logger.error(f"Intermediates operation {operation_id} crashed: {error}", exc_info=True)
- self._finish(operation, error=str(error))
+ try:
+ self._finish(operation, error=str(error))
+ except Exception as finish_error:
+ # A failed receipt write must not strand the rest of the accepted queue.
+ # The target rows remain durable and are retryable after a restart.
+ self._logger.error(
+ f"Could not persist failure for intermediates operation {operation_id}: {finish_error}",
+ exc_info=True,
+ )
def _run(self, operation: _Operation) -> None:
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._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))
deleters: dict[MediaKind, Callable[[list[str], IntermediateDeleteGuard], IntermediateDeleteResult]] = {
@@ -548,7 +742,10 @@ class IntermediatesService(IntermediatesServiceBase):
media_kind = cast(MediaKind, kind)
targets = operation.targets[media_kind]
guard = self._records.make_delete_guard(
- media_kind, mode=operation.dto.mode, allowed_user_ids=operation.allowed_user_ids
+ 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]
@@ -630,7 +827,14 @@ class IntermediatesService(IntermediatesServiceBase):
for name in names:
if name not in failed_set:
unresolved.pop(name, None)
+ operation.confirmed_references[kind].pop(name, None)
setattr(progress, f"unresolved_{suffix}", len(unresolved))
+ self._records.save_operation(
+ operation.dto.operation_id,
+ operation.caller.user_id,
+ self._operation_state(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`.
now = time.monotonic()
if now - operation.last_progress_event_at < PROGRESS_EVENT_INTERVAL_SECONDS:
@@ -647,6 +851,10 @@ 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._prune_operations_locked()
snapshot = operation.dto.model_copy(deep=True)
self._services.events.emit_intermediates_operation_changed(snapshot)
@@ -667,27 +875,26 @@ class IntermediatesService(IntermediatesServiceBase):
cast(MediaKind, kind),
MEASURE_BATCH_SIZE,
min_age_seconds=MEASURE_MIN_AGE_SECONDS,
- exclude=sorted(self._measure_skipped),
)
sizes: dict[str, int] = {}
+ unmeasurable: list[str] = []
for name, subfolder in pending:
if self._stop.is_set():
return
- if name in self._measure_skipped:
- continue
try:
size = files.get_file_size_bytes(name, subfolder)
except Exception as error:
self._logger.warning(f"Could not measure {kind} {name}; skipping it until restart: {error}")
- self._measure_skipped.add(name)
+ unmeasurable.append(name)
continue
# A missing file occupies nothing; recording 0 is a measurement, not a guess, and
# keeps the row from being re-measured forever.
sizes[name] = size if size is not None else 0
+ self._records.mark_unmeasurable(cast(MediaKind, kind), unmeasurable)
# One transaction per batch: a library of hundreds of thousands of intermediates is
# measured in a few thousand commits rather than one per file.
records.set_file_sizes_bytes(sizes)
- if len(pending) == MEASURE_BATCH_SIZE and sizes:
+ if len(pending) == MEASURE_BATCH_SIZE:
remaining = True
if remaining:
self._measure_requested.set()
diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
index 8a7665f732..599972ff5a 100644
--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py
+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
@@ -13,6 +13,7 @@ Queue inputs are found by scanning each active item's stored session for media-n
scan is cached per item so a queue of a thousand pending items is parsed once, not per query.
"""
+import json
import re
import sqlite3
from collections import defaultdict
@@ -84,6 +85,127 @@ class IntermediatesRecordsSqlite:
# 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]]] = {}
+ def replace_browser_hold(self, user_id: str, lease_id: str, images: Sequence[str], videos: Sequence[str]) -> None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ "DELETE FROM intermediates_browser_holds WHERE expires_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW');"
+ )
+ cursor.execute(
+ "DELETE FROM intermediates_browser_holds WHERE user_id = ? AND lease_id = ?;", (user_id, lease_id)
+ )
+ cursor.execute("CREATE TEMP TABLE IF NOT EXISTS intermediates_hold_names (name TEXT PRIMARY KEY);")
+ for kind, names in (("image", images), ("video", videos)):
+ cursor.execute("DELETE FROM temp.intermediates_hold_names;")
+ cursor.executemany(
+ "INSERT OR IGNORE INTO temp.intermediates_hold_names(name) VALUES (?);",
+ [(name,) for name in names],
+ )
+ table, name_column, _ = _TABLES[cast(MediaKind, kind)]
+ cursor.execute(
+ f"""--sql
+ INSERT INTO intermediates_browser_holds
+ (user_id, lease_id, media_kind, media_name, expires_at)
+ SELECT ?, ?, ?, m.{name_column}, STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '+1 day')
+ FROM {table} m
+ JOIN temp.intermediates_hold_names h ON h.name = m.{name_column}
+ WHERE m.user_id = ? AND m.is_intermediate = TRUE;
+ """,
+ (user_id, lease_id, kind, user_id),
+ )
+
+ def release_browser_hold(self, user_id: str, lease_id: str) -> None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ "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]]:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ "SELECT operation_id, caller_user_id, preview_id, idempotency_key, state_json "
+ "FROM intermediates_operations ORDER BY created_at, operation_id;"
+ )
+ operations = cursor.fetchall()
+ cursor.execute(
+ "SELECT operation_id, media_kind, media_name, size_bytes, confirmed_refs_json "
+ "FROM intermediates_operation_targets;"
+ )
+ 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": {}}
+ for kind, name, size, refs_json in targets.get(str(operation_id), []):
+ state["unresolved"][kind][name] = size
+ refs = json.loads(refs_json)
+ if refs:
+ state["confirmed_references"][kind][name] = refs
+ loaded.append((str(user), preview, key, state))
+ return loaded
+
+ def save_operation(
+ self,
+ operation_id: str,
+ caller_user_id: str,
+ state: dict,
+ *,
+ 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,
+ ) -> None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ "INSERT INTO intermediates_operations "
+ "(operation_id, caller_user_id, preview_id, idempotency_key, state_json, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(operation_id) DO UPDATE SET state_json = excluded.state_json;",
+ (
+ operation_id,
+ caller_user_id,
+ preview_id,
+ idempotency_key,
+ json.dumps(state),
+ state["dto"]["created_at"],
+ ),
+ )
+ if targets 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],
+ )
+ if resolved_targets is not None:
+ kind, names = resolved_targets
+ cursor.executemany(
+ "DELETE FROM intermediates_operation_targets "
+ "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
+ cursor.execute(
+ "UPDATE intermediates_operations SET state_json = ? WHERE operation_id = ?;",
+ (json.dumps(linked_state), linked_id),
+ )
+ cursor.execute("DELETE FROM intermediates_operation_targets WHERE operation_id = ?;", (linked_id,))
+
+ def delete_operations(self, operation_ids: Sequence[str]) -> None:
+ if not operation_ids:
+ return
+ with self._db.transaction() as cursor:
+ cursor.executemany(
+ "DELETE FROM intermediates_operation_targets WHERE operation_id = ?;",
+ [(name,) for name in operation_ids],
+ )
+ cursor.executemany(
+ "DELETE FROM intermediates_operations WHERE operation_id = ?;", [(name,) for name in operation_ids]
+ )
+
# region policy expression
@staticmethod
@@ -97,6 +219,10 @@ class IntermediatesRecordsSqlite:
AND m.session_id IN (SELECT session_id FROM session_queue WHERE status IN ({statuses}))
) OR m.{name_column} IN (
SELECT name FROM temp.intermediates_active_media WHERE kind = '{kind}'
+ ) 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')
) THEN 'active'
WHEN m.created_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds')
THEN 'recent'
@@ -249,32 +375,43 @@ class IntermediatesRecordsSqlite:
return True
return False
- def next_unmeasured(
- self, kind: MediaKind, limit: int, *, min_age_seconds: int = 0, exclude: Sequence[str] = ()
- ) -> list[tuple[str, str]]:
+ def next_unmeasured(self, kind: MediaKind, limit: int, *, min_age_seconds: int = 0) -> list[tuple[str, str]]:
"""Unmeasured intermediates in insertion order; rows younger than ``min_age_seconds`` are left for later.
- A row is written before its file, so a brand-new one would measure as missing. ``exclude``
- skips names a measurement already failed on, so they cannot pin the batch window.
+ A row is written before its file, so a brand-new one would measure as missing. Failures
+ are held in a temporary table instead of a bounded IN list, so later rows remain reachable.
"""
table, name_column, subfolder_column = _TABLES[kind]
- excluded = list(exclude[: _MAX_SQL_VARIABLES - 2])
- placeholders = ",".join("?" for _ in excluded)
- exclusion = f"AND {name_column} NOT IN ({placeholders})" if excluded else ""
with self._db.transaction() as cursor:
+ cursor.execute(
+ "CREATE TEMP TABLE IF NOT EXISTS intermediates_unmeasurable (kind TEXT, name TEXT, PRIMARY KEY(kind, name));"
+ )
cursor.execute(
f"""--sql
- SELECT {name_column}, {subfolder_column} FROM {table}
- WHERE is_intermediate = TRUE AND file_size_bytes IS NULL
- AND created_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', ?)
- {exclusion}
- ORDER BY rowid ASC
+ SELECT m.{name_column}, m.{subfolder_column} FROM {table} m
+ WHERE m.is_intermediate = TRUE AND m.file_size_bytes IS NULL
+ AND m.created_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', ?)
+ AND NOT EXISTS (SELECT 1 FROM temp.intermediates_unmeasurable u
+ WHERE u.kind = ? AND u.name = m.{name_column})
+ ORDER BY m.rowid ASC
LIMIT ?;
""",
- [f"-{min_age_seconds} seconds", *excluded, limit],
+ [f"-{min_age_seconds} seconds", kind, limit],
)
return [(cast(str, r[0]), cast(str, r[1])) for r in cursor.fetchall()]
+ def mark_unmeasurable(self, kind: MediaKind, names: Sequence[str]) -> None:
+ if not names:
+ return
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ "CREATE TEMP TABLE IF NOT EXISTS intermediates_unmeasurable (kind TEXT, name TEXT, PRIMARY KEY(kind, name));"
+ )
+ cursor.executemany(
+ "INSERT OR IGNORE INTO temp.intermediates_unmeasurable(kind, name) VALUES (?, ?);",
+ [(kind, name) for name in names],
+ )
+
# endregion
# region candidates
@@ -298,6 +435,8 @@ class IntermediatesRecordsSqlite:
*,
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.
@@ -309,24 +448,44 @@ class IntermediatesRecordsSqlite:
with self._db.transaction() as cursor:
self._prepare(cursor)
select = f"""--sql
- SELECT m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes, m.user_id,
+ 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:
continue
- cursor.execute(f"{select} AND ({predicate});", params)
+ 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 [])],
+ )
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:
- cursor.execute(f"{select} AND m.user_id = ?;", (user_id,))
+ 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:
- cursor.execute(f"{select};")
+ 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
@@ -363,6 +522,21 @@ class IntermediatesRecordsSqlite:
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)))
+ return owners
+
def get_document_names(self, refs: Sequence[AffectedReference]) -> dict[tuple[str, str, str], str]:
names: dict[tuple[str, str, str], str] = {}
with self._db.transaction() as cursor:
@@ -383,7 +557,12 @@ class IntermediatesRecordsSqlite:
# region delete guard
def make_delete_guard(
- self, kind: MediaKind, *, mode: IntermediatesCleanupMode, allowed_user_ids: Optional[frozenset[str]]
+ self,
+ kind: MediaKind,
+ *,
+ mode: IntermediatesCleanupMode,
+ allowed_user_ids: Optional[frozenset[str]],
+ confirmed_references: Optional[dict[str, set[tuple[str, str, str]]]] = None,
):
"""The final check of a cleanup batch, run on the deleting transaction.
@@ -400,14 +579,25 @@ class IntermediatesRecordsSqlite:
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))
+ )
cursor.execute(
f"""--sql
SELECT name, user_id FROM (
- SELECT m.{name_column} AS name, m.user_id AS user_id, {self._classification_sql(kind)} AS cls
+ SELECT m.{name_column} AS name, m.user_id AS user_id,
+ {self._classification_sql(kind)} AS cls
FROM {table} m
WHERE m.{name_column} IN ({placeholders}) AND m.is_intermediate = TRUE
- )
- WHERE cls IN {deletable};
+ ) WHERE cls IN {deletable};
""",
chunk,
)
@@ -416,6 +606,10 @@ class IntermediatesRecordsSqlite:
cast(str, row[0])
for row in cursor.fetchall()
if allowed_user_ids is None or cast(str, row[1]) in allowed_user_ids
+ if mode != "force"
+ or current_references.get(cast(str, row[0]), set()).issubset(
+ (confirmed_references or {}).get(cast(str, row[0]), set())
+ )
)
return kept
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 c287fd0778..7c2353d943 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
@@ -46,6 +46,47 @@ class AddIntermediatesManagementCallback:
"""
)
create_media_references_table(cursor)
+ cursor.execute(
+ """--sql
+ CREATE TABLE IF NOT EXISTS intermediates_operations (
+ operation_id TEXT PRIMARY KEY,
+ caller_user_id TEXT NOT NULL,
+ preview_id TEXT,
+ idempotency_key TEXT,
+ state_json TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ UNIQUE(caller_user_id, idempotency_key)
+ );
+ """
+ )
+ cursor.execute(
+ """--sql
+ CREATE TABLE IF NOT EXISTS intermediates_browser_holds (
+ user_id TEXT NOT NULL,
+ lease_id TEXT NOT NULL,
+ media_kind TEXT NOT NULL,
+ media_name TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ PRIMARY KEY(user_id, lease_id, media_kind, media_name)
+ );
+ """
+ )
+ cursor.execute(
+ "CREATE INDEX IF NOT EXISTS idx_intermediates_browser_holds_media "
+ "ON intermediates_browser_holds(media_kind, media_name, expires_at);"
+ )
+ cursor.execute(
+ """--sql
+ CREATE TABLE IF NOT EXISTS intermediates_operation_targets (
+ operation_id TEXT NOT NULL,
+ media_kind TEXT NOT NULL,
+ media_name TEXT NOT NULL,
+ size_bytes INTEGER,
+ confirmed_refs_json TEXT NOT NULL,
+ PRIMARY KEY(operation_id, media_kind, media_name)
+ );
+ """
+ )
self._backfill_references(cursor)
@staticmethod
diff --git a/invokeai/app/services/video_files/video_files_base.py b/invokeai/app/services/video_files/video_files_base.py
index a26a443c72..f7825dffd3 100644
--- a/invokeai/app/services/video_files/video_files_base.py
+++ b/invokeai/app/services/video_files/video_files_base.py
@@ -1,6 +1,6 @@
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Optional
+from typing import Collection, Optional, Sequence
from PIL import Image
@@ -58,7 +58,17 @@ class VideoFileStorageBase(ABC):
pass
@abstractmethod
- def commit_delete(self, token: object) -> None:
+ def begin_delete(self, videos: Sequence[tuple[str, str]]) -> object:
+ """Durably journals a conditional delete before video records are removed."""
+ pass
+
+ @abstractmethod
+ def abandon_delete(self, token: object) -> None:
+ """Discards a pending journal after record deletion fails."""
+ pass
+
+ @abstractmethod
+ def commit_delete(self, token: object, video_names: Optional[Collection[str]] = None) -> None:
"""Permanently removes files represented by a staged-delete token."""
pass
diff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.py
index f0b99aa955..24b5f8a9c8 100644
--- a/invokeai/app/services/video_files/video_files_disk.py
+++ b/invokeai/app/services/video_files/video_files_disk.py
@@ -4,7 +4,7 @@ import shutil
import tempfile
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional, Union
+from typing import Collection, Optional, Sequence, Union
from PIL import Image
@@ -19,6 +19,7 @@ from invokeai.app.services.video_files.video_files_common import (
VideoFileNotFoundException,
VideoFileSaveException,
)
+from invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException
from invokeai.app.util.mp4_metadata import read_mp4_tags, write_mp4_tags
from invokeai.app.util.thumbnails import make_thumbnail
from invokeai.app.util.video_thumbnails import extract_representative_video_frame, get_video_thumbnail_name
@@ -31,6 +32,12 @@ class _StagedDelete:
files: list[tuple[Path, Path]]
+@dataclass
+class _PendingDelete:
+ directory: Path
+ videos: list[tuple[str, str]]
+
+
# Prefix of the same-directory temp file a metadata remux writes before replacing the video.
_EMBED_TEMP_PREFIX = ".embed_"
@@ -151,11 +158,7 @@ class DiskVideoFileStorage(VideoFileStorageBase):
self.commit_delete(token)
def stage_delete(self, video_name: str, video_subfolder: str = "") -> _StagedDelete:
- candidates = [
- self.get_path(video_name, video_subfolder=video_subfolder),
- self.get_path(video_name, thumbnail=True, video_subfolder=video_subfolder),
- self.__get_sidecar_path(video_name, video_subfolder=video_subfolder),
- ]
+ candidates = self.__delete_candidates(video_name, video_subfolder)
staging_dir = Path(tempfile.mkdtemp(prefix=".delete_", dir=self.__output_folder))
staged: list[tuple[Path, Path]] = []
try:
@@ -177,11 +180,77 @@ class DiskVideoFileStorage(VideoFileStorageBase):
shutil.rmtree(staging_dir, ignore_errors=True)
raise VideoFileDeleteException from e
- def commit_delete(self, token: object) -> None:
+ def begin_delete(self, videos: Sequence[tuple[str, str]]) -> _PendingDelete:
+ for name, subfolder in videos:
+ self.__delete_candidates(name, subfolder)
+ directory = Path(tempfile.mkdtemp(prefix=".delete_", dir=self.__output_folder))
+ try:
+ with open(directory / "manifest.json", "w", encoding="utf-8") as manifest:
+ json.dump({"version": 2, "videos": videos}, manifest)
+ manifest.flush()
+ os.fsync(manifest.fileno())
+ self.__fsync_directory(directory)
+ self.__fsync_directory(self.__output_folder)
+ return _PendingDelete(directory=directory, videos=list(videos))
+ except Exception as error:
+ shutil.rmtree(directory, ignore_errors=True)
+ raise VideoFileDeleteException from error
+
+ def abandon_delete(self, token: object) -> None:
+ if not isinstance(token, _PendingDelete):
+ raise VideoFileDeleteException("Invalid pending-delete token")
+ shutil.rmtree(token.directory, ignore_errors=True)
+
+ def commit_delete(self, token: object, video_names: Optional[Collection[str]] = None) -> None:
+ if isinstance(token, _PendingDelete):
+ self.__commit_pending_delete(token, video_names)
+ return
if not isinstance(token, _StagedDelete):
raise VideoFileDeleteException("Invalid staged-delete token")
shutil.rmtree(token.directory)
+ def __commit_pending_delete(self, token: _PendingDelete, video_names: Optional[Collection[str]]) -> None:
+ selected = None if video_names is None else set(video_names)
+ purged: list[tuple[str, str]] = []
+ try:
+ for name, subfolder in token.videos:
+ if selected is not None and name not in selected:
+ continue
+ self.__purge_files(name, subfolder)
+ purged.append((name, subfolder))
+ self.__persist_purges(purged)
+ except OSError as error:
+ # A retry must re-check the record before touching the live files.
+ raise VideoFileDeleteException from error
+ shutil.rmtree(token.directory, ignore_errors=True)
+
+ def __delete_candidates(self, name: str, subfolder: str) -> list[Path]:
+ return [
+ self.get_path(name, video_subfolder=subfolder),
+ self.get_path(name, thumbnail=True, video_subfolder=subfolder),
+ self.__get_sidecar_path(name, video_subfolder=subfolder),
+ ]
+
+ def __purge_files(self, name: str, subfolder: str) -> None:
+ for path in self.__delete_candidates(name, subfolder):
+ path.unlink(missing_ok=True)
+
+ @staticmethod
+ def __fsync_directory(directory: Path) -> None:
+ if os.name == "nt":
+ return
+ descriptor = os.open(directory, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+ def __persist_purges(self, videos: Sequence[tuple[str, str]]) -> None:
+ parents = {path.parent for name, subfolder in videos for path in self.__delete_candidates(name, subfolder)}
+ for parent in parents:
+ if parent.exists():
+ self.__fsync_directory(parent)
+
def rollback_delete(self, token: object) -> None:
if not isinstance(token, _StagedDelete):
raise VideoFileDeleteException("Invalid staged-delete token")
@@ -342,6 +411,16 @@ class DiskVideoFileStorage(VideoFileStorageBase):
try:
with open(manifest_path, encoding="utf-8") as manifest:
data = json.load(manifest)
+ if data.get("version") == 2:
+ videos = [(entry[0], entry[1]) for entry in data["videos"]]
+ for video_name, video_subfolder in videos:
+ try:
+ self.__invoker.services.video_records.get(video_name)
+ except VideoRecordNotFoundException:
+ self.__purge_files(video_name, video_subfolder)
+ self.__persist_purges(videos)
+ shutil.rmtree(staging_dir)
+ continue
video_name = data["video_name"]
video_subfolder = data.get("video_subfolder", "")
candidates = [
@@ -360,8 +439,6 @@ class DiskVideoFileStorage(VideoFileStorageBase):
self.__invoker.services.video_records.get(video_name)
self.rollback_delete(token)
except Exception as error:
- from invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException
-
if isinstance(error, VideoRecordNotFoundException):
shutil.rmtree(staging_dir, ignore_errors=True)
else:
diff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.py
index eb85e05cff..08aec9314c 100644
--- a/invokeai/app/services/videos/videos_default.py
+++ b/invokeai/app/services/videos/videos_default.py
@@ -405,20 +405,23 @@ class VideoService(VideoServiceABC):
if not subfolders:
return IntermediateDeleteResult()
- # Records first, files second, like the image path: only the files of rows the conditional
- # delete actually removed are touched, so a video promoted or protected between the preview
- # and this call keeps both. There is no video delete journal, so a crash between the two
- # steps leaves files without records — the exposure `delete_videos_by_names` already has.
- deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)
- result = IntermediateDeleteResult(deleted_names=deleted)
- for name in deleted:
+ # Journal the live paths before deleting records. The guard decides inside that transaction
+ # which records still qualify; a promoted or newly protected video retains its files.
+ token = files.begin_delete(list(subfolders.items()))
+ try:
+ deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)
+ except Exception:
try:
- files.delete(name, video_subfolder=subfolders[name])
+ files.abandon_delete(token)
except Exception as cleanup_error:
- self.__invoker.services.logger.error(
- f"Failed to purge intermediate video files for {name}: {cleanup_error}"
- )
- result.purge_deferred.append(name)
+ self.__invoker.services.logger.error(f"Failed to discard pending video deletion: {cleanup_error}")
+ raise
+ result = IntermediateDeleteResult(deleted_names=deleted)
+ try:
+ files.commit_delete(token, video_names=deleted)
+ except Exception as cleanup_error:
+ self.__invoker.services.logger.error(f"Failed to purge intermediate video files: {cleanup_error}")
+ result.purge_deferred = list(deleted)
for name in deleted:
self._on_deleted(name)
return result
diff --git a/invokeai/app/services/workflow_records/workflow_records_sqlite.py b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
index 12cbe28b63..c275078868 100644
--- a/invokeai/app/services/workflow_records/workflow_records_sqlite.py
+++ b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
@@ -140,34 +140,32 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
def update_is_public(self, workflow_id: str, is_public: bool, user_id: Optional[str] = None) -> WorkflowRecordDTO:
"""Updates the is_public field of a workflow and manages the 'shared' tag automatically."""
- record = self.get(workflow_id)
- workflow = record.workflow
-
- # Manage "shared" tag: add when public, remove when private
- tags_list = [t.strip() for t in workflow.tags.split(",") if t.strip()] if workflow.tags else []
- if is_public and "shared" not in tags_list:
- tags_list.append("shared")
- elif not is_public and "shared" in tags_list:
- tags_list.remove("shared")
- updated_tags = ", ".join(tags_list)
- updated_workflow = workflow.model_copy(update={"tags": updated_tags})
-
+ # Read and rewrite the current document under one transaction. A concurrent workflow edit
+ # must not land between the read and this full-document write: its reference index would
+ # then describe the edit while the stored workflow names the previous assets.
with self._db.transaction() as cursor:
if user_id is not None:
cursor.execute(
- """--sql
- UPDATE workflow_library
- SET workflow = ?, is_public = ?
- WHERE workflow_id = ? AND category = 'user' AND user_id = ?;
- """,
- (updated_workflow.model_dump_json(), is_public, workflow_id, user_id),
+ "SELECT workflow FROM workflow_library WHERE workflow_id = ? AND category = 'user' AND user_id = ?;",
+ (workflow_id, user_id),
)
else:
+ cursor.execute(
+ "SELECT workflow FROM workflow_library WHERE workflow_id = ? AND category = 'user';", (workflow_id,)
+ )
+ row = cursor.fetchone()
+ if row is not None:
+ workflow = Workflow.model_validate_json(row[0])
+ tags_list = [t.strip() for t in workflow.tags.split(",") if t.strip()] if workflow.tags else []
+ if is_public and "shared" not in tags_list:
+ tags_list.append("shared")
+ elif not is_public and "shared" in tags_list:
+ tags_list.remove("shared")
+ updated_workflow = workflow.model_copy(update={"tags": ", ".join(tags_list)})
cursor.execute(
"""--sql
UPDATE workflow_library
- SET workflow = ?, is_public = ?
- WHERE workflow_id = ? AND category = 'user';
+ SET workflow = ?, is_public = ? WHERE workflow_id = ?;
""",
(updated_workflow.model_dump_json(), is_public, workflow_id),
)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index b0593c5ef3..16ca5cdbee 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -7518,6 +7518,95 @@
}
}
},
+ "/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"],
@@ -7550,6 +7639,24 @@
},
"description": "Admins only: restrict rows to one account"
},
+ {
+ "name": "project_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 255
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id"
+ }
+ },
{
"name": "search",
"in": "query",
@@ -49153,6 +49260,32 @@
"title": "IntermediatesAffectedDocument",
"description": "A saved document a force clear would leave pointing at deleted media."
},
+ "IntermediatesBrowserHoldRequest": {
+ "properties": {
+ "images": {
+ "items": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ },
+ "type": "array",
+ "maxItems": 50000,
+ "title": "Images"
+ },
+ "videos": {
+ "items": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ },
+ "type": "array",
+ "maxItems": 50000,
+ "title": "Videos"
+ }
+ },
+ "type": "object",
+ "title": "IntermediatesBrowserHoldRequest"
+ },
"IntermediatesImpact": {
"properties": {
"delete_images": {
@@ -49330,6 +49463,18 @@
}
],
"title": "Retried From Operation Id"
+ },
+ "retried_by_operation_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Retried By Operation Id",
+ "description": "The retry that took over this operation's unresolved targets, if any"
}
},
"type": "object",
@@ -49418,11 +49563,29 @@
"description": "Bytes whose files are confirmed removed",
"default": 0
},
+ "unknown_size_count": {
+ "type": "integer",
+ "title": "Unknown Size Count",
+ "description": "Deleted items whose size was never measured; their bytes are not in reclaimed_bytes",
+ "default": 0
+ },
"pending_disk_cleanup": {
"type": "integer",
"title": "Pending Disk Cleanup",
"description": "Deleted records whose files could not be purged yet; the journal retries at startup",
"default": 0
+ },
+ "unresolved_images": {
+ "type": "integer",
+ "title": "Unresolved Images",
+ "description": "Image targets that failed or were never attempted",
+ "default": 0
+ },
+ "unresolved_videos": {
+ "type": "integer",
+ "title": "Unresolved Videos",
+ "description": "Video targets that failed or were never attempted",
+ "default": 0
}
},
"type": "object",
@@ -49477,6 +49640,12 @@
"title": "Target Rows",
"description": "Rows the scope resolved to"
},
+ "has_more_eligible": {
+ "type": "boolean",
+ "title": "Has More Eligible",
+ "description": "More eligible intermediates remain outside this bounded preview batch",
+ "default": false
+ },
"impact": {
"$ref": "#/components/schemas/IntermediatesImpact"
},
@@ -49518,13 +49687,17 @@
"properties": {
"user_id": {
"type": "string",
+ "maxLength": 255,
+ "minLength": 1,
"title": "User Id",
"description": "The owning account"
},
"project_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
},
{
"type": "null"
@@ -49569,6 +49742,18 @@
"title": "Project Name",
"description": "The project's name; null for unassigned rows"
},
+ "cover_image_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image Name",
+ "description": "The newest durable image on the project's board, for a thumbnail"
+ },
"images": {
"$ref": "#/components/schemas/IntermediatesKindCounts"
},
@@ -49618,7 +49803,9 @@
"user_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
},
{
"type": "null"
@@ -49636,13 +49823,17 @@
"properties": {
"user_id": {
"type": "string",
+ "maxLength": 255,
+ "minLength": 1,
"title": "User Id",
"description": "The owning account"
},
"project_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
},
{
"type": "null"
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 0f2c4a5af9..b52960e60c 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1820,6 +1820,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_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;
@@ -20628,6 +20649,13 @@ export type components = {
*/
references: number;
};
+ /** IntermediatesBrowserHoldRequest */
+ IntermediatesBrowserHoldRequest: {
+ /** Images */
+ images?: string[];
+ /** Videos */
+ videos?: string[];
+ };
/** IntermediatesImpact */
IntermediatesImpact: {
/**
@@ -20760,6 +20788,11 @@ export type components = {
progress: components["schemas"]["IntermediatesOperationProgress"];
/** Retried From Operation Id */
retried_from_operation_id?: string | null;
+ /**
+ * Retried By Operation Id
+ * @description The retry that took over this operation's unresolved targets, if any
+ */
+ retried_by_operation_id?: string | null;
};
/**
* IntermediatesOperationChangedEvent
@@ -20832,12 +20865,30 @@ export type components = {
* @default 0
*/
reclaimed_bytes?: number;
+ /**
+ * Unknown Size Count
+ * @description Deleted items whose size was never measured; their bytes are not in reclaimed_bytes
+ * @default 0
+ */
+ unknown_size_count?: number;
/**
* Pending Disk Cleanup
* @description Deleted records whose files could not be purged yet; the journal retries at startup
* @default 0
*/
pending_disk_cleanup?: number;
+ /**
+ * Unresolved Images
+ * @description Image targets that failed or were never attempted
+ * @default 0
+ */
+ unresolved_images?: number;
+ /**
+ * Unresolved Videos
+ * @description Video targets that failed or were never attempted
+ * @default 0
+ */
+ unresolved_videos?: number;
};
/** IntermediatesOperationRequest */
IntermediatesOperationRequest: {
@@ -20874,6 +20925,12 @@ export type components = {
* @description Rows the scope resolved to
*/
target_rows: number;
+ /**
+ * Has More Eligible
+ * @description More eligible intermediates remain outside this bounded preview batch
+ * @default false
+ */
+ has_more_eligible?: boolean;
impact: components["schemas"]["IntermediatesImpact"];
/**
* Affected Documents
@@ -20923,6 +20980,11 @@ export type components = {
* @description The project's name; null for unassigned rows
*/
project_name?: string | null;
+ /**
+ * Cover Image Name
+ * @description The newest durable image on the project's board, for a thumbnail
+ */
+ cover_image_name?: string | null;
images?: components["schemas"]["IntermediatesKindCounts"];
videos?: components["schemas"]["IntermediatesKindCounts"];
/**
@@ -53166,11 +53228,74 @@ 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?: {
/** @description Admins only: restrict rows to one account */
owner_id?: string | null;
+ project_id?: string | null;
/** @description Project (and, for admins, owner) filter */
search?: string | null;
sort?: "reclaimable_bytes" | "project_name";
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 9be43acc3d..6502d4f7bb 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4220,6 +4220,7 @@
"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}}?",
"reclaim": "Approximately {{size}} can be reclaimed.",
@@ -4277,7 +4278,10 @@
},
"owner": {
"filtered": "Account: {{name}}",
- "showEveryone": "Show everyone"
+ "showEveryone": "Show everyone",
+ "showMine": "My account",
+ "projectFilter": "Selected project",
+ "showAllProjects": "Show all projects"
},
"list": {
"selectAll": "Select all",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 609b411dae..213f81ac19 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -1066,6 +1066,11 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, []);
}
+ if ((method === 'PUT' || method === 'DELETE') && /^\/api\/v1\/intermediates\/holds\/[^/]+$/.test(path)) {
+ response.writeHead(204);
+ return response.end();
+ }
+
if (method === 'GET' && path === '/api/v1/intermediates/summary') {
const search = (url.searchParams.get('search') ?? '').trim().toLowerCase();
const sort = url.searchParams.get('sort') ?? 'reclaimable_bytes';
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 1fcc597412..aa3bb47e76 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -931,9 +931,10 @@ const runSettingsJourney = async (browser) => {
const sectionNames = await navigation.getByRole('button').allTextContents();
assert.equal(
sectionNames.length,
- 14,
+ 15,
'All application, project, widget, and system sections must be discoverable.'
);
+ assert(sectionNames.includes('Intermediates'), 'Intermediates settings must be discoverable.');
for (const name of sectionNames) {
await navigation.getByRole('button', { exact: true, name }).click();
await page.getByRole('dialog', { exact: true, name: `Settings: ${name}` }).waitFor();
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 3a6439564b..09d5bf1c3a 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
@@ -60,7 +60,7 @@ describe('row selection', () => {
selection = toggleRowSelection(selection, secondPage[1]!, secondPage);
expect(summarizeSelection(selection, totals).rows).toBe(2);
- expect(resolveScope({ hasSearch: false, loadedRows: secondPage, ownerId: 'alice', selection })).toEqual({
+ expect(resolveScope({ hasSubsetFilter: false, loadedRows: secondPage, ownerId: 'alice', selection })).toEqual({
kind: 'selection',
targets: [
{ projectId: 'a', userId: 'alice' },
@@ -116,27 +116,30 @@ describe('selection summary', () => {
describe('scope resolution', () => {
it('turns all-matching without a search into the owner or everyone scope', () => {
expect(
- resolveScope({ hasSearch: false, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
+ resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
).toEqual({ kind: 'owner', userId: 'alice' });
- expect(resolveScope({ hasSearch: false, loadedRows: page, ownerId: null, selection: selectAllMatching() })).toEqual(
- {
- kind: 'everyone',
- }
- );
+ expect(
+ resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: null, selection: selectAllMatching() })
+ ).toEqual({
+ kind: 'everyone',
+ });
});
it('turns picks, and all-matching under a search, into explicit targets', () => {
const picks = toggleRowSelection(EMPTY_SELECTION, page[2]!, page);
- expect(resolveScope({ hasSearch: false, loadedRows: page, ownerId: 'alice', selection: picks })).toEqual({
+ expect(resolveScope({ hasSubsetFilter: false, loadedRows: page, ownerId: 'alice', selection: picks })).toEqual({
kind: 'selection',
targets: [{ projectId: null, userId: 'alice' }],
});
expect(
- resolveScope({ hasSearch: true, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
+ resolveScope({ hasSubsetFilter: true, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
).toEqual({
kind: 'selection',
targets: page.map(({ projectId, userId }) => ({ projectId, userId })),
});
+ 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 142f4d4b01..fdb4375e4d 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
@@ -145,18 +145,18 @@ export const selectionToTargets = (
}));
/**
- * The scope a confirmation acts on. With no search, "all matching" is exactly the owner filter (or everyone), which
- * the server can freeze without the client enumerating rows.
+ * 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.
*/
export const resolveScope = (options: {
selection: IntermediatesSelection;
loadedRows: readonly IntermediatesRow[];
- hasSearch: boolean;
+ hasSubsetFilter: boolean;
ownerId: string | null;
}): IntermediatesScope => {
- const { hasSearch, loadedRows, ownerId, selection } = options;
+ const { hasSubsetFilter, loadedRows, ownerId, selection } = options;
- if (selection.mode === 'all-matching' && !hasSearch) {
+ if (selection.mode === 'all-matching' && !hasSubsetFilter) {
return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
index e3e9965dd9..f83460f85e 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
@@ -98,6 +98,7 @@ export interface IntermediatesPreview {
createdAt: string;
expiresAt: string;
targetRows: number;
+ hasMoreEligible: boolean;
impact: IntermediatesImpact;
affectedDocuments: IntermediatesAffectedDocument[];
affectedDocumentsHidden: number;
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 5b87560f3c..fa17bc4469 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
@@ -82,6 +82,7 @@ describe('intermediates transport', () => {
affected_documents_hidden: 0,
created_at: 'now',
expires_at: 'later',
+ has_more_eligible: true,
impact: {
delete_images: 1,
delete_videos: 0,
@@ -115,6 +116,7 @@ describe('intermediates transport', () => {
});
expect(preview.scope).toEqual({ kind: 'selection', targets: [{ projectId: null, userId: 'a' }] });
expect(preview.impact.deleteImages).toBe(1);
+ expect(preview.hasMoreEligible).toBe(true);
});
it('maps operation progress including the unresolved counts a retry depends on', () => {
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
index e4a216605b..367a05fc5d 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
@@ -97,6 +97,7 @@ interface PreviewDTO {
created_at: string;
expires_at: string;
target_rows: number;
+ has_more_eligible: boolean;
impact: ImpactDTO;
affected_documents: AffectedDocumentDTO[];
affected_documents_hidden: number;
@@ -247,6 +248,9 @@ const buildSummaryUrl = (params: IntermediatesSummaryParams): string => {
if (params.ownerId) {
query.set('owner_id', params.ownerId);
}
+ if (params.projectId) {
+ query.set('project_id', params.projectId);
+ }
if (params.search?.trim()) {
query.set('search', params.search.trim());
}
@@ -315,6 +319,7 @@ export const createIntermediatesPreview = async (
previewId: dto.preview_id,
scope: mapScope(dto.scope),
targetRows: dto.target_rows,
+ hasMoreEligible: dto.has_more_eligible,
};
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts b/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts
index dbd2d08f94..6262e8215e 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts
@@ -3,6 +3,7 @@ import type { AccountScope } from '@platform/state/accountLifecycle';
export interface IntermediatesSummaryParams {
ownerId?: string | null;
+ projectId?: string | null;
search?: string;
sort?: IntermediatesSummarySort;
order?: 'asc' | 'desc';
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
index f91fd2197c..50afe25382 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
@@ -1,4 +1,4 @@
-import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { captureAccountScope, registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -7,6 +7,61 @@ import { createExternalStore } from '@platform/state/externalStore';
*/
export const activeOperationStore = createExternalStore<{ operationId: string | null }>({ operationId: null });
+interface PendingStart {
+ previewId: string;
+ idempotencyKey: string;
+}
+
+const receiptKey = (): string => {
+ const owner = captureAccountScope();
+ return `invokeai:webv2:intermediates-receipt:${owner.accountId ?? 'local'}${owner.storageSuffix}`;
+};
+
+const readReceipt = (): { operationId?: string; pendingStart?: PendingStart } => {
+ try {
+ return JSON.parse(sessionStorage.getItem(receiptKey()) ?? '{}') as {
+ operationId?: string;
+ pendingStart?: PendingStart;
+ };
+ } catch {
+ return {};
+ }
+};
+
+const writeReceipt = (receipt: { operationId?: string; pendingStart?: PendingStart }): void => {
+ try {
+ if (!receipt.operationId && !receipt.pendingStart) {
+ sessionStorage.removeItem(receiptKey());
+ } else {
+ sessionStorage.setItem(receiptKey(), JSON.stringify(receipt));
+ }
+ } catch {
+ // A private-mode storage failure still leaves the in-memory operation visible this session.
+ }
+};
+
+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): boolean => {
+ const current = readReceipt().pendingStart;
+ return current?.previewId === pendingStart.previewId && current.idempotencyKey === pendingStart.idempotencyKey;
+};
+
+export const clearPendingIntermediatesStart = (): void => {
+ const { operationId } = readReceipt();
+ writeReceipt({ operationId });
+};
+
registerAccountOwnedResource({
clear: () => activeOperationStore.setSnapshot({ operationId: null }),
name: 'intermediates-active-operation',
@@ -14,4 +69,5 @@ registerAccountOwnedResource({
export const followIntermediatesOperation = (operationId: string | null): void => {
activeOperationStore.setSnapshot({ operationId });
+ writeReceipt({ operationId: operationId ?? undefined });
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
index 9950984981..0246329516 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
@@ -209,6 +209,14 @@ export const ClearDialog = ({
)}
</Box>
</Dialog.Description>
+ {preview?.hasMoreEligible ? (
+ <Alert.Root size="sm" status="info" variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Description>{t('intermediates.dialog.batchLimit')}</Alert.Description>
+ </Alert.Content>
+ </Alert.Root>
+ ) : null}
<Checkbox.Root
checked={isForce}
colorPalette="red"
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 b3065d7cfc..ae20c0b5c6 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
@@ -6,11 +6,13 @@ import type {
} from '@features/intermediates/core/types';
import { ChakraProvider } from '@chakra-ui/react';
+import { ApiError } from '@platform/transport/http';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
const dependencies = vi.hoisted(() => ({
createIntermediatesPreview: vi.fn(),
@@ -93,6 +95,7 @@ const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesP
unknownSizeCount: 0,
},
mode,
+ hasMoreEligible: false,
previewId: `preview-${mode}`,
scope: { kind: 'owner', userId: 'alice' },
targetRows: 1,
@@ -134,7 +137,7 @@ let root: Root;
let queryClient: QueryClient;
const renderManager = async (
- options: { focusProjectId?: string; currentUserId?: string | null } = {}
+ options: { focusProjectId?: string; currentUserId?: string | null; canClearOthersIntermediates?: boolean } = {}
): Promise<void> => {
host = document.createElement('div');
host.style.height = '640px';
@@ -155,7 +158,7 @@ const renderManager = async (
<ChakraProvider value={system}>
<QueryClientProvider client={queryClient}>
<IntermediatesManager
- canClearOthersIntermediates={false}
+ canClearOthersIntermediates={options.canClearOthersIntermediates ?? false}
currentUserId={options.currentUserId === undefined ? 'alice' : options.currentUserId}
/>
</QueryClientProvider>
@@ -189,6 +192,7 @@ const setInputValue = (input: HTMLInputElement, value: string) => {
describe('IntermediatesManager', () => {
beforeEach(() => {
+ sessionStorage.clear();
dependencies.getIntermediatesSummary
.mockReset()
.mockImplementation((params: { search?: string }) =>
@@ -211,6 +215,208 @@ describe('IntermediatesManager', () => {
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation(null);
+ });
+
+ it('starts an admin in their own account and exposes an explicit everyone switch', async () => {
+ await renderManager({ canClearOthersIntermediates: true });
+ host.style.width = '400px';
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesSummary).toHaveBeenCalledWith(
+ expect.objectContaining({ ownerId: 'alice' }),
+ expect.anything()
+ )
+ );
+ const everyoneControl = host.querySelector<HTMLElement>('[aria-label="intermediates.owner.showEveryone"]')!;
+ expect(everyoneControl.getBoundingClientRect().right).toBeLessThanOrEqual(host.getBoundingClientRect().right);
+ await page.screenshot({ path: '../../../../artifacts/intermediates/admin-own-narrow.png' });
+ await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.owner.showEveryone"]')!.click());
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesSummary).toHaveBeenLastCalledWith(
+ expect.objectContaining({ ownerId: null }),
+ expect.anything()
+ )
+ );
+ await act(() => buttonWithText('intermediates.owner.showMine', host).click());
+ expect(host.querySelector('[aria-label="intermediates.owner.showEveryone"]')).not.toBeNull();
+ expect(host.textContent).not.toContain('intermediates.owner.showMine');
+ });
+
+ it('fetches a focused project by id even when it is outside the first page', async () => {
+ dependencies.getIntermediatesSummary.mockImplementation((params: { projectId?: string }) =>
+ Promise.resolve(summaryOf(params.projectId === 'p55' ? [row('p55', 'Far project', 2)] : [row('p1', 'First', 1)]))
+ );
+ await renderManager({ focusProjectId: 'p55' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Far project'));
+ expect(checkbox('intermediates.list.selectRow(name=Far project)').checked).toBe(true);
+ expect(dependencies.getIntermediatesSummary).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'p55' }),
+ expect.anything()
+ );
+ });
+
+ it('keeps Select all within a focused project', async () => {
+ dependencies.getIntermediatesSummary.mockImplementation((params: { projectId?: string }) =>
+ Promise.resolve(summaryOf(params.projectId === 'p1' ? [row('p1', 'Portraits', 4)] : [row('p2', 'Other', 3)]))
+ );
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => checkbox('intermediates.list.selectAll').click());
+ await act(() => checkbox('intermediates.list.selectAll').click());
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
+ { mode: 'safe', scope: { kind: 'selection', targets: [{ projectId: 'p1', userId: 'alice' }] } },
+ expect.anything()
+ )
+ );
+ });
+
+ it('labels a bounded preview as a repeatable batch', async () => {
+ dependencies.createIntermediatesPreview.mockResolvedValue({ ...previewOf('safe', 4), hasMoreEligible: true });
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ await vi.waitFor(() =>
+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('intermediates.dialog.batchLimit')
+ );
+ });
+
+ 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' });
+
+ await renderManager();
+ await vi.waitFor(() =>
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
+ { idempotencyKey: 'confirmed-key', previewId: 'confirmed-preview' },
+ expect.anything()
+ )
+ );
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
+ expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('op-1');
+ });
+
+ it('does not let a late start replay replace a newer confirmed operation', async () => {
+ const { activeOperationStore, recordPendingIntermediatesStart } =
+ await import('@features/intermediates/data/operationStore');
+ let resolveOld!: (operation: IntermediatesOperation) => void;
+ const oldStart = new Promise<IntermediatesOperation>((resolve) => {
+ resolveOld = resolve;
+ });
+ recordPendingIntermediatesStart({ idempotencyKey: 'old-key', previewId: 'old-preview' });
+ dependencies.startIntermediatesOperation.mockImplementation((request: { previewId: string }) =>
+ request.previewId === 'old-preview'
+ ? oldStart
+ : Promise.resolve({ ...operationOf('running'), operationId: 'new-op' })
+ );
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() =>
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
+ { idempotencyKey: 'old-key', previewId: 'old-preview' },
+ expect.anything()
+ )
+ );
+ 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(activeOperationStore.getSnapshot().operationId).toBe('new-op'));
+ await act(() => resolveOld({ ...operationOf('completed'), operationId: 'old-op' }));
+ expect(activeOperationStore.getSnapshot().operationId).toBe('new-op');
+ });
+
+ it('does not let an old rejected replay erase a newer pending confirmation', async () => {
+ const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
+ let rejectOld!: (error: Error) => void;
+ let resolveNew!: (operation: IntermediatesOperation) => void;
+ const oldStart = new Promise<IntermediatesOperation>((_resolve, reject) => {
+ rejectOld = reject;
+ });
+ const newStart = new Promise<IntermediatesOperation>((resolve) => {
+ resolveNew = resolve;
+ });
+ recordPendingIntermediatesStart({ idempotencyKey: 'old-key', previewId: 'old-preview' });
+ dependencies.startIntermediatesOperation.mockImplementation((request: { previewId: string }) =>
+ request.previewId === 'old-preview' ? oldStart : newStart
+ );
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() =>
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
+ { idempotencyKey: 'old-key', previewId: 'old-preview' },
+ expect.anything()
+ )
+ );
+ 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(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-safe')
+ );
+ await act(() => rejectOld(new ApiError('Rejected', 409)));
+ expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-safe');
+ await act(() => resolveNew({ ...operationOf('running'), operationId: 'new-op' }));
+ });
+
+ it('drops a definitively rejected start receipt', async () => {
+ const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
+ recordPendingIntermediatesStart({ idempotencyKey: 'rejected-key', previewId: 'rejected-preview' });
+ dependencies.startIntermediatesOperation.mockRejectedValue(new ApiError('Unavailable', 409));
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Unavailable'));
+ expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toBeNull();
+ });
+
+ it('follows a retry whose response was lost before reload', async () => {
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation('op-1');
+ dependencies.getIntermediatesOperation.mockImplementation((operationId: string) =>
+ Promise.resolve(
+ operationId === 'op-1'
+ ? { ...operationOf('failed'), retriedByOperationId: 'op-2' }
+ : { ...operationOf('running'), operationId: 'op-2' }
+ )
+ );
+ await renderManager();
+ await vi.waitFor(() =>
+ expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('op-2')
+ );
+ expect(host.textContent).toContain('intermediates.operation.status.running');
+ });
+
+ it('does not let a late retry lookup replace a newer followed operation', async () => {
+ const { activeOperationStore, followIntermediatesOperation } =
+ await import('@features/intermediates/data/operationStore');
+ let resolveOriginal!: (operation: IntermediatesOperation) => void;
+ const original = new Promise<IntermediatesOperation>((resolve) => {
+ resolveOriginal = resolve;
+ });
+ dependencies.getIntermediatesOperation.mockImplementation((operationId: string) =>
+ operationId === 'op-1' ? original : Promise.resolve({ ...operationOf('running'), operationId })
+ );
+ followIntermediatesOperation('op-1');
+ await renderManager();
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesOperation).toHaveBeenCalledWith('op-1', expect.anything())
+ );
+ await act(() => followIntermediatesOperation('newer-op'));
+ await act(() => resolveOriginal({ ...operationOf('failed'), retriedByOperationId: 'op-2' }));
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesOperation).toHaveBeenCalledWith('op-2', expect.anything())
+ );
+ expect(activeOperationStore.getSnapshot().operationId).toBe('newer-op');
});
it('lists projects with used and unused counts and keeps Delete disabled until something is selected', async () => {
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
index d1695fe077..58957d51e2 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
@@ -35,13 +35,21 @@ import {
} from '@features/intermediates/core/selection';
import {
createIntermediatesPreview,
+ getIntermediatesOperation,
getIntermediatesSummary,
retryIntermediatesOperation,
startIntermediatesOperation,
} from '@features/intermediates/data/api';
import { takeIntermediatesFocus } from '@features/intermediates/data/focus';
import { intermediatesKeys } from '@features/intermediates/data/keys';
-import { activeOperationStore, followIntermediatesOperation } from '@features/intermediates/data/operationStore';
+import {
+ activeOperationStore,
+ clearPendingIntermediatesStart,
+ followIntermediatesOperation,
+ isPendingIntermediatesStartCurrent,
+ recordPendingIntermediatesStart,
+ restoreIntermediatesReceipt,
+} from '@features/intermediates/data/operationStore';
import {
INTERMEDIATES_MAX_ROWS,
INTERMEDIATES_PAGE_SIZE,
@@ -85,6 +93,19 @@ const EMPTY_TOTALS = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos:
let nextIdempotencyKey = 1;
const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;
+const isDefinitiveStartRejection = (error: unknown): boolean =>
+ error instanceof ApiError && error.status >= 400 && error.status < 500 && error.status !== 408;
+
+const getLatestRetry = async (operationId: string, signal: AbortSignal) => {
+ 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 Settings section: search, a select-all row with the delete action, and one row per project. */
export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserId }: IntermediatesManagerProps) => {
const { t } = useTranslation();
@@ -93,34 +114,88 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
const [focus] = useState(takeIntermediatesFocus);
const [search, setSearch] = useState('');
const [ownerFilter, setOwnerFilter] = useState<string | null>(() =>
- focus?.ownerId && canClearOthersIntermediates ? focus.ownerId : null
+ focus?.ownerId && canClearOthersIntermediates ? focus.ownerId : currentUserId
);
+ const [projectFilter, setProjectFilter] = useState<string | null>(focus?.projectId ?? null);
const [offset, setOffset] = useState(0);
const [selection, setSelection] = useState<IntermediatesSelection>(EMPTY_SELECTION);
- // A project to preselect is resolved against loaded rows, whichever page and owner it turns out to have; the
- // intent is consumed by the first selection change.
+ // The focused project is queried directly, so pagination cannot hide the entry point's selection.
const [pendingProjectId, setPendingProjectId] = useState<string | null>(focus?.projectId ?? null);
const [dialog, setDialog] = useState<ClearDialogState | null>(null);
const activeOperationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
const [retryError, setRetryError] = useState<string | null>(null);
+ const [recoveryError, setRecoveryError] = useState<string | null>(null);
const [isRetrying, setIsRetrying] = useState(false);
const dialogTriggerRef = useRef<HTMLElement | null>(null);
const searchRef = useRef<HTMLInputElement | null>(null);
const previewRequestRef = useRef(0);
const pendingScopeRef = useRef<IntermediatesScope | null>(null);
- useMountEffect(() => attachIntermediatesRealtime(queryClient));
+ useMountEffect(() => {
+ let mounted = true;
+ const detach = attachIntermediatesRealtime(queryClient);
+ const pending = restoreIntermediatesReceipt();
+ if (pending) {
+ const owner = captureAccountScope();
+ void startIntermediatesOperation(pending, owner.signal)
+ .then((operation) => {
+ if (mounted && isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ }
+ })
+ .catch((error: unknown) => {
+ if (mounted && isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
+ if (isDefinitiveStartRejection(error)) {
+ clearPendingIntermediatesStart();
+ }
+ setRecoveryError(getApiErrorMessage(error, t('intermediates.dialog.startFailed')));
+ }
+ });
+ } else {
+ const operationId = activeOperationStore.getSnapshot().operationId;
+ if (operationId) {
+ const owner = captureAccountScope();
+ void getLatestRetry(operationId, owner.signal)
+ .then((operation) => {
+ if (
+ mounted &&
+ isAccountScopeCurrent(owner) &&
+ activeOperationStore.getSnapshot().operationId === operationId &&
+ operation.operationId !== operationId
+ ) {
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ }
+ })
+ .catch(() => undefined); // The operation query reports lookup failures in the panel.
+ }
+ }
+ return () => {
+ mounted = false;
+ detach();
+ };
+ });
- // Non-admins are confined to their own rows by the server whatever is sent; admins see everyone unless filtered.
+ // Non-admins are confined to their own rows by the server whatever is sent.
const ownerId: string | null = canClearOthersIntermediates ? ownerFilter : currentUserId;
const params = useMemo<IntermediatesSummaryParams>(
- () => ({ limit: INTERMEDIATES_PAGE_SIZE, offset, order: 'desc', ownerId, search, sort: 'reclaimable_bytes' }),
- [offset, ownerId, search]
+ () => ({
+ limit: INTERMEDIATES_PAGE_SIZE,
+ offset,
+ order: 'desc',
+ ownerId,
+ projectId: projectFilter,
+ search,
+ sort: 'reclaimable_bytes',
+ }),
+ [offset, ownerId, projectFilter, search]
);
const query = useQuery(intermediatesSummaryQueryOptions(params));
const rows = query.data?.items ?? EMPTY_ROWS;
const totals = query.data?.totals;
const hasSearch = search.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 && offset > 0 && offset >= query.data.total) {
setOffset(
@@ -141,6 +216,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
const handleSearchChange = useCallback(
(value: string) => {
setSearch(value);
+ setProjectFilter(null);
setOffset(0);
// A filter change hides rows; hidden selections would act on what the user can no longer see.
resetSelection();
@@ -152,6 +228,16 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
setOffset(0);
resetSelection();
}, [resetSelection]);
+ const showOwnAccount = useCallback(() => {
+ setOwnerFilter(currentUserId);
+ setOffset(0);
+ resetSelection();
+ }, [currentUserId, resetSelection]);
+ const clearProjectFilter = useCallback(() => {
+ setProjectFilter(null);
+ setOffset(0);
+ resetSelection();
+ }, [resetSelection]);
const handleToggleRow = useCallback(
(row: IntermediatesRow) => {
setPendingProjectId(null);
@@ -184,8 +270,8 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
}));
try {
let resolvedScope = scope;
- // "All matching" under a search cannot be expressed to the server; resolve it to explicit rows.
- if (effectiveSelection.mode === 'all-matching' && hasSearch && scope.kind === 'selection') {
+ // Row filters cannot be expressed by the cleanup scope; resolve them to explicit rows.
+ if (effectiveSelection.mode === 'all-matching' && hasSubsetFilter && scope.kind === 'selection') {
const everything = await getIntermediatesSummary(
{ ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
owner.signal
@@ -216,7 +302,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
}
}
},
- [effectiveSelection.mode, hasSearch, params, t]
+ [effectiveSelection.mode, hasSubsetFilter, params, t]
);
const openDialog = useCallback(
(scope: IntermediatesScope, trigger: HTMLElement | null) => {
@@ -252,6 +338,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
return;
}
const owner = captureAccountScope();
+ recordPendingIntermediatesStart({ idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId });
setDialog((current) => (current ? { ...current, isStarting: true, startError: null } : current));
try {
const operation = await startIntermediatesOperation(
@@ -270,6 +357,9 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
// 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;
+ if (isDefinitiveStartRejection(error)) {
+ clearPendingIntermediatesStart();
+ }
setDialog((current) =>
current
? {
@@ -298,6 +388,20 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
followIntermediatesOperation(operation.operationId);
} catch (error) {
if (isAccountScopeCurrent(owner)) {
+ try {
+ const latest = await getLatestRetry(activeOperationId, owner.signal);
+ if (
+ latest.operationId !== activeOperationId &&
+ isAccountScopeCurrent(owner) &&
+ activeOperationStore.getSnapshot().operationId === activeOperationId
+ ) {
+ queryClient.setQueryData(intermediatesKeys.operation(owner, latest.operationId), latest);
+ followIntermediatesOperation(latest.operationId);
+ return;
+ }
+ } catch {
+ // Preserve the original retry error when reconciliation is unavailable.
+ }
setRetryError(getApiErrorMessage(error, t('intermediates.operation.retryFailed')));
}
} finally {
@@ -316,7 +420,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all });
}, [queryClient]);
- const selectedScope = resolveScope({ hasSearch, loadedRows: rows, ownerId, selection: effectiveSelection });
+ const selectedScope = resolveScope({ hasSubsetFilter, loadedRows: rows, ownerId, selection: effectiveSelection });
const hasSelection = !isSelectionEmpty(effectiveSelection);
const pageSelection = getPageSelectionState(effectiveSelection, rows);
const filteredOwnerRow = ownerFilter ? rows[0] : undefined;
@@ -348,8 +452,13 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</IconButton>
</Tooltip>
</HStack>
- <HStack gap="2">
- <InputGroup flex="1" startElement={SEARCH_ICON}>
+ {recoveryError ? (
+ <Text color="fg.error" fontSize="xs" role="alert">
+ {recoveryError}
+ </Text>
+ ) : null}
+ <HStack flexWrap="wrap" gap="2">
+ <InputGroup flex="1 1 16rem" minW="0" startElement={SEARCH_ICON}>
<Input
ref={searchRef}
aria-label={t('intermediates.searchLabel')}
@@ -363,7 +472,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
onChange={(event) => handleSearchChange(event.currentTarget.value)}
/>
</InputGroup>
- {ownerFilter ? (
+ {canClearOthersIntermediates && ownerFilter ? (
<Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
{t('intermediates.owner.filtered', {
name: filteredOwnerRow ? getOwnerLabel(filteredOwnerRow) : ownerFilter,
@@ -381,6 +490,27 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Tooltip>
</Badge>
) : null}
+ {canClearOthersIntermediates && !ownerFilter && currentUserId ? (
+ <Button size="2xs" variant="outline" onClick={showOwnAccount}>
+ {t('intermediates.owner.showMine')}
+ </Button>
+ ) : null}
+ {projectFilter ? (
+ <Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
+ {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>
+ ) : null}
</HStack>
{activeOperationId ? (
<OperationPanel
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index c091aaf07f..fc425f67e9 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -3,9 +3,11 @@ import type { Project } from '@workbench/projectContracts';
import type { ProjectSettings } from '@workbench/settings/contracts';
import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';
+import { createUuid } from '@platform/browser/randomUuid';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';
import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
+import { apiFetch } from '@platform/transport/http';
import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,6 +19,7 @@ import { createExtensionRegistry, type ExtensionRegistry } from './extensions/ex
import { clearLayerPanelStates } from './layerPanelState';
import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';
import { createOpenProjectBroker } from './projects/openProjectBroker';
+import { collectHeldAssetRefs, partitionHeldAssetNames } from './projects/projectAssets';
import { describeRefusedProjects } from './projects/projectLoadRefusal';
import {
createSyncedWorkbenchPersistence,
@@ -44,6 +47,119 @@ const getNullSnapshot = (): null => null;
export const shallowEqual = selectorShallowEqual;
+/** An open editor keeps its unsaved and undo media protected while the tab is alive. */
+const startBrowserIntermediateHold = (store: WorkbenchInternalStore, owner: AccountScope): (() => void) => {
+ const leaseId = createUuid();
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let inFlight = false;
+ let pending = false;
+ let pendingRefresh = false;
+ const lastSentSignatures: string[] = [];
+ let lastProjects = store.getSnapshot().projects;
+ // Canvas undo owns some references outside Project. Retain every asset observed in this open
+ // editor until its lease expires, so removing a layer cannot expose its undo image to cleanup.
+ const seenImages = new Set<string>();
+ const seenVideos = new Set<string>();
+ const observe = (projects: readonly Project[]): void => {
+ const refs = collectHeldAssetRefs(projects);
+ for (const name of refs.images) {
+ seenImages.add(name);
+ }
+ for (const name of refs.videos) {
+ seenVideos.add(name);
+ }
+ };
+ observe(lastProjects);
+
+ const send = async (refresh = false): Promise<void> => {
+ if (disposed || owner.signal.aborted) {
+ return;
+ }
+ if (inFlight) {
+ pending = true;
+ pendingRefresh ||= refresh;
+ return;
+ }
+ inFlight = true;
+ try {
+ do {
+ pending = false;
+ observe(store.getSnapshot().projects);
+ const images = [...seenImages];
+ const videos = [...seenVideos];
+ const mustRefresh = refresh || pendingRefresh;
+ refresh = false;
+ pendingRefresh = false;
+ if (!images.length && !videos.length && lastSentSignatures.length === 0) {
+ continue;
+ }
+ const batches = partitionHeldAssetNames(images, videos);
+ for (let index = 0; index < batches.length; index += 1) {
+ if (disposed || owner.signal.aborted) {
+ break;
+ }
+ const batch = batches[index]!;
+ const signature = JSON.stringify([batch.images, batch.videos]);
+ if (!mustRefresh && signature === lastSentSignatures[index]) {
+ continue;
+ }
+ try {
+ await apiFetch(`/api/v1/intermediates/holds/${encodeURIComponent(`${leaseId}-${index}`)}`, {
+ body: JSON.stringify(batch),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ signal: owner.signal,
+ });
+ lastSentSignatures[index] = signature;
+ } catch {
+ // Each failed batch keeps its prior server hold and retries on the next heartbeat.
+ }
+ }
+ if (disposed || owner.signal.aborted) {
+ break;
+ }
+ } while (pending);
+ } finally {
+ inFlight = false;
+ }
+ };
+ const schedule = (): void => {
+ const projects = store.getSnapshot().projects;
+ if (projects === lastProjects) {
+ return;
+ }
+ const changedProjects = projects.filter((project, index) => project !== lastProjects[index]);
+ lastProjects = projects;
+ observe(changedProjects);
+ if (timer !== null) {
+ clearTimeout(timer);
+ }
+ timer = setTimeout(() => {
+ timer = null;
+ void send();
+ }, 250);
+ };
+ const unsubscribe = store.subscribe(schedule);
+ const heartbeat = setInterval(() => void send(true), 5 * 60_000);
+ const onVisible = (): void => {
+ if (document.visibilityState === 'visible') {
+ void send(true);
+ }
+ };
+ document.addEventListener('visibilitychange', onVisible);
+ void send();
+ return () => {
+ disposed = true;
+ unsubscribe();
+ clearInterval(heartbeat);
+ document.removeEventListener('visibilitychange', onVisible);
+ if (timer !== null) {
+ clearTimeout(timer);
+ }
+ };
+};
+
export const WorkbenchProvider = ({
children,
loadOptions,
@@ -134,8 +250,10 @@ export const WorkbenchProvider = ({
});
persistenceRuntime.start();
+ const releaseIntermediateHold = startBrowserIntermediateHold(store, owner);
return () => {
+ releaseIntermediateHold();
clearLayerPanelStates();
openProjectBroker.dispose();
persistenceRuntime.dispose();
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
index d556abf493..f1eefb1b2e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
@@ -1,6 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName, stripInstallationState } from './projectAssets';
+import {
+ collectHeldAssetRefs,
+ collectLiveAssetRefs,
+ partitionHeldAssetNames,
+ remapAssetRefs,
+ selectCoverImageName,
+ stripInstallationState,
+} from './projectAssets';
const imageRef = (imageName: string) => ({ height: 512, imageName, width: 512 });
@@ -29,6 +36,31 @@ const galleryInstance = (recentImageNames: string[]) => ({
const noMappings = { images: new Map<string, string>(), videos: new Map<string, string>() };
+it('holds media from unsaved editor state and undo history', () => {
+ const refs = collectHeldAssetRefs([
+ {
+ canvas: { imageName: 'unsaved.png' },
+ queue: { items: [{ imageName: 'completed-job.png' }] },
+ widgetInstances: galleryInstance(['gallery-recent.png']),
+ undoRedo: { past: [{ project: { imageName: 'undo.png', video_name: 'undo.mp4' } }] },
+ },
+ ]);
+
+ expect(refs.images).toEqual(new Set(['unsaved.png', 'undo.png']));
+ expect(refs.videos).toEqual(new Set(['undo.mp4']));
+});
+
+it('partitions a long editor hold without dropping names or exceeding either API limit', () => {
+ const images = Array.from({ length: 50_001 }, (_, index) => `image-${index}`);
+ const videos = ['first.mp4', 'second.mp4'];
+ const batches = partitionHeldAssetNames(images, videos);
+
+ expect(batches).toHaveLength(2);
+ expect(batches.every((batch) => batch.images.length <= 50_000 && batch.videos.length <= 50_000)).toBe(true);
+ expect(batches.flatMap((batch) => batch.images)).toEqual(images);
+ expect(batches.flatMap((batch) => batch.videos)).toEqual(videos);
+});
+
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 5332eaef8f..8ce5b4f345 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -94,6 +94,59 @@ export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>):
return refs;
};
+/** Open editors hold live content and undo state, but not completed queue/event or gallery history. */
+export const collectHeldAssetRefs = (projects: readonly object[]): ProjectAssetRefs => {
+ const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };
+ const pending: unknown[] = [];
+ for (const project of projects) {
+ for (const [key, value] of Object.entries(project)) {
+ if (!PROJECT_HISTORY_ROOT_KEYS.has(key)) {
+ pending.push(value);
+ }
+ }
+ }
+ while (pending.length > 0) {
+ const node = pending.pop();
+ if (Array.isArray(node)) {
+ for (const value of node) {
+ pending.push(value);
+ }
+ } else if (isRecord(node)) {
+ for (const [key, value] of Object.entries(node)) {
+ if (key === 'recentImages' || GALLERY_SELECTION_KEYS.has(key)) {
+ continue;
+ }
+ if (typeof value === 'string' && value.length <= 255) {
+ 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;
+};
+
+/** Each lease request must stay within the backend's per-kind 50,000-name limit. */
+export const partitionHeldAssetNames = (
+ images: readonly string[],
+ videos: readonly string[]
+): { images: string[]; videos: string[] }[] => {
+ const batchSize = 50_000;
+ const batches: { images: string[]; videos: string[] }[] = [];
+ for (let start = 0; start < Math.max(images.length, videos.length); start += batchSize) {
+ batches.push({
+ images: images.slice(start, start + batchSize),
+ videos: videos.slice(start, start + batchSize),
+ });
+ }
+ return batches;
+};
+
/** `{ drop: true }` removes the key, `{ value }` replaces it, `null` recurses into it. */
type NodeVisit = { drop: true } | { value: unknown } | null;
diff --git a/tests/app/routers/test_intermediates.py b/tests/app/routers/test_intermediates.py
index 993cff6d9e..5e8cf4d88c 100644
--- a/tests/app/routers/test_intermediates.py
+++ b/tests/app/routers/test_intermediates.py
@@ -78,6 +78,8 @@ def test_every_route_requires_authentication(enable_multiuser: Any, client: Test
)
assert client.get("/api/v1/intermediates/operations/x").status_code == status.HTTP_401_UNAUTHORIZED
assert client.post("/api/v1/intermediates/operations/x/retry").status_code == status.HTTP_401_UNAUTHORIZED
+ assert client.put("/api/v1/intermediates/holds/tab", json={"images": ["x.png"]}).status_code == 401
+ assert client.delete("/api/v1/intermediates/holds/tab").status_code == 401
def test_non_admins_see_only_their_rows_and_cannot_widen_scope(
@@ -184,6 +186,44 @@ def test_mutations_are_refused_during_image_storage_maintenance(
assert started.json()["detail"] == "Image storage maintenance is active"
+def test_replayed_start_succeeds_during_image_storage_maintenance(
+ storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str
+) -> None:
+ user1 = _user_id(mock_invoker, "[email protected]")
+ _seed_intermediate(mock_invoker, "replay.png", user1)
+ preview = client.post(
+ "/api/v1/intermediates/previews",
+ json={"mode": "safe", "scope": {"kind": "owner", "user_id": user1}},
+ headers=_auth(user1_token),
+ ).json()
+ request = {"preview_id": preview["preview_id"], "idempotency_key": "replay-maintenance"}
+ first = client.post("/api/v1/intermediates/operations", json=request, headers=_auth(user1_token))
+ assert first.status_code == 202
+ _wait(client, user1_token, first.json()["operation_id"])
+ mock_invoker.services.image_moves.is_maintenance_active.return_value = True
+
+ replay = client.post("/api/v1/intermediates/operations", json=request, headers=_auth(user1_token))
+
+ assert replay.status_code == 202
+ assert replay.json()["operation_id"] == first.json()["operation_id"]
+
+
+def test_hold_is_account_scoped_at_the_http_boundary(
+ storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str, user2_token: str
+) -> None:
+ user1 = _user_id(mock_invoker, "[email protected]")
+ _seed_intermediate(mock_invoker, "held.png", user1)
+ assert (
+ client.put(
+ "/api/v1/intermediates/holds/tab", json={"images": ["held.png"]}, headers=_auth(user1_token)
+ ).status_code
+ == 204
+ )
+ assert client.delete("/api/v1/intermediates/holds/tab", headers=_auth(user2_token)).status_code == 204
+ summary = client.get("/api/v1/intermediates/summary", headers=_auth(user1_token)).json()
+ assert summary["items"][0]["images"]["active"] == 1
+
+
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/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.py
index ecdcc1a1f6..e18925913f 100644
--- a/tests/app/services/intermediates/test_intermediates_service.py
+++ b/tests/app/services/intermediates/test_intermediates_service.py
@@ -268,6 +268,19 @@ def test_summary_scopes_owners_search_sort_and_pages(invoker: Invoker, service:
assert [row.project_name for row in by_name.items] == ["Beta"]
assert by_name.total == 2 and by_name.totals.reclaimable_bytes == 30
+ focused = service.get_summary(
+ ALICE,
+ owner_id=None,
+ project_id=beta,
+ search=None,
+ sort="project_name",
+ descending=False,
+ offset=0,
+ limit=1,
+ )
+ assert [(row.project_id, row.project_name) for row in focused.items] == [(beta, "Beta")]
+ assert focused.total == 1
+
searched = service.get_summary(
ADMIN, owner_id=None, search="bo", sort="project_name", descending=False, offset=0, limit=50
)
@@ -635,6 +648,30 @@ def test_a_purge_failure_counts_as_pending_disk_cleanup_not_reclaimed(
assert len(list(invoker.services.image_files.image_root.glob(".delete_*"))) == 1
+def test_failed_video_purge_is_recovered_after_restart(invoker: Invoker, monkeypatch: pytest.MonkeyPatch) -> None:
+ _seed_video(invoker, "recover.mp4")
+ files = invoker.services.video_files
+ path = files.get_path("recover.mp4")
+ original_unlink = Path.unlink
+ failed_once = False
+
+ def fail_once(candidate: Path, *args, **kwargs) -> None:
+ nonlocal failed_once
+ if candidate == path and not failed_once:
+ failed_once = True
+ raise OSError("video file temporarily locked")
+ original_unlink(candidate, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", fail_once)
+ result = invoker.services.videos.delete_intermediates_by_names(["recover.mp4"])
+
+ assert result.deleted_names == ["recover.mp4"]
+ assert result.purge_deferred == ["recover.mp4"]
+ assert path.exists()
+ DiskVideoFileStorage(path.parent).start(invoker)
+ assert not path.exists()
+
+
def test_cleanup_refuses_to_start_or_continue_during_storage_maintenance(
invoker: Invoker, service: IntermediatesService, monkeypatch
) -> None:
@@ -856,8 +893,10 @@ def test_a_save_cannot_slip_between_the_final_check_and_the_delete(
guard_may_finish = threading.Event()
delete_committed_at: list[float] = []
- def slow_guard_factory(kind, *, mode, allowed_user_ids):
- guard = real_guard_factory(kind, mode=mode, allowed_user_ids=allowed_user_ids)
+ def slow_guard_factory(kind, *, mode, allowed_user_ids, confirmed_references=None):
+ guard = real_guard_factory(
+ kind, mode=mode, allowed_user_ids=allowed_user_ids, confirmed_references=confirmed_references
+ )
def paused(cursor, names):
guard_entered.set()
@@ -937,3 +976,166 @@ def test_active_inputs_survive_a_rolled_back_batch(
assert operation.progress.failed_images == 1
assert _exists(invoker, "consumed.png"), "an input of pending work was deleted after a rolled-back batch"
+
+
+def test_force_clear_keeps_a_newly_referenced_target(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "force-race.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ assert preview.affected_documents == []
+ _project(invoker, "alice", "Saved after preview", {"imageName": "force-race.png"})
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="force-race"), ALICE
+ )
+ finished = _wait(service, started.operation_id)
+
+ assert finished.progress.retained_images == 1
+ assert _exists(invoker, "force-race.png")
+
+
+def test_browser_hold_protects_unsaved_and_undo_references(invoker: Invoker, service: IntermediatesService) -> None:
+ from invokeai.app.services.intermediates.intermediates_common import IntermediatesBrowserHoldRequest
+
+ _seed_image(invoker, "browser-only.png")
+ service.replace_browser_hold(ALICE, "tab-1", IntermediatesBrowserHoldRequest(images=["browser-only.png"]))
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ assert preview.impact.keep_active_images == 1
+ assert preview.impact.delete_images == 0
+
+ service.release_browser_hold(BOB, "tab-1")
+ still_held = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert still_held.impact.keep_active_images == 1
+ service.release_browser_hold(ALICE, "tab-1")
+ service.replace_browser_hold(BOB, "tab-2", IntermediatesBrowserHoldRequest(images=["browser-only.png"]))
+ available = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert available.impact.delete_images == 1
+
+
+def test_operation_receipt_and_retry_survive_restart(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ _seed_image(invoker, "restart-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"))
+ )
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="restart-key"), ALICE
+ )
+ finished = _wait(service, started.operation_id)
+ assert finished.progress.unresolved_images == 1
+ service.stop()
+
+ restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))
+ invoker.services.intermediates = restored
+ restored.start(invoker)
+ try:
+ assert restored.get_operation(finished.operation_id, ALICE).progress.unresolved_images == 1
+ replay = restored.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="restart-key"), ALICE
+ )
+ assert replay.operation_id == finished.operation_id
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
+ retry = restored.retry_operation(finished.operation_id, ALICE)
+ assert _wait(restored, retry.operation_id).progress.deleted_images == 1
+ assert restored.retry_operation(finished.operation_id, ALICE).operation_id == retry.operation_id
+ assert not _exists(invoker, "restart-flaky.png")
+ finally:
+ restored.stop()
+
+
+def test_force_confirmation_guard_survives_failed_batch_and_restart(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _seed_image(invoker, "force-retry.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ real_delete = invoker.services.images.delete_intermediates_by_names
+ monkeypatch.setattr(
+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))
+ )
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="force-retry"), ALICE
+ )
+ assert _wait(service, started.operation_id).progress.unresolved_images == 1
+ service.stop()
+ _project(invoker, "alice", "New reference", {"imageName": "force-retry.png"})
+
+ restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))
+ invoker.services.intermediates = restored
+ restored.start(invoker)
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)
+ try:
+ retry = restored.retry_operation(started.operation_id, ALICE)
+ result = _wait(restored, retry.operation_id)
+ assert result.progress.retained_images == 1
+ assert _exists(invoker, "force-retry.png")
+ finally:
+ restored.stop()
+
+
+def test_measurement_skip_set_does_not_starve_later_rows(invoker: Invoker, service: IntermediatesService) -> None:
+ records = service._records
+ for index in range(501):
+ _seed_image(invoker, f"unmeasurable-{index}.png", with_file=False)
+ invoker.services.image_records.set_file_size_bytes(f"unmeasurable-{index}.png", None)
+ _seed_image(invoker, "later-measurable.png", with_file=False)
+ invoker.services.image_records.set_file_size_bytes("later-measurable.png", None)
+
+ records.mark_unmeasurable("image", [f"unmeasurable-{index}.png" for index in range(501)])
+
+ assert records.next_unmeasured("image", 1) == [("later-measurable.png", "")]
+
+
+def test_receipt_write_failure_does_not_strand_the_accepted_queue(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ original_ensure_worker = service._ensure_worker
+ monkeypatch.setattr(service, "_ensure_worker", lambda: None)
+ operation_ids = []
+ for index in range(2):
+ _seed_image(invoker, f"queued-{index}.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=f"queued-{index}"), ALICE
+ )
+ operation_ids.append(started.operation_id)
+
+ real_save = service._records.save_operation
+ failures = 0
+
+ def fail_two_writes(*args, **kwargs):
+ nonlocal failures
+ if failures < 2:
+ failures += 1
+ raise OSError("storage temporarily unavailable")
+ return real_save(*args, **kwargs)
+
+ monkeypatch.setattr(service._records, "save_operation", fail_two_writes)
+ monkeypatch.setattr(service, "_ensure_worker", original_ensure_worker)
+ service._ensure_worker()
+
+ assert _wait(service, operation_ids[0]).status == "failed"
+ assert _wait(service, operation_ids[1]).status == "completed"
+
+
+def test_large_single_row_clears_in_bounded_batches_past_protected_items(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "MAX_OPERATION_TARGETS", 2)
+ _seed_image(invoker, "protected-first.png")
+ _project(invoker, "alice", "Uses image", {"imageName": "protected-first.png"})
+ for index in range(3):
+ _seed_image(invoker, f"eligible-{index}.png")
+
+ first, first_result = _run(service, ALICE, _owner("alice"))
+ assert first.has_more_eligible
+ assert first.impact.delete_images == 2
+ assert first.impact.keep_referenced_images == 1
+ assert first_result.progress.deleted_images == 2
+
+ second, second_result = _run(service, ALICE, _owner("alice"))
+ assert not second.has_more_eligible
+ assert second.impact.delete_images == 1
+ assert second_result.progress.deleted_images == 1
+ assert _exists(invoker, "protected-first.png")
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 764564ec29..260ca46f32 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
@@ -57,6 +57,15 @@ def test_adds_provenance_and_size_columns(cursor: sqlite3.Cursor) -> None:
assert {"project_id", "file_size_bytes"} <= _columns(cursor, "images")
assert {"project_id", "file_size_bytes"} <= _columns(cursor, "videos")
assert "project_id" in _columns(cursor, "session_queue")
+ assert {"operation_id", "caller_user_id", "idempotency_key", "state_json"} <= _columns(
+ cursor, "intermediates_operations"
+ )
+ assert {"user_id", "lease_id", "media_kind", "media_name", "expires_at"} <= _columns(
+ cursor, "intermediates_browser_holds"
+ )
+ assert {"operation_id", "media_kind", "media_name", "size_bytes", "confirmed_refs_json"} <= _columns(
+ cursor, "intermediates_operation_targets"
+ )
# Existing media stays unassigned and unmeasured rather than guessed.
cursor.execute("INSERT INTO images (image_name) VALUES ('old.png');")
diff --git a/tests/app/services/workflow_records/test_workflow_media_references.py b/tests/app/services/workflow_records/test_workflow_media_references.py
index 2f7571f78f..f7edb6945f 100644
--- a/tests/app/services/workflow_records/test_workflow_media_references.py
+++ b/tests/app/services/workflow_records/test_workflow_media_references.py
@@ -3,10 +3,12 @@
import pytest
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.media_references import extract_media_references
from invokeai.app.services.workflow_records.workflow_records_common import (
Workflow,
WorkflowCategory,
WorkflowMeta,
+ WorkflowRecordDTO,
WorkflowWithoutID,
)
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
@@ -59,3 +61,24 @@ def test_an_update_refused_by_ownership_leaves_the_index_alone(workflow_records:
workflow_records.update(Workflow(**_workflow("stolen.png").model_dump(), id=created.workflow_id), user_id="user-2")
assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "input.png")}
+
+
+def test_visibility_change_keeps_the_reference_index_of_the_document_it_writes(
+ workflow_records: SqliteWorkflowRecordsStorage, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ created = workflow_records.create(_workflow("old.png"), user_id="user-1")
+ original_get = workflow_records.get
+
+ def concurrent_edit(workflow_id: str) -> WorkflowRecordDTO:
+ previous = original_get(workflow_id)
+ monkeypatch.setattr(workflow_records, "get", original_get)
+ workflow_records.update(Workflow(**_workflow("new.png").model_dump(), id=workflow_id), user_id="user-1")
+ return previous
+
+ monkeypatch.setattr(workflow_records, "get", concurrent_edit)
+ workflow_records.update_is_public(created.workflow_id, True, user_id="user-1")
+ actual = original_get(created.workflow_id)
+
+ assert _references(workflow_records, created.workflow_id) == {
+ ("user-1", "image", name) for name in extract_media_references(actual.workflow.model_dump()).images
+ }