Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(intermediates): protect active and undo media during cleanup
Josh Corbett5bb063087315
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdxindex ca53d60ec5..9f28210183 100644--- a/docs/src/content/docs/features/intermediates.mdx+++ b/docs/src/content/docs/features/intermediates.mdx@@ -19,7 +19,7 @@ A normal clear deletes only safe items. It always keeps:- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job;- 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 the open webv2 editor still references, including unsaved edits and available 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.@@ -29,13 +29,13 @@ A single preview includes at most 50,000 eligible items. If more remain, the conEvery 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.+An open editor refreshes its browser hold every five minutes and when the tab becomes visible. It releases names removed from the current projects and undo history. 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 resultsCleanup 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.+The server accepts at most eight active operations at a time. Wait for one to finish before confirming more cleanup if that limit is reached. If unresolved targets fill the recovery limit, retry them before starting another cleanup; the server keeps their receipts rather than silently discarding them.## Permissionsdiff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.pyindex 158d5703a1..9d1f730a17 100644--- a/invokeai/app/services/intermediates/intermediates_default.py+++ b/invokeai/app/services/intermediates/intermediates_default.py@@ -112,6 +112,7 @@ class IntermediatesService(IntermediatesServiceBase):self._idempotency: dict[tuple[str, str], tuple[str, str]] = {}self._pending: "queue.Queue[str]" = queue.Queue()self._measure_requested = threading.Event()+ self._measure_due_at: Optional[float] = Noneself._stop = threading.Event()self._worker: Optional[threading.Thread] = None@@ -120,6 +121,7 @@ class IntermediatesService(IntermediatesServiceBase):def start(self, invoker: Invoker) -> None:self._invoker = invokerself._stop.clear()+ self._measure_due_at = Nonewith self._lock:for user_id, preview_id, key, state in self._records.load_operations():dto = IntermediatesOperation.model_validate(state["dto"])@@ -489,6 +491,7 @@ class IntermediatesService(IntermediatesServiceBase):preview = self._previews.get(request.preview_id)if preview is None or preview.caller_user_id != caller.user_id:raise IntermediatesPreviewNotFoundError("Preview expired or unknown; request a new one")+ self._require_operation_capacity(len(preview.targets["image"]) + len(preview.targets["video"]))# Single use: a second confirmation of the same preview must go through a new preview.del self._previews[request.preview_id]@@ -552,6 +555,7 @@ class IntermediatesService(IntermediatesServiceBase):raise IntermediatesUnavailableError("The operation has nothing left to retry")# A retry is authorized as the retrying caller, never as the original one.self._authorize_scope(original.dto.scope, caller)+ self._require_operation_capacity(len(unresolved["image"]) + len(unresolved["video"]), replacing=original)operation = self._register_operation_locked(caller=caller,mode=original.dto.mode,@@ -634,6 +638,29 @@ class IntermediatesService(IntermediatesServiceBase):for name, size in names.items()]+ def _can_prune_operation_locked(self, operation: _Operation) -> bool:+ if operation.dto.status not in ("completed", "failed") or any(operation.unresolved.values()):+ return False+ retry_id = operation.dto.retried_by_operation_id+ retry = self._operations.get(retry_id) if retry_id is not None else None+ return retry is None or retry.dto.status not in ("pending", "running")++ def _require_operation_capacity(self, incoming_targets: int, *, replacing: Optional[_Operation] = None) -> None:+ outstanding = sum(+ len(operation.unresolved["image"]) + len(operation.unresolved["video"])+ for operation in self._operations.values()+ )+ if replacing is not None:+ outstanding -= len(replacing.unresolved["image"]) + len(replacing.unresolved["video"])+ if outstanding + incoming_targets > MAX_RETAINED_TARGETS:+ raise IntermediatesUnavailableError("Retry unresolved cleanup targets before starting more cleanup")+ if (+ len(self._operations) >= MAX_RETAINED_OPERATIONS+ and replacing is None+ and not any(self._can_prune_operation_locked(operation) for operation in self._operations.values())+ ):+ raise IntermediatesUnavailableError("Retry unresolved cleanup operations before starting more cleanup")+def _prune_operations_locked(self) -> None:evicted: list[str] = []retained_order = list(self._operation_order)@@ -645,11 +672,7 @@ class IntermediatesService(IntermediatesServiceBase):oldest = Nonefor 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")- ):+ if self._can_prune_operation_locked(candidate):oldest = operation_idbreakif oldest is None:@@ -707,7 +730,9 @@ class IntermediatesService(IntermediatesServiceBase):try:operation_id = self._pending.get(timeout=0.5)except queue.Empty:- if self._measure_requested.is_set():+ if self._measure_requested.is_set() or (+ self._measure_due_at is not None and time.monotonic() >= self._measure_due_at+ ):self._measure_once()continueif not operation_id:@@ -865,12 +890,14 @@ class IntermediatesService(IntermediatesServiceBase):def _measure_once(self) -> None:"""Measures a bounded batch of unmeasured intermediates; clears the request when none remain."""self._measure_requested.clear()+ self._measure_due_at = Noneimage_moves = getattr(self._services, "image_moves", None)if image_moves is not None and image_moves.is_maintenance_active():# Files are being relocated; a measurement now could record a missing file as empty.returntry:remaining = False+ retry_young = Falsefor kind, files, records in (("image", self._services.image_files, self._services.image_records),("video", self._services.video_files, self._services.video_records),@@ -900,10 +927,16 @@ class IntermediatesService(IntermediatesServiceBase):records.set_file_sizes_bytes(sizes)if len(pending) == MEASURE_BATCH_SIZE:remaining = True+ elif self._records.next_unmeasured(cast(MediaKind, kind), 1):+ # All older rows were measured or skipped; a new row still needs its file+ # to be written before measuring it. Wake after the minimum age has elapsed.+ retry_young = Trueif remaining:self._measure_requested.set()# Yield the database lock between batches so generation and saves keep flowing.time.sleep(0.05)+ elif retry_young:+ self._measure_due_at = time.monotonic() + MEASURE_MIN_AGE_SECONDSexcept Exception as error:self._logger.warning(f"Measuring intermediate file sizes failed; will retry on demand: {error}")diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.pyindex ad18745a19..a2b3423c9c 100644--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py@@ -79,9 +79,9 @@ class IntermediatesRecordsSqlite:def __init__(self, db: SqliteDatabase) -> None:self._db = db# Media names an active queue item's session names, keyed by item id and stamped with the- # row's status, status sequence, session length and updated_at: a session rewritten while- # the item stays active (a workflow-call parent resuming with its child's outputs) is- # re-scanned. Entries live as long as the item is active. This cache is derived from committed+ # row's status and monotonic session revision: a session rewritten while the item stays+ # active (a workflow-call parent resuming with its child's outputs) is re-scanned. Entries+ # live as long as the item is active. This cache is derived from committed# rows only, so it is safe across a rolled-back transaction; the temp table is not, which is# why it is rebuilt on every call rather than skipped on an unchanged set.self._active_inputs: dict[int, tuple[str, set[str], set[str]]] = {}@@ -296,7 +296,7 @@ class IntermediatesRecordsSqlite:statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)cursor.execute(f"""--sql- SELECT item_id, status || ':' || COALESCE(status_sequence, 0) || ':' || LENGTH(session) || ':' || updated_at+ SELECT item_id, status || ':' || COALESCE(session_revision, 0)FROM session_queue WHERE status IN ({statuses});""")@@ -315,7 +315,7 @@ class IntermediatesRecordsSqlite:cursor.execute(f"""--sqlSELECT item_id,- status || ':' || COALESCE(status_sequence, 0) || ':' || LENGTH(session) || ':' || updated_at,+ status || ':' || COALESCE(session_revision, 0),sessionFROM session_queue WHERE item_id IN ({placeholders});""",@@ -416,9 +416,16 @@ class IntermediatesRecordsSqlite:def has_unmeasured_intermediates(self) -> bool:with self._db.transaction() as cursor:- for table, _, _ in _TABLES.values():+ cursor.execute(+ "CREATE TEMP TABLE IF NOT EXISTS intermediates_unmeasurable "+ "(kind TEXT, name TEXT, PRIMARY KEY(kind, name));"+ )+ for kind, (table, name_column, _) in _TABLES.items():cursor.execute(- f"SELECT 1 FROM {table} WHERE is_intermediate = TRUE AND file_size_bytes IS NULL LIMIT 1;"+ f"SELECT 1 FROM {table} m WHERE m.is_intermediate = TRUE AND m.file_size_bytes IS NULL "+ f"AND NOT EXISTS (SELECT 1 FROM temp.intermediates_unmeasurable u "+ f"WHERE u.kind = ? AND u.name = m.{name_column}) LIMIT 1;",+ (kind,),)if cursor.fetchone() is not None:return Truediff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_track_queue_session_revision.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_track_queue_session_revision.pynew file mode 100644index 0000000000..b1ae94bd82--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_track_queue_session_revision.py@@ -0,0 +1,31 @@+"""Give active queue sessions a monotonic revision for cleanup's media-input cache."""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++def _track_queue_session_revision(cursor: sqlite3.Cursor) -> None:+ cursor.execute("PRAGMA table_info(session_queue);")+ if "session_revision" not in {row[1] for row in cursor.fetchall()}:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN session_revision INTEGER NOT NULL DEFAULT 0;")+ cursor.execute(+ """--sql+ CREATE TRIGGER IF NOT EXISTS tg_session_queue_session_revision+ AFTER UPDATE OF session ON session_queue+ FOR EACH ROW+ WHEN NEW.session IS NOT OLD.session+ BEGIN+ UPDATE session_queue SET session_revision = OLD.session_revision + 1+ WHERE item_id = NEW.item_id;+ END;+ """+ )+++def build_migration() -> Migration:+ return Migration(+ id="2026_09_23_track_queue_session_revision",+ depends_on="2026_09_22_index_unmeasured_intermediates",+ callback=_track_queue_session_revision,+ )diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 21a4e32d26..130163ac4e 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4287,6 +4287,7 @@"list": {"selectAll": "Select all","selectRow": "Select {{name}}",+ "selectRowForOwner": "Select {{name}} for {{owner}} (account {{userId}})","delete": "Delete","used": "Used","unused": "Unused",diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsxindex a7a2d4e8ca..3b3adbaa89 100644--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx@@ -6,6 +6,7 @@ import { useSearch } from '@tanstack/react-router';import { preloadBootWidgets } from '@workbench/bootWidgetPreload';import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';import { WorkbenchCommandPalette } from '@workbench/palette/WorkbenchCommandPalette';+import { getCanvasHeldAssetRefs } from '@workbench/projects/projectAssets';import { WorkbenchShell } from '@workbench/shell';import { WidgetHosts } from '@workbench/widget-frame/WidgetHosts';import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';@@ -37,7 +38,7 @@ export const WorkbenchApp = () => {useMountEffect(preloadBootWidgets);return (- <WorkbenchProvider loadOptions={loadOptions}>+ <WorkbenchProvider getCanvasHeldAssetRefs={getCanvasHeldAssetRefs} loadOptions={loadOptions}><WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}><BootWidgetHintController /><GenerateWidgetSyncRuntime />diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.tsindex 7f8841bbc1..897a053017 100644--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts@@ -67,7 +67,8 @@ export interface SelectionSummary {export const summarizeSelection = (selection: IntermediatesSelection,totals: { rows: number; safeImages: number; safeVideos: number; reclaimableBytes: number; unknownSizeCount: number },- matchingRows?: readonly IntermediatesRow[]+ matchingRows?: readonly IntermediatesRow[],+ visibleRows: readonly IntermediatesRow[] = []): SelectionSummary | null => {if (selection.mode === 'all-matching') {if (selection.excluded.size > 0) {@@ -108,7 +109,9 @@ export const summarizeSelection = (unknownSizeCount: 0,};- for (const row of selection.rows.values()) {+ const freshRows = new Map(visibleRows.map((row) => [getIntermediatesRowKey(row), row]));+ for (const [key, snapshot] of selection.rows) {+ const row = freshRows.get(key) ?? snapshot;summary.rows += 1;summary.safeImages += row.images.safe;summary.safeVideos += row.videos.safe;diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts b/invokeai/frontend/webv2/src/features/intermediates/data/queries.tsindex 23883f1926..57f87894f6 100644--- a/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts@@ -25,6 +25,7 @@ export const intermediatesSummaryQueryOptions = (params: IntermediatesSummaryParqueryOptions<IntermediatesSummary>({queryFn: ({ signal }) => fenced(owner, (fencedSignal) => getIntermediatesSummary(params, fencedSignal), signal),queryKey: intermediatesKeys.summary(owner, params),+ refetchInterval: (query) => (query.state.data?.measuring ? 5_000 : false),staleTime: 15_000,});diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsxindex c7d383b272..d64a7ba5b1 100644--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx@@ -104,7 +104,15 @@ export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }:onClick={() => onToggleRow(row)}><Checkbox.Root- aria-label={t('intermediates.list.selectRow', { name: label })}+ aria-label={+ showOwner+ ? t('intermediates.list.selectRowForOwner', {+ name: label,+ owner: getOwnerLabel(row),+ userId: row.userId,+ })+ : t('intermediates.list.selectRow', { name: label })+ }checked={selected}colorPalette="accent"size="xs"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.tsxindex 284690c8da..5e822c289c 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@@ -243,6 +243,29 @@ describe('IntermediatesManager', () => {expect(host.textContent).not.toContain('intermediates.owner.showMine');});+ it('identifies the account in repeated admin row selections', async () => {+ dependencies.getIntermediatesSummary.mockImplementation((params: { ownerId: string | null }) =>+ Promise.resolve(+ summaryOf(+ params.ownerId+ ? [row(null, null, 1)]+ : [row(null, null, 1), { ...row(null, null, 1), userDisplayName: 'Alice', userId: 'bob' }]+ )+ )+ );+ await renderManager({ canClearOthersIntermediates: true });+ await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.owner.showEveryone"]')!.click());+ await vi.waitFor(() => expect(host.querySelectorAll('[role="list"] li')).toHaveLength(2));++ const names = [...host.querySelectorAll('[role="list"] li [aria-label]')].map((element) =>+ element.getAttribute('aria-label')+ );+ expect(names).toEqual([+ 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=Alice,userId=alice)',+ 'intermediates.list.selectRowForOwner(name=intermediates.list.unassigned,owner=Alice,userId=bob)',+ ]);+ });+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)]))@@ -449,6 +472,30 @@ describe('IntermediatesManager', () => {expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(true);});+ it('refreshes measured sizes while an open summary is still being measured', async () => {+ const initial = summaryOf([{ ...row('p1', 'Portraits', 1), reclaimableBytes: 0, unknownSizeCount: 1 }]);+ initial.measuring = true;+ initial.totals.reclaimableBytes = 0;+ initial.totals.unknownSizeCount = 1;+ const measured = summaryOf([row('p1', 'Portraits', 1)]);+ dependencies.getIntermediatesSummary.mockImplementationOnce(() => Promise.resolve(initial));+ dependencies.getIntermediatesSummary.mockImplementation(() => Promise.resolve(measured));++ await renderManager();+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.list.unmeasured(count=1)'));+ await act(() => host.querySelector<HTMLButtonElement>('[role="list"] li [aria-label]')!.click());+ expect(host.textContent).toContain('intermediates.selection.estimate');+ await vi.waitFor(+ () => {+ expect(dependencies.getIntermediatesSummary.mock.calls.length).toBeGreaterThan(1);+ expect(host.textContent).toContain('1.0 MB');+ expect(host.textContent).toContain('size=1.0 MB');+ expect(host.querySelector('[aria-label="intermediates.stats.measuringNote"]')).toBeNull();+ },+ { timeout: 8_000 }+ );+ }, 10_000);+it('previews the delete, starts the operation, and reports it once it settles', async () => {await renderManager({ focusProjectId: 'p1' });await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsxindex 04dfb93744..3b712f485e 100644--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx@@ -6,6 +6,7 @@ import type {} from '@features/intermediates/core/types';/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';+import type { TFunction } from 'i18next';import {Badge,@@ -88,6 +89,11 @@ const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;const EMPTY_ROWS: readonly IntermediatesRow[] = [];const EMPTY_TOTALS = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos: 0, unknownSizeCount: 0 };+const formatSummarySize = (bytes: number, unknownCount: number, t: TFunction): string =>+ unknownCount > 0+ ? `${formatBytes(bytes)} ${t('intermediates.list.unmeasured', { count: unknownCount })}`+ : formatBytes(bytes);+let nextIdempotencyKey = 1;const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;@@ -257,9 +263,10 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserIsummarizeSelection(effectiveSelection,totals ?? EMPTY_TOTALS,- matchingSnapshot && !matchingSnapshotQuery.isError && !selectionOverLimit ? matchingSnapshot.items : undefined+ matchingSnapshot && !matchingSnapshotQuery.isError && !selectionOverLimit ? matchingSnapshot.items : undefined,+ rows),- [effectiveSelection, matchingSnapshot, matchingSnapshotQuery.isError, selectionOverLimit, totals]+ [effectiveSelection, matchingSnapshot, matchingSnapshotQuery.isError, rows, selectionOverLimit, totals]);const matchingRowCount = hasExclusions ? matchingSnapshot?.total : totals?.rows;// Select all selects every matching row, including pages not loaded; only a complete selection clears.@@ -581,13 +588,13 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI? t('intermediates.selection.estimate', {count: selectionSummary.rows,images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),- size: formatBytes(selectionSummary.reclaimableBytes),+ size: formatSummarySize(selectionSummary.reclaimableBytes, selectionSummary.unknownSizeCount, t),videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),}): totals? t('intermediates.selection.available', {images: t('intermediates.counts.images', { count: totals.safeImages }),- size: formatBytes(totals.reclaimableBytes),+ size: formatSummarySize(totals.reclaimableBytes, totals.unknownSizeCount, t),videos: t('intermediates.counts.videos', { count: totals.safeVideos }),}): ''}diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.ts b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.tsnew file mode 100644index 0000000000..c24b88e279--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.ts@@ -0,0 +1,160 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { apiFetch } from '@platform/transport/http';+import { expect, it, vi } from 'vitest';++import type { Project } from './projectContracts';+import type { WorkbenchInternalStore } from './workbenchStore';++import { startBrowserIntermediateHold } from './WorkbenchContext';++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ apiFetch: vi.fn().mockResolvedValue(undefined),+}));+it('replaces current holds and releases names removed from the open editor', async () => {+ const fetch = vi.mocked(apiFetch);+ fetch.mockClear();+ let projects = [{ canvas: { imageName: 'first.png' } }] as unknown as Project[];+ let notify: () => void = () => undefined;+ const store = {+ getSnapshot: () => ({ projects }),+ subscribe: (callback: () => void) => {+ notify = callback;+ return () => undefined;+ },+ } as unknown as WorkbenchInternalStore;+ const owner: AccountScope = { accountId: 'alice', epoch: 1, signal: new AbortController().signal, storageSuffix: '' };+ const stop = startBrowserIntermediateHold(store, owner, () => undefined);+ try {+ await vi.waitFor(() =>+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/holds/'),+ expect.objectContaining({+ body: JSON.stringify({ images: ['first.png'], videos: [] }),+ method: 'PUT',+ })+ )+ );++ projects = [{ canvas: { imageName: 'second.png' } }] as unknown as Project[];+ notify();+ await vi.waitFor(() =>+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/holds/'),+ expect.objectContaining({+ body: JSON.stringify({ images: ['second.png'], videos: [] }),+ method: 'PUT',+ })+ )+ );++ projects = [];+ notify();+ await vi.waitFor(() =>+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/holds/'),+ expect.objectContaining({+ method: 'DELETE',+ })+ )+ );+ } finally {+ stop();+ }+});++it('includes names retained by Canvas undo after the current project removes them', async () => {+ const fetch = vi.mocked(apiFetch);+ fetch.mockClear();+ let projects = [{ id: 'project-1', canvas: { imageName: 'first.png' } }] as unknown as Project[];+ let undoNames = ['first.png'];+ let notify: () => void = () => undefined;+ const store = {+ getSnapshot: () => ({ projects }),+ subscribe: (callback: () => void) => {+ notify = callback;+ return () => undefined;+ },+ } as unknown as WorkbenchInternalStore;+ const owner: AccountScope = { accountId: 'alice', epoch: 1, signal: new AbortController().signal, storageSuffix: '' };+ const stop = startBrowserIntermediateHold(store, owner, () => ({ images: undoNames, videos: [] }));+ try {+ await vi.waitFor(() => expect(fetch).toHaveBeenCalled());+ projects = [{ id: 'project-1', canvas: { imageName: 'second.png' } }] as unknown as Project[];+ notify();+ await vi.waitFor(() =>+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/holds/'),+ expect.objectContaining({ body: JSON.stringify({ images: ['first.png', 'second.png'], videos: [] }) })+ )+ );++ undoNames = [];+ projects = [{ id: 'project-1', canvas: { imageName: 'second.png' } }] as unknown as Project[];+ notify();+ await vi.waitFor(() =>+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/holds/'),+ expect.objectContaining({ body: JSON.stringify({ images: ['second.png'], videos: [] }) })+ )+ );+ } finally {+ stop();+ }+});++it('keeps old batches held until every replacement batch is installed', async () => {+ const fetch = vi.mocked(apiFetch);+ fetch.mockClear();+ const imageNames = Array.from({ length: 50_001 }, (_, index) => `b${index.toString().padStart(5, '0')}.png`);+ const boundaryName = imageNames[49_999]!;+ let projects = [{ canvas: { images: imageNames.map((imageName) => ({ imageName })) } }] as unknown as Project[];+ let notify: () => void = () => undefined;+ const store = {+ getSnapshot: () => ({ projects }),+ subscribe: (callback: () => void) => {+ notify = callback;+ return () => undefined;+ },+ } as unknown as WorkbenchInternalStore;+ const held = new Map<string, string[]>();+ let started = false;+ let exposed = false;+ let failSecondStagedBatch = true;+ fetch.mockImplementation((url, options) => {+ if (started && options?.method === 'PUT' && String(url).endsWith('-1-1') && failSecondStagedBatch) {+ failSecondStagedBatch = false;+ throw new Error('temporary network failure');+ }+ if (options?.method === 'PUT') {+ held.set(String(url), (JSON.parse(String(options.body)) as { images: string[] }).images);+ } else if (options?.method === 'DELETE') {+ held.delete(String(url));+ }+ if (started) {+ exposed ||= ![...held.values()].some((names) => names.includes(boundaryName));+ }+ return Promise.resolve(undefined as never);+ });+ const owner: AccountScope = { accountId: 'alice', epoch: 1, signal: new AbortController().signal, storageSuffix: '' };+ const stop = startBrowserIntermediateHold(store, owner, () => undefined);+ try {+ await vi.waitFor(() => expect(held.size).toBe(2));+ const initialLeases = [...held.keys()];+ started = true;+ projects = [+ { canvas: { images: [{ imageName: 'a.png' }, ...imageNames.map((imageName) => ({ imageName }))] } },+ ] as unknown as Project[];+ notify();+ await vi.waitFor(() => expect(failSecondStagedBatch).toBe(false));+ expect(initialLeases.every((lease) => held.has(lease))).toBe(true);+ projects = [...projects];+ notify();+ await vi.waitFor(() => expect(initialLeases.every((lease) => !held.has(lease))).toBe(true));+ expect(exposed).toBe(false);+ } finally {+ stop();+ fetch.mockResolvedValue(undefined as never);+ }+});diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex fc425f67e9..ef4c3bba8d 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -47,30 +47,70 @@ const getNullSnapshot = (): null => null;export const shallowEqual = selectorShallowEqual;+type GetCanvasHeldAssetRefs = (+ projectId: string+) => { images: readonly string[]; videos: readonly string[] } | undefined;+/** An open editor keeps its unsaved and undo media protected while the tab is alive. */-const startBrowserIntermediateHold = (store: WorkbenchInternalStore, owner: AccountScope): (() => void) => {+export const startBrowserIntermediateHold = (+ store: WorkbenchInternalStore,+ owner: AccountScope,+ getCanvasHeldAssetRefs: GetCanvasHeldAssetRefs+): (() => 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[] = [];+ const leaseSignatures: [string[], string[]] = [[], []];+ let activeSlot: 0 | 1 | null = null;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);+ // Project snapshots are immutable; reuse each open project's scan until its object changes.+ const projectRefs = new Map<string, { project: Project; refs: ReturnType<typeof collectHeldAssetRefs> }>();++ const releaseSlot = async (slot: 0 | 1, from = 0): Promise<void> => {+ const signatures = leaseSignatures[slot];+ for (let index = from; index < signatures.length; index += 1) {+ if (!signatures[index] || disposed || owner.signal.aborted) {+ continue;+ }+ try {+ await apiFetch(`/api/v1/intermediates/holds/${encodeURIComponent(`${leaseId}-${slot}-${index}`)}`, {+ method: 'DELETE',+ signal: owner.signal,+ });+ signatures[index] = '';+ } catch {+ // Keep the signature so a later send can retry releasing this lease.+ }+ }+ while (signatures.at(-1) === '') {+ signatures.pop();}- for (const name of refs.videos) {- seenVideos.add(name);+ };++ const putBatch = async (+ slot: 0 | 1,+ index: number,+ batch: { images: string[]; videos: string[] }+ ): Promise<boolean> => {+ if (disposed || owner.signal.aborted) {+ return false;+ }+ try {+ await apiFetch(`/api/v1/intermediates/holds/${encodeURIComponent(`${leaseId}-${slot}-${index}`)}`, {+ body: JSON.stringify(batch),+ headers: { 'Content-Type': 'application/json' },+ method: 'PUT',+ signal: owner.signal,+ });+ leaseSignatures[slot][index] = JSON.stringify([batch.images, batch.videos]);+ return true;+ } catch {+ return false;}};- observe(lastProjects);const send = async (refresh = false): Promise<void> => {if (disposed || owner.signal.aborted) {@@ -85,36 +125,75 @@ const startBrowserIntermediateHold = (store: WorkbenchInternalStore, owner: Accotry {do {pending = false;- observe(store.getSnapshot().projects);- const images = [...seenImages];- const videos = [...seenVideos];+ const projects = store.getSnapshot().projects;+ const refs = { images: new Set<string>(), videos: new Set<string>() };+ const openProjectIds = new Set<string>();+ for (const project of projects) {+ openProjectIds.add(project.id);+ const cached = projectRefs.get(project.id);+ const projectAssets = cached?.project === project ? cached.refs : collectHeldAssetRefs([project]);+ if (cached?.project !== project) {+ projectRefs.set(project.id, { project, refs: projectAssets });+ }+ projectAssets.images.forEach((name) => refs.images.add(name));+ projectAssets.videos.forEach((name) => refs.videos.add(name));+ const retained = getCanvasHeldAssetRefs(project.id);+ retained?.images.forEach((name) => refs.images.add(name));+ retained?.videos.forEach((name) => refs.videos.add(name));+ }+ for (const projectId of projectRefs.keys()) {+ if (!openProjectIds.has(projectId)) {+ projectRefs.delete(projectId);+ }+ }+ const images = [...refs.images].sort();+ const videos = [...refs.videos].sort();const mustRefresh = refresh || pendingRefresh;refresh = false;pendingRefresh = false;- if (!images.length && !videos.length && lastSentSignatures.length === 0) {+ if (!images.length && !videos.length) {+ await releaseSlot(0);+ await releaseSlot(1);+ activeSlot = null;continue;}const batches = partitionHeldAssetNames(images, videos);- for (let index = 0; index < batches.length; index += 1) {- if (disposed || owner.signal.aborted) {- break;+ const signatures = batches.map((batch) => JSON.stringify([batch.images, batch.videos]));+ const current = activeSlot === null ? null : leaseSignatures[activeSlot];+ let trimActive = false;+ if (+ current &&+ current.length === signatures.length &&+ signatures.every((value, index) => value === current[index])+ ) {+ if (mustRefresh) {+ for (let index = 0; index < batches.length; index += 1) {+ await putBatch(activeSlot!, index, batches[index]!);+ }}- const batch = batches[index]!;- const signature = JSON.stringify([batch.images, batch.videos]);- if (!mustRefresh && signature === lastSentSignatures[index]) {- continue;+ trimActive = true;+ } else {+ // Stage all replacement batches under the other lease set. Old names stay protected+ // even when sorting moves them across the per-request batch boundary.+ const nextSlot: 0 | 1 = activeSlot === 0 ? 1 : 0;+ let staged = true;+ for (let index = 0; index < batches.length; index += 1) {+ staged = (await putBatch(nextSlot, index, batches[index]!)) && staged;}- 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 (staged && !disposed && !owner.signal.aborted) {+ const oldSlot = activeSlot;+ activeSlot = nextSlot;+ trimActive = true;+ if (oldSlot !== null) {+ await releaseSlot(oldSlot);+ }+ }+ }+ if (activeSlot !== null) {+ if (trimActive) {+ await releaseSlot(activeSlot, batches.length);}+ await releaseSlot(activeSlot === 0 ? 1 : 0);}if (disposed || owner.signal.aborted) {break;@@ -129,9 +208,7 @@ const startBrowserIntermediateHold = (store: WorkbenchInternalStore, owner: Accoif (projects === lastProjects) {return;}- const changedProjects = projects.filter((project, index) => project !== lastProjects[index]);lastProjects = projects;- observe(changedProjects);if (timer !== null) {clearTimeout(timer);}@@ -162,9 +239,11 @@ const startBrowserIntermediateHold = (store: WorkbenchInternalStore, owner: Accoexport const WorkbenchProvider = ({children,+ getCanvasHeldAssetRefs,loadOptions,}: {children: ReactNode;+ getCanvasHeldAssetRefs: GetCanvasHeldAssetRefs;/** Boot-time session options (deep-linked project, fresh draft). Read once at mount. */loadOptions?: WorkbenchLoadOptions;}) => {@@ -250,7 +329,7 @@ export const WorkbenchProvider = ({});persistenceRuntime.start();- const releaseIntermediateHold = startBrowserIntermediateHold(store, owner);+ const releaseIntermediateHold = startBrowserIntermediateHold(store, owner, getCanvasHeldAssetRefs);return () => {releaseIntermediateHold();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 7cea16741d..5728405ac1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -227,6 +227,7 @@ export interface CanvasHistoryCapability {redo(): void;clearHistory(): void;getEntries(): CanvasHistoryEntries;+ getHeldAssetRefs(): { images: readonly string[]; videos: readonly string[] };/** Replays `offset` steps — negative undoes, positive redoes — clamped to the stacks. */stepBy(offset: number): void;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex d06541ed6f..e4166c862a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -11,6 +11,7 @@ import type { Rect } from '@workbench/canvas-engine/types';import { lookupLayerBelow, mergeDownEligibility } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';@@ -192,6 +193,7 @@ export class BooleanMergeController {apply();this.deps.history.push({bytes: resultRect.width * resultRect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(resultLayer),label: `Boolean ${operation}`,redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex 741f92cd46..ef2cf8d0dd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -10,6 +10,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }@@ -107,6 +108,7 @@ export class CopyLayerController {apply();this.deps.history.push({bytes: baked.rect.width * baked.rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label: 'Copy layer to raster',redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex a8be2ce994..9d4d972a54 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -13,6 +13,7 @@ import type { Rect } from '@workbench/canvas-engine/types';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';export type CropLayerResult =@@ -152,6 +153,7 @@ export class CropLayerController {publish(after, prepared);this.deps.history.push({bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + cropRect.width * cropRect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(before, after),label: 'Crop layer to bbox',redo: () => apply(after, afterPixels),replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 50b8555f2a..79f4d869e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -24,6 +24,7 @@ import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/dimport { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { createEmptyStacks, isGroupNode } from '@workbench/canvas-engine/document/documentTree';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty } from '@workbench/canvas-engine/math/rect';import { compositeDocument } from '@workbench/canvas-engine/render/compositor';@@ -252,6 +253,7 @@ export class ExtractMaskedAreaController {apply();this.deps.history.push({bytes: rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label: 'Extract masked area',redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.tsindex 6d3b5c582a..a1e55e3b44 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts@@ -15,6 +15,7 @@ import type { Rect } from '@workbench/canvas-engine/types';import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer } from '@workbench/canvas-engine/document/layerFactories';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import type { CanvasMutationContext } from './mutationContext';@@ -143,6 +144,7 @@ export class FilterResultController {publish(after, o.ctx.preparePixels(liveLayer.id, rect, pixels), { discardPersistence: true, persist: false });o.ctx.history.push({bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(before, after),label: 'Replace layer with filter result',redo: () => apply(after, afterPixels, { discardPersistence: true, persist: false }),replayFailureAtomic: true,@@ -210,6 +212,7 @@ export class FilterResultController {apply();o.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(copy),label: 'Copy layer filter result',redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.tsindex ab92770df8..d58f4e2811 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts@@ -9,6 +9,7 @@ import type { Rect } from '@workbench/canvas-engine/types';import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer, nextControlLayerName } from '@workbench/canvas-engine/document/layerFactories';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import type { CanvasMutationContext } from './mutationContext';@@ -144,6 +145,7 @@ export class GeneratedResultController {publishSnapshot(after, prepared, { discardPersistence: true, persist: false });o.ctx.history.push({bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(before, after),label: options.historyLabel ?? 'Replace layer with workflow result',redo: () => applySnapshot(after, afterPixels, { discardPersistence: true, persist: false }),replayFailureAtomic: true,@@ -206,6 +208,7 @@ export class GeneratedResultController {publishCopy(prepared);o.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(copy),label:options.target === 'copy-control'? 'Copy workflow result to control layer'diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex b696632e63..cb9bd3cb48 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -22,6 +22,7 @@ import {import { cloneSubtree, collectSubtreeLeaves } from '@workbench/canvas-engine/document/documentTree';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';@@ -324,6 +325,7 @@ export class LayerMutationController {};o.history.push({bytes: historyBytes,+ heldAssetRefs: collectHistoryMediaRefs(duplicates),dispose: () => detachedLease?.release(),label: duplicates.length === 1 ? 'Duplicate layer' : 'Duplicate layers',redo,@@ -390,6 +392,7 @@ export class LayerMutationController {apply();o.history.push({bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label,redo: apply,replayFailureAtomic: true,@@ -453,6 +456,7 @@ export class LayerMutationController {apply(after);o.history.push({bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,+ heldAssetRefs: collectHistoryMediaRefs(before, after),label,redo: () => apply(after),replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.tsindex 43b32ccef3..941b4d05c4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts@@ -9,6 +9,7 @@ import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/docuimport { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceContentRect, isMaskLayer } from '@workbench/canvas-engine/document/sources';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { invert as invertMatrix } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';@@ -81,6 +82,7 @@ export class MaskLayerController {applyClear();this.deps.history.push({bytes: (before?.data.byteLength ?? 0) + 256,+ heldAssetRefs: collectHistoryMediaRefs(originalBitmap),label: 'Clear mask',redo: applyClear,undo: applyRestore,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.tsindex 1ca27a74ad..94dadff63f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts@@ -19,6 +19,7 @@ import {nextRegionalGuidanceFillColor,nextRegionalGuidanceName,} from '@workbench/canvas-engine/document/layerFactories';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';export type {CommitMaskImageResult,@@ -112,6 +113,7 @@ export class MaskResultController {apply();o.history.push({bytes: 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label: options.target === 'inpaint_mask' ? 'Create inpaint mask from object' : 'Create region from object',redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex a337ec3df4..95cd902119 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -16,6 +16,7 @@ import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionimport { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';import { canMergeSelectedRasters, getMergeVisibleRasterLeaves } from '@workbench/canvas-engine/document/mergeVisible';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';@@ -303,6 +304,7 @@ export class MergeLayerController {apply();this.deps.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(contributors),label: 'Merge visible',redo: apply,replayFailureAtomic: true,@@ -516,6 +518,7 @@ export class MergeLayerController {applyPrepared();this.deps.ctx.history.push({bytes: historyBytes,+ heldAssetRefs: collectHistoryMediaRefs(rawSnapshots.map(({ layer }) => layer)),label: 'Merge selected layers',redo,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.tsindex 7d82c64e92..2eabcec7d4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts@@ -15,6 +15,7 @@ import type { SelectionState } from '@workbench/canvas-engine/selection/selectioimport type { Rect, Vec2 } from '@workbench/canvas-engine/types';import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';@@ -114,6 +115,7 @@ export class NewRasterLayerController {apply();this.deps.history.push({bytes: rect.width * rect.height * 4 + 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label,redo: apply,replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex 797b003dd9..5e9e14ab4d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -7,6 +7,7 @@ import type { RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers'import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect, isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { rasterizeSource } from '@workbench/canvas-engine/render/rasterizers';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';@@ -92,6 +93,7 @@ export class RasterizeLayerController {apply();this.deps.history.push({bytes: 256,+ heldAssetRefs: collectHistoryMediaRefs(parametricLayer),label: 'Rasterize layer',redo: apply,undo: () =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.tsindex d7af69c7c0..e9c620196e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts@@ -15,6 +15,7 @@ import type { ProjectEvent } from '@workbench/projectContracts';import { getDocumentLayer, getDocumentLeaves, hasDocumentNode } from '@workbench/canvas-engine/document/documentIndex';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';export interface StagedResultControllerOptions {@@ -201,6 +202,7 @@ export class StagedResultController {};o.history.push({bytes: 256,+ heldAssetRefs: collectHistoryMediaRefs(layer),label: continueStaging ? 'Save staged image as disabled layer' : 'Accept staged image',redo: () =>applyLayerStack(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex cf113b36f1..65b70894cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -4168,6 +4168,30 @@ describe('commitStructural', () => {const forward: EngineTestAction = { id: 'a', type: 'setCanvasSelectedLayer' };const inverse: EngineTestAction = { id: null, type: 'setCanvasSelectedLayer' };+ it('keeps a removed image held while Canvas can undo the removal', () => {+ const layer = rasterLayer('L', { imageName: 'older-intermediate.png' });+ const { projectId, store } = createReducerBackedStore({ ...makeDoc(), stacks: stacksFrom([layer]) });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(+ engine.layers.commitStructural(+ 'Remove layer',+ { ids: ['L'], type: 'removeCanvasLayers' },+ { anchor: stackTopAnchor(projectId), layer, type: 'addCanvasLayer' }+ )+ ).toEqual({ status: 'committed' });+ expect(getDocumentLeaves(engine.document.getDocument())).toEqual([]);+ expect(engine.history.getHeldAssetRefs().images).toContain('older-intermediate.png');+ engine.history.clearHistory();+ expect(engine.history.getHeldAssetRefs().images).toEqual([]);+ engine.lifecycle.dispose();+ });+it('dispatches forward immediately and records a reversible history entry', () => {const { store } = createFakeStore(makeDoc());const dispatch = store.dispatch as Mock;@@ -11778,6 +11802,7 @@ describe('commitMaskImageResult', () => {expect(engine.document.getDocument()!.selectedLayerId).toBe('below');expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);+ expect(engine.history.getHeldAssetRefs().images).toContain(resultImage.imageName);engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId)).toEqual(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex b0c739b443..c518476b70 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -2631,6 +2631,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst historyCapability: CanvasHistoryCapability = {clearHistory,getEntries: () => history.entries(),+ getHeldAssetRefs: () => history.heldAssetRefs(),redo,stepBy: stepHistoryBy,undo,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.tsindex b112710d1f..5e801ab677 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts@@ -27,4 +27,18 @@ describe('createDocumentPatchEntry', () => {expect(heavier.bytes).toBe(4096);expect(heavier.label).toBe('Cycle');});++ it('retains media names embedded in an undoable removed layer', () => {+ const removedLayer = {+ type: 'addCanvasLayer',+ layer: { source: { imageName: 'removed.png', video_name: 'source.mp4' } },+ } as unknown as CanvasProjectMutation;+ const entry = createDocumentPatchEntry({+ dispatch: vi.fn(),+ forward,+ inverse: removedLayer,+ label: 'Remove layer',+ });+ expect(entry.heldAssetRefs).toEqual({ images: ['removed.png'], videos: ['source.mp4'] });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.tsindex 61ee2367a7..21dd071e0d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts@@ -7,6 +7,8 @@ import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationConimport type { HistoryEntry } from './history';+import { collectHistoryMediaRefs } from './history';+/** Nominal byte cost for a structural entry (small; actions are plain objects). */export const DOCUMENT_PATCH_DEFAULT_BYTES = 256;@@ -32,6 +34,7 @@ export const createDocumentPatchEntry = (opts: CreateDocumentPatchEntryOptions):return {bytes,+ heldAssetRefs: collectHistoryMediaRefs(forward, inverse),label,redo: () => dispatch(forward),undo: () => dispatch(inverse),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.tsindex e31c26ba33..516ef6e805 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts@@ -62,6 +62,20 @@ describe('createHistory: redo cleared on push', () => {});describe('createHistory: entry-count eviction', () => {+ it('keeps undo and redo media held until their entry is evicted', () => {+ const history = createHistory({ maxEntries: 1 });+ const first = { ...makeEntry('remove first', []), heldAssetRefs: { images: ['first.png'], videos: [] } };+ const second = { ...makeEntry('remove second', []), heldAssetRefs: { images: ['second.png'], videos: [] } };+ history.push(first);+ history.undo();+ expect(history.heldAssetRefs().images).toEqual(['first.png']);+ history.redo();+ history.push(second);+ expect(history.heldAssetRefs().images).toEqual(['second.png']);+ history.clear();+ expect(history.heldAssetRefs().images).toEqual([]);+ });+it('evicts the oldest entry beyond the 64-entry budget', () => {const log: string[] = [];const history = createHistory();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.tsindex 06d5926524..2d0fd51f66 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts@@ -10,12 +10,39 @@ export const HISTORY_MAX_ENTRIES = 64;/** Max total bytes retained across the undo + redo stacks before the oldest is evicted (256 MB). */export const HISTORY_BYTE_BUDGET = 256 * 1024 * 1024;+/** Media names captured by an undo entry, including sources no longer in the live document. */+export const collectHistoryMediaRefs = (...values: unknown[]): { images: string[]; videos: string[] } => {+ const images = new Set<string>();+ const videos = new Set<string>();+ const pending: unknown[] = [...values];+ while (pending.length > 0) {+ const value = pending.pop();+ if (typeof value !== 'object' || value === null) {+ continue;+ }+ for (const [key, child] of Object.entries(value)) {+ if (typeof child === 'string' && child.length > 0 && child.length <= 255) {+ if (key === 'imageName' || key === 'image_name') {+ images.add(child);+ } else if (key === 'video_name') {+ videos.add(child);+ }+ } else if (typeof child === 'object' && child !== null) {+ pending.push(child);+ }+ }+ }+ return { images: [...images], videos: [...videos] };+};+/** One reversible step. `bytes` is the (approximate) memory the entry pins, for the budget. */export interface HistoryEntry {/** Human-readable label (e.g. "Brush stroke"). */readonly label: string;/** Approximate retained size in bytes (e.g. before+after ImageData byteLength). */readonly bytes: number;+ /** Media names this entry can restore after they leave the current document. */+ readonly heldAssetRefs?: { readonly images: readonly string[]; readonly videos: readonly string[] };/*** Opts into failure-atomic replay. When true, History moves this entry only* after `undo`/`redo` returns successfully, so a preparation failure remains@@ -74,6 +101,8 @@ export interface History {* what `undo()` reverts), `future` next-redo-first. Fresh arrays per call.*/entries(): { past: readonly string[]; future: readonly string[] };+ /** Union of media references retained by undo and redo entries. */+ heldAssetRefs(): { images: string[]; videos: string[] };/** Subscribes to every stack mutation (push, amend, undo, redo, clear, eviction). Returns an unsubscribe function. */subscribe(listener: () => void): () => void;}@@ -145,6 +174,16 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {past: undoStack.map((entry) => entry.label),});+ const heldAssetRefs = (): { images: string[]; videos: string[] } => {+ const images = new Set<string>();+ const videos = new Set<string>();+ for (const entry of [...undoStack, ...redoStack]) {+ entry.heldAssetRefs?.images.forEach((name) => images.add(name));+ entry.heldAssetRefs?.videos.forEach((name) => videos.add(name));+ }+ return { images: [...images], videos: [...videos] };+ };+const push = (entry: HistoryEntry): void => {// Replaying an entry must never record a new one; drop it defensively.if (applying) {@@ -326,6 +365,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {amendLast,byteSize: () => undoBytes + redoBytes,entries,+ heldAssetRefs,canRetain: (bytes) => Number.isFinite(bytes) && Math.max(0, Math.ceil(bytes)) <= byteBudget,canRedo: () => redoStack.length > 0,canUndo: () => undoStack.length > 0,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.tsindex 10945ccca5..0e1a7b409e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts@@ -44,6 +44,7 @@ describe('createLayerSnapshotEntry', () => {const entry = createLayerSnapshotEntry({ after, apply, before, label: 'Brush stroke' });expect(entry.bytes).toBe(before.pixels!.data.byteLength + after.pixels!.data.byteLength + 256);+ expect(entry.heldAssetRefs?.images).toEqual(['before']);expect(entry.replayFailureAtomic).toBe(true);entry.undo();entry.redo();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.tsindex 9eb31b9a07..22d4d2c818 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts@@ -3,6 +3,8 @@ import type { Rect } from '@workbench/canvas-engine/types';import type { HistoryEntry } from './history';+import { collectHistoryMediaRefs } from './history';+export interface LayerPixelSnapshot {layer: CanvasControlLayerContract | CanvasRasterLayerContractV2;rect: Rect;@@ -57,6 +59,7 @@ export const createLayerSnapshotEntry = ({};return {bytes: (before.pixels?.data.byteLength ?? 0) + (after.pixels?.data.byteLength ?? 0) + 256,+ heldAssetRefs: collectHistoryMediaRefs(beforeSnapshot.layer, afterSnapshot.layer),label,redo: () => apply(afterSnapshot),replayFailureAtomic: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.tsindex cf4ed515ae..c24e7189a0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts@@ -21,6 +21,7 @@ import {} from '@workbench/canvas-operations/generationCompositePlan';import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { getCanvasHeldAssetRefs } from '@workbench/projects/projectAssets';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';@@ -148,10 +149,12 @@ describe('createEngineRegistry', () => {accountLifecycle.activate('user-a');const engine = getOrCreateEngine('shared-project-id', createFakeDeps());const dispose = vi.spyOn(engine.lifecycle, 'dispose');+ expect(getCanvasHeldAssetRefs('shared-project-id')).toEqual({ images: [], videos: [] });accountLifecycle.invalidate();expect(getCanvasEngine('shared-project-id')).toBeUndefined();+ expect(getCanvasHeldAssetRefs('shared-project-id')).toBeUndefined();expect(dispose).toHaveBeenCalledOnce();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.tsindex 83853169d6..657972f941 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts@@ -11,6 +11,7 @@ import {type CanvasEngine,type CanvasEngineOptions,} from '@workbench/canvas-operations/createCanvasEngine';+import { registerCanvasHeldAssetRefs } from '@workbench/projects/projectAssets';/** Engine creation dependencies, minus the project id the registry supplies. */export type EngineDeps = Omit<CanvasEngineOptions, 'projectId'>;@@ -38,6 +39,7 @@ export interface EngineRegistry {interface RegistryEntry {engine: CanvasEngine;+ releaseHeldAssetRefs: () => void;refCount: number;disposeHandle: number | null;generation: number;@@ -53,6 +55,7 @@ const defaultTimers: RegistryTimers = {export const createEngineRegistry = (options: {gracePeriodMs?: number;+ registerHeldAssetRefs?: typeof registerCanvasHeldAssetRefs;timers?: RegistryTimers;} = {}): EngineRegistry => {@@ -80,6 +83,7 @@ export const createEngineRegistry = (return;}entries.delete(projectId);+ entry.releaseHeldAssetRefs();entry.engine.lifecycle.dispose();});}, gracePeriodMs);@@ -93,6 +97,7 @@ export const createEngineRegistry = (entries.clear();for (const entry of ownedEntries) {cancelDisposal(entry);+ entry.releaseHeldAssetRefs();try {entry.engine.lifecycle.dispose();} catch (error) {@@ -118,7 +123,16 @@ export const createEngineRegistry = (return existing.engine;}const engine = createCanvasEngine({ projectId, ...deps });- entries.set(projectId, { cooldown: null, disposeHandle: null, engine, generation: 0, refCount: 1 });+ const releaseHeldAssetRefs =+ options.registerHeldAssetRefs?.(projectId, () => engine.history.getHeldAssetRefs()) ?? (() => undefined);+ entries.set(projectId, {+ cooldown: null,+ disposeHandle: null,+ engine,+ generation: 0,+ refCount: 1,+ releaseHeldAssetRefs,+ });return engine;},releaseEngine: (projectId) => {@@ -139,7 +153,7 @@ export const createEngineRegistry = (};/** The process-wide default registry shared by all widget surfaces. */-const defaultRegistry = createEngineRegistry();+const defaultRegistry = createEngineRegistry({ registerHeldAssetRefs: registerCanvasHeldAssetRefs });registerAccountOwnedResource({clear: defaultRegistry.disposeAll,diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 8ce5b4f345..4df4daf72f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -43,6 +43,22 @@ export interface ProjectAssetRefs {videos: Set<string>;}+type CanvasHeldAssetRefs = { images: readonly string[]; videos: readonly string[] };+const canvasHeldAssetReaders = new Map<string, () => CanvasHeldAssetRefs>();++/** Canvas owns each reader for as long as its engine remains alive. */+export const registerCanvasHeldAssetRefs = (projectId: string, read: () => CanvasHeldAssetRefs): (() => void) => {+ canvasHeldAssetReaders.set(projectId, read);+ return () => {+ if (canvasHeldAssetReaders.get(projectId) === read) {+ canvasHeldAssetReaders.delete(projectId);+ }+ };+};++export const getCanvasHeldAssetRefs = (projectId: string): CanvasHeldAssetRefs | undefined =>+ canvasHeldAssetReaders.get(projectId)?.();+const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.pyindex bab69bd29c..e9c71ec383 100644--- a/tests/app/services/intermediates/test_intermediates_service.py+++ b/tests/app/services/intermediates/test_intermediates_service.py@@ -320,6 +320,24 @@ def test_summary_triggers_measurement_of_unmeasured_sizes(invoker: Invoker, servassert invoker.services.image_records.get("missing.png").file_size_bytes == 0+def test_measurement_retries_when_an_unmeasured_file_is_still_too_new(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(intermediates_default, "MEASURE_MIN_AGE_SECONDS", 1)+ _seed_image(invoker, "young.png", created_at=None)+ invoker.services.image_records.set_file_size_bytes("young.png", None)++ summary = service.get_summary(+ ALICE, owner_id=None, search=None, sort="project_name", descending=False, offset=0, limit=50+ )+ assert summary.measuring is True++ deadline = time.monotonic() + 4+ while time.monotonic() < deadline and invoker.services.image_records.get("young.png").file_size_bytes is None:+ time.sleep(0.02)+ assert invoker.services.image_records.get("young.png").file_size_bytes is not None++# ── previews and policy ──@@ -788,6 +806,28 @@ def test_inputs_added_to_an_active_session_after_it_was_scanned_are_protected(assert second.impact.keep_active_images == 1+def test_cleanup_rechecks_same_length_active_session_rewrites_with_an_unchanged_timestamp(+ invoker: Invoker, service: IntermediatesService+) -> None:+ _seed_image(invoker, "old.png")+ _seed_image(invoker, "new.png")+ item_id = _enqueue_row(invoker, session_id="parent", status="waiting", session_json='{"image_name":"old.png"}')+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+ assert preview.impact.delete_images == 1++ # The queue timestamp has millisecond precision. Suppress its trigger to make the+ # same-millisecond, same-length rewrite deterministic instead of timing dependent.+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("DROP TRIGGER tg_session_queue_updated_at;")+ cursor.execute("UPDATE session_queue SET session = ? WHERE item_id = ?;", ('{"image_name":"new.png"}', item_id))++ started = service.start_operation(+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="same-stamp"), ALICE+ )+ assert _wait(service, started.operation_id).progress.retained_images == 1+ assert _exists(invoker, "new.png")++def test_retries_are_authorized_as_the_retrying_caller(invoker: Invoker, service: IntermediatesService, monkeypatch) -> None:@@ -1045,6 +1085,51 @@ def test_operation_receipt_and_retry_survive_restart(restored.stop()+def test_receipt_pruning_keeps_unresolved_targets_retryable(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS", 2)+ _seed_image(invoker, "flaky.png")+ real_delete = invoker.services.images.delete_intermediates_by_names+ monkeypatch.setattr(+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))+ )+ _, failed = _run(service, ALICE, _owner("alice"))+ assert failed.progress.unresolved_images == 1+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)++ # New successful receipts may be pruned; the failed operation's exact target must not be.+ for _ in range(2):+ _run(service, ADMIN, _owner("bob"))++ assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1+ retry = service.retry_operation(failed.operation_id, ALICE)+ assert _wait(service, retry.operation_id).progress.deleted_images == 1+++def test_recovery_capacity_refuses_new_work_but_allows_the_unresolved_retry(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS", 1)+ _seed_image(invoker, "flaky.png")+ real_delete = invoker.services.images.delete_intermediates_by_names+ monkeypatch.setattr(+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))+ )+ _, failed = _run(service, ALICE, _owner("alice"))+ assert failed.progress.unresolved_images == 1+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)++ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), ADMIN)+ with pytest.raises(IntermediatesUnavailableError, match="Retry unresolved"):+ service.start_operation(+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="another"), ADMIN+ )+ assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1+ retry = service.retry_operation(failed.operation_id, ALICE)+ assert _wait(service, retry.operation_id).progress.deleted_images == 1++def test_force_confirmation_guard_survives_failed_batch_and_restart(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_track_queue_session_revision.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_track_queue_session_revision.pynew file mode 100644index 0000000000..77156eedba--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_track_queue_session_revision.py@@ -0,0 +1,27 @@+"""The cleanup cache must notice session rewrites even when their timestamps collide."""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_23_track_queue_session_revision import (+ build_migration,+)+++def test_session_revision_advances_only_for_changed_session_content() -> None:+ connection = sqlite3.connect(":memory:")+ cursor = connection.cursor()+ cursor.execute("CREATE TABLE session_queue (item_id INTEGER PRIMARY KEY, session TEXT NOT NULL, updated_at TEXT);")+ cursor.execute("INSERT INTO session_queue VALUES (1, '{\"image_name\":\"old.png\"}', 'same-timestamp');")+ build_migration().callback(cursor)++ cursor.execute('UPDATE session_queue SET session = \'{"image_name":"new.png"}\' WHERE item_id = 1;')+ cursor.execute("SELECT session_revision, updated_at FROM session_queue WHERE item_id = 1;")+ assert cursor.fetchone() == (1, "same-timestamp")++ cursor.execute("UPDATE session_queue SET session = session WHERE item_id = 1;")+ cursor.execute("SELECT session_revision FROM session_queue WHERE item_id = 1;")+ assert cursor.fetchone()[0] == 1+ build_migration().callback(cursor)+ cursor.execute('UPDATE session_queue SET session = \'{"image_name":"old.png"}\' WHERE item_id = 1;')+ cursor.execute("SELECT session_revision FROM session_queue WHERE item_id = 1;")+ assert cursor.fetchone()[0] == 2