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(webv2): release intermediate holds and require undo media refs
Josh Corbett2eb7d604c794
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 7200bd5bec..dc856ee8fd 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -40,7 +40,7 @@ The queue pilot is the first migrated feature. Its private `QueueBackendPort` isQueue exposes board-independent active backend sessions, including preparation and result settlement. The Gallery progress section includes every unfinished batch slot, including queued work; Preview follows executing and settling sessions. Both use gallery-destination projections of the active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions do not participate in board counts, saved-image selection, or navigation. Saved outputs retain their actual backend board destinations; automatic result selection does not change the browsed board or its paging window.-Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the client only freezes a server preview and confirms it. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.+Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the manager requests a server preview, which freezes the targets, and confirms it. The client's one input to that policy is a browser hold lease: `holdLease` (a public entry, started by Workbench for the provider's lifetime) keeps the media open editors still need (live content from every open project plus the undo state each live Canvas engine retains, read through `projects/projectAssets`) classified as active. It sends sorted names in batches within the server's per-kind limit, stages a changed set under a second lease before releasing the old one, refreshes every five minutes and when a tab becomes visible after a minute away, and releases with `keepalive` on dispose and `pagehide`; the server expires a lease after 15 minutes, which bounds anything a crash leaves behind. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.@@ -89,17 +89,17 @@ The target dependency graph intentionally records the current migration cycle: WFeature interfaces remain ordinary module interfaces unless two adapters add leverage. Queue's backend port has production transport/realtime and test adapters; Identity's token/session port has browser-session and test adapters; Models and Nodes use production event/transport adapters; their sinks (model-load activity, node execution) are injected into Queue's runtime at the App composition root, with test doubles in Queue's runtime tests. Gallery, Generation, Workflow, and Upscale keep their compilation and UI seams internal until their feature tickets demonstrate another independent adapter. Workbench image actions likewise remain internal rather than becoming a shallow Image Feature.-| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |-| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |-| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |-| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |-| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |-| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |-| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |-| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |-| Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent and the `settingsContribution` metadata whose loader owns the section body |+| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |+| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |+| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |+| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |+| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |+| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |+| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |+| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |+| Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent, the browser hold lease and the `settingsContribution` metadata whose loader owns the section body |## Settings contributionsdiff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex c2682260f3..21b7401897 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -586,6 +586,7 @@"source:src/features/identity/ui/UsersPage.tsx","source:src/features/identity/ui/useIdentityNotify.ts","source:src/features/intermediates/data/focus.ts",+ "source:src/features/intermediates/holdLease.ts","source:src/features/intermediates/index.ts","source:src/features/intermediates/settingsContribution.ts","source:src/features/models/core/baseIdentity.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 3218b43e59..20dd6aae2d 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1081,6 +1081,7 @@"source:src/features/identity/ui/UsersPage.tsx","source:src/features/identity/ui/useIdentityNotify.ts","source:src/features/intermediates/data/focus.ts",+ "source:src/features/intermediates/holdLease.ts","source:src/features/intermediates/index.ts","source:src/features/intermediates/settingsContribution.ts","source:src/features/models/core/baseIdentity.ts",@@ -2131,6 +2132,7 @@"source:src/features/identity/ui/UsersPage.tsx","source:src/features/identity/ui/useIdentityNotify.ts","source:src/features/intermediates/data/focus.ts",+ "source:src/features/intermediates/holdLease.ts","source:src/features/intermediates/index.ts","source:src/features/intermediates/settingsContribution.ts","source:src/features/models/core/baseIdentity.ts",@@ -3339,6 +3341,7 @@"source:src/features/identity/ui/UsersPage.tsx","source:src/features/identity/ui/useIdentityNotify.ts","source:src/features/intermediates/data/focus.ts",+ "source:src/features/intermediates/holdLease.ts","source:src/features/intermediates/index.ts","source:src/features/intermediates/settingsContribution.ts","source:src/features/models/core/baseIdentity.ts",diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsxindex 3b3adbaa89..a7a2d4e8ca 100644--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx@@ -6,7 +6,6 @@ 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';@@ -38,7 +37,7 @@ export const WorkbenchApp = () => {useMountEffect(preloadBootWidgets);return (- <WorkbenchProvider getCanvasHeldAssetRefs={getCanvasHeldAssetRefs} loadOptions={loadOptions}>+ <WorkbenchProvider loadOptions={loadOptions}><WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}><BootWidgetHintController /><GenerateWidgetSyncRuntime />diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex 0c641ba5e2..a1d7c0df23 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -236,6 +236,7 @@ describe('feature public-interface registry', () => {expect(checkDependency('workbench/invocationSubmit.ts', '@features/generation/prompts')).toEqual([]);expect(checkDependency('app/GenerateWidgetSyncRuntime.tsx', '@features/generation/runtime')).toEqual([]);expect(checkDependency('workbench/widgets/canvas/invoke.ts', '@features/generation/canvasGraph')).toEqual([]);+ expect(checkDependency('workbench/WorkbenchContext.tsx', '@features/intermediates/holdLease')).toEqual([]);expect(checkDependency('workbench/invocationSubmit.ts', '@features/generation/data/dynamicPromptsQueries')).toMatchObject([{ rule: 'feature-private-interface' }]);diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex 52c460984b..27422dba8b 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -31,7 +31,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string['widget',],identity: [],- intermediates: ['settingsContribution'],+ intermediates: ['holdLease', 'settingsContribution'],models: ['launchpad', 'react'],nodes: [],queue: ['contracts', 'devices', 'launchpad', 'menu', 'queries', 'react', 'reveal', 'utility', 'widget'],diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.tsnew file mode 100644index 0000000000..282d1030e3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts@@ -0,0 +1,178 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { apiFetch } from '@platform/transport/http';+import { afterEach, expect, it, vi } from 'vitest';++import type { HeldMediaNames } from './holdLease';++import { MAX_HOLD_NAMES_PER_KIND, partitionHeldMediaNames, startIntermediatesHoldLease } from './holdLease';++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ apiFetch: vi.fn().mockResolvedValue(undefined),+ getHttpAuthToken: vi.fn(() => 'lease-token'),+}));++const fetchMock = vi.mocked(apiFetch);++const ownerWith = (signal: AbortSignal): AccountScope => ({ accountId: 'alice', epoch: 1, signal, storageSuffix: '' });++const startWith = (initial: HeldMediaNames, signal = new AbortController().signal) => {+ let held = initial;+ let notify: () => void = () => undefined;+ const stop = startIntermediatesHoldLease({+ owner: ownerWith(signal),+ read: () => held,+ subscribe: (onChange) => {+ notify = onChange;+ return () => undefined;+ },+ });+ return {+ stop,+ update: (next: HeldMediaNames) => {+ held = next;+ notify();+ },+ };+};++const calls = (method: string) =>+ fetchMock.mock.calls.filter(([, init]) => init?.method === method).map(([url, init]) => ({ init, url: String(url) }));++const settle = () =>+ new Promise((resolve) => {+ setTimeout(resolve, 20);+ });++afterEach(() => {+ fetchMock.mockReset();+ fetchMock.mockResolvedValue(undefined as never);+});++it('partitions a long hold without dropping names or exceeding either API limit', () => {+ const images = Array.from({ length: MAX_HOLD_NAMES_PER_KIND + 1 }, (_, index) => `image-${index}`);+ const videos = ['first.mp4', 'second.mp4'];+ const batches = partitionHeldMediaNames(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);+});++it('replaces current holds and releases names removed from the open editor', async () => {+ const lease = startWith({ images: ['first.png'], videos: [] });+ try {+ await vi.waitFor(() =>+ expect(calls('PUT').map(({ init }) => init?.body)).toContain(+ JSON.stringify({ images: ['first.png'], videos: [] })+ )+ );+ lease.update({ images: ['second.png'], videos: [] });+ await vi.waitFor(() =>+ expect(calls('PUT').map(({ init }) => init?.body)).toContain(+ JSON.stringify({ images: ['second.png'], videos: [] })+ )+ );+ await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(1));+ lease.update({ images: [], videos: [] });+ await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(2));+ } finally {+ lease.stop();+ }+});++it('releases its leases with keepalive when disposed', async () => {+ const lease = startWith({ images: ['held.png'], videos: ['held.mp4'] });+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));+ const leaseUrl = calls('PUT')[0]!.url;++ lease.stop();++ expect(calls('DELETE')).toEqual([expect.objectContaining({ url: leaseUrl })]);+ expect(calls('DELETE')[0]!.init).toMatchObject({ keepalive: true });+});++it('releases as the account that took the lease after that account signed out', async () => {+ const session = new AbortController();+ const lease = startWith({ images: ['held.png'], videos: [] }, session.signal);+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));++ session.abort();+ lease.stop();++ const [release] = calls('DELETE');+ expect(release).toBeDefined();+ expect(release!.init?.signal).toBeUndefined();+ expect(new Headers(release!.init?.headers).get('Authorization')).toBe('Bearer lease-token');+});++it('releases on pagehide and holds again when the page is restored', async () => {+ const lease = startWith({ images: ['held.png'], videos: [] });+ try {+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));++ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true }));+ expect(calls('DELETE')).toHaveLength(1);+ expect(calls('DELETE')[0]!.init).toMatchObject({ keepalive: true });++ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }));+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(2));+ } finally {+ lease.stop();+ }+});++it('does not resend an unchanged hold each time the tab becomes visible', async () => {+ const lease = startWith({ images: ['held.png'], videos: [] });+ try {+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));+ await settle();+ expect(document.visibilityState).toBe('visible');+ document.dispatchEvent(new Event('visibilitychange'));+ document.dispatchEvent(new Event('visibilitychange'));+ await settle();+ expect(calls('PUT')).toHaveLength(1);+ } finally {+ lease.stop();+ }+});++it('keeps old batches held until every replacement batch is installed', async () => {+ const imageNames = Array.from({ length: 50_001 }, (_, index) => `b${index.toString().padStart(5, '0')}.png`);+ const boundaryName = imageNames[49_999]!;+ const held = new Map<string, string[]>();+ let started = false;+ let exposed = false;+ let failSecondStagedBatch = true;+ fetchMock.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 lease = startWith({ images: imageNames, videos: [] });+ try {+ await vi.waitFor(() => expect(held.size).toBe(2));+ const initialLeases = [...held.keys()];+ started = true;+ lease.update({ images: ['a.png', ...imageNames], videos: [] });+ await vi.waitFor(() => expect(failSecondStagedBatch).toBe(false));+ expect(initialLeases.every((leaseUrl) => held.has(leaseUrl))).toBe(true);+ lease.update({ images: ['a.png', ...imageNames], videos: [] });+ await vi.waitFor(() => expect(initialLeases.every((leaseUrl) => !held.has(leaseUrl))).toBe(true));+ expect(exposed).toBe(false);+ } finally {+ lease.stop();+ }+});diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.tsnew file mode 100644index 0000000000..ce0ed7bfa3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts@@ -0,0 +1,246 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { createUuid } from '@platform/browser/randomUuid';+import { apiFetch, getHttpAuthToken } from '@platform/transport/http';++export interface HeldMediaNames {+ images: readonly string[];+ videos: readonly string[];+}++/** Mirrors the server's per-kind `max_length` on a hold request. */+export const MAX_HOLD_NAMES_PER_KIND = 50_000;++/** The server keeps a lease for 15 minutes; refreshing well inside that survives a missed beat. */+const HEARTBEAT_MS = 5 * 60_000;+const RESEND_ON_VISIBLE_AFTER_MS = 60_000;+const CHANGE_DEBOUNCE_MS = 250;++type Batch = { images: string[]; videos: string[] };+type Slot = 0 | 1;++const holdPath = (leaseId: string): string => `/api/v1/intermediates/holds/${encodeURIComponent(leaseId)}`;++/** Each request stays within the per-kind limit; sorted input keeps unchanged batches byte-identical. */+export const partitionHeldMediaNames = (images: readonly string[], videos: readonly string[]): Batch[] => {+ const batches: Batch[] = [];+ for (let start = 0; start < Math.max(images.length, videos.length); start += MAX_HOLD_NAMES_PER_KIND) {+ batches.push({+ images: images.slice(start, start + MAX_HOLD_NAMES_PER_KIND),+ videos: videos.slice(start, start + MAX_HOLD_NAMES_PER_KIND),+ });+ }+ return batches;+};++/**+ * Keeps the media an open editor still needs (unsaved content, undo state) out of cleanup for as long as the tab is+ * alive. Replacement batches are staged under a second lease set before the old one is released, so a name never+ * goes unprotected mid-update. Leases are released on dispose and on `pagehide`, with `keepalive` so the release+ * survives the page; the server's 15-minute expiry bounds anything a crash leaves behind.+ */+export const startIntermediatesHoldLease = ({+ owner,+ read,+ subscribe,+}: {+ owner: AccountScope;+ /** Current names to hold, in any order. */+ read: () => HeldMediaNames;+ /** Notifies when `read` may return something new. */+ subscribe: (onChange: () => void) => () => void;+}): (() => void) => {+ const leaseId = createUuid();+ const leaseSignatures: [string[], string[]] = [[], []];+ let activeSlot: Slot | null = null;+ let disposed = false;+ let inFlight = false;+ let pending = false;+ let pendingRefresh = false;+ let lastSentAt = 0;+ let timer: ReturnType<typeof setTimeout> | null = null;+ // Releases must authenticate as the account that took the lease, even after sign-out cleared the session.+ let leaseToken: string | null = null;++ const batchLeaseId = (slot: Slot, index: number): string => `${leaseId}-${slot}-${index}`;+ const isStopped = (): boolean => disposed || owner.signal.aborted;++ const fireRelease = (id: string): void => {+ void apiFetch(holdPath(id), {+ headers: leaseToken ? { Authorization: `Bearer ${leaseToken}` } : undefined,+ keepalive: true,+ method: 'DELETE',+ }).catch(() => undefined);+ };++ const releaseEverything = (): void => {+ for (const slot of [0, 1] as const) {+ leaseSignatures[slot].forEach((signature, index) => {+ if (signature) {+ fireRelease(batchLeaseId(slot, index));+ }+ });+ leaseSignatures[slot] = [];+ }+ activeSlot = null;+ };++ const releaseSlot = async (slot: Slot, from = 0): Promise<void> => {+ const signatures = leaseSignatures[slot];+ for (let index = from; index < signatures.length; index += 1) {+ if (!signatures[index] || isStopped()) {+ continue;+ }+ try {+ await apiFetch(holdPath(batchLeaseId(slot, index)), { method: 'DELETE', signal: owner.signal });+ signatures[index] = '';+ } catch {+ // Keep the signature so a later send retries the release.+ }+ }+ while (signatures.at(-1) === '') {+ signatures.pop();+ }+ };++ const putBatch = async (slot: Slot, index: number, batch: Batch): Promise<boolean> => {+ if (isStopped()) {+ return false;+ }+ const token = getHttpAuthToken();+ try {+ await apiFetch(holdPath(batchLeaseId(slot, index)), {+ body: JSON.stringify(batch),+ headers: { 'Content-Type': 'application/json' },+ method: 'PUT',+ signal: owner.signal,+ });+ } catch {+ return false;+ }+ leaseToken = token;+ if (disposed) {+ // Dispose already released what it knew about; this lease landed after.+ fireRelease(batchLeaseId(slot, index));+ return false;+ }+ leaseSignatures[slot][index] = JSON.stringify([batch.images, batch.videos]);+ return true;+ };++ const sendOnce = async (refresh: boolean): Promise<void> => {+ const held = read();+ const images = [...new Set(held.images)].sort();+ const videos = [...new Set(held.videos)].sort();+ if (!images.length && !videos.length) {+ await releaseSlot(0);+ await releaseSlot(1);+ activeSlot = null;+ return;+ }+ const batches = partitionHeldMediaNames(images, videos);+ const signatures = batches.map((batch) => JSON.stringify([batch.images, batch.videos]));+ const current = activeSlot === null ? null : leaseSignatures[activeSlot];+ let trimActive = false;+ if (current && current.length === signatures.length && signatures.every((value, i) => value === current[i])) {+ if (refresh) {+ let refreshed = true;+ for (let index = 0; index < batches.length; index += 1) {+ refreshed = (await putBatch(activeSlot!, index, batches[index]!)) && refreshed;+ }+ if (refreshed) {+ lastSentAt = Date.now();+ }+ }+ trimActive = true;+ } else {+ const nextSlot: Slot = activeSlot === 0 ? 1 : 0;+ let staged = true;+ for (let index = 0; index < batches.length; index += 1) {+ staged = (await putBatch(nextSlot, index, batches[index]!)) && staged;+ }+ if (staged && !isStopped()) {+ const oldSlot = activeSlot;+ activeSlot = nextSlot;+ lastSentAt = Date.now();+ trimActive = true;+ if (oldSlot !== null) {+ await releaseSlot(oldSlot);+ }+ }+ }+ if (activeSlot !== null) {+ if (trimActive) {+ await releaseSlot(activeSlot, batches.length);+ }+ await releaseSlot(activeSlot === 0 ? 1 : 0);+ }+ };++ const send = async (refresh = false): Promise<void> => {+ if (isStopped()) {+ return;+ }+ if (inFlight) {+ pending = true;+ pendingRefresh ||= refresh;+ return;+ }+ inFlight = true;+ try {+ do {+ pending = false;+ const mustRefresh = refresh || pendingRefresh;+ refresh = false;+ pendingRefresh = false;+ await sendOnce(mustRefresh);+ } while (pending && !isStopped());+ } finally {+ inFlight = false;+ }+ };++ const schedule = (): void => {+ if (timer !== null) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => {+ timer = null;+ void send();+ }, CHANGE_DEBOUNCE_MS);+ };+ const onVisibilityChange = (): void => {+ if (+ document.visibilityState === 'visible' &&+ (activeSlot === null || Date.now() - lastSentAt >= RESEND_ON_VISIBLE_AFTER_MS)+ ) {+ void send(true);+ }+ };+ const onPageHide = (): void => releaseEverything();+ const onPageShow = (event: PageTransitionEvent): void => {+ if (event.persisted) {+ void send();+ }+ };++ const unsubscribe = subscribe(schedule);+ const heartbeat = setInterval(() => void send(true), HEARTBEAT_MS);+ document.addEventListener('visibilitychange', onVisibilityChange);+ window.addEventListener('pagehide', onPageHide);+ window.addEventListener('pageshow', onPageShow);+ void send();++ return () => {+ disposed = true;+ unsubscribe();+ clearInterval(heartbeat);+ if (timer !== null) {+ clearTimeout(timer);+ }+ document.removeEventListener('visibilitychange', onVisibilityChange);+ window.removeEventListener('pagehide', onPageHide);+ window.removeEventListener('pageshow', onPageShow);+ releaseEverything();+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.ts b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.tsdeleted file mode 100644index c24b88e279..0000000000--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.holds.browser.test.ts+++ /dev/null@@ -1,160 +0,0 @@-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 ef4c3bba8d..bd7f7179ad 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -3,11 +3,10 @@ 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 { startIntermediatesHoldLease } from '@features/intermediates/holdLease';import { useMountEffect } from '@platform/react/useMountEffect';-import { captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';+import { captureAccountScope } 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';@@ -19,7 +18,7 @@ import { createExtensionRegistry, type ExtensionRegistry } from './extensions/eximport { clearLayerPanelStates } from './layerPanelState';import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';import { createOpenProjectBroker } from './projects/openProjectBroker';-import { collectHeldAssetRefs, partitionHeldAssetNames } from './projects/projectAssets';+import { createOpenProjectsHeldMediaReader } from './projects/projectAssets';import { describeRefusedProjects } from './projects/projectLoadRefusal';import {createSyncedWorkbenchPersistence,@@ -47,203 +46,11 @@ 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. */-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 leaseSignatures: [string[], string[]] = [[], []];- let activeSlot: 0 | 1 | null = null;- let lastProjects = store.getSnapshot().projects;- // 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();- }- };-- 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;- }- };-- 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;- 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) {- await releaseSlot(0);- await releaseSlot(1);- activeSlot = null;- continue;- }- const batches = partitionHeldAssetNames(images, videos);- const signatures = batches.map((batch) => JSON.stringify([batch.images, batch.videos]));- const current = activeSlot === null ? null : leaseSignatures[activeSlot];- let trimActive = false;- if (- current &&- current.length === signatures.length &&- signatures.every((value, index) => value === current[index])- ) {- if (mustRefresh) {- for (let index = 0; index < batches.length; index += 1) {- await putBatch(activeSlot!, index, batches[index]!);- }- }- 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;- }- 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;- }- } while (pending);- } finally {- inFlight = false;- }- };- const schedule = (): void => {- const projects = store.getSnapshot().projects;- if (projects === lastProjects) {- return;- }- lastProjects = projects;- 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,- getCanvasHeldAssetRefs,loadOptions,}: {children: ReactNode;- getCanvasHeldAssetRefs: GetCanvasHeldAssetRefs;/** Boot-time session options (deep-linked project, fresh draft). Read once at mount. */loadOptions?: WorkbenchLoadOptions;}) => {@@ -329,7 +136,20 @@ export const WorkbenchProvider = ({});persistenceRuntime.start();- const releaseIntermediateHold = startBrowserIntermediateHold(store, owner, getCanvasHeldAssetRefs);+ const releaseIntermediateHold = startIntermediatesHoldLease({+ owner,+ read: createOpenProjectsHeldMediaReader(() => store.getSnapshot().projects),+ subscribe: (onChange) => {+ let projects = store.getSnapshot().projects;+ return store.subscribe(() => {+ const next = store.getSnapshot().projects;+ if (next !== projects) {+ projects = next;+ onChange();+ }+ });+ },+ });return () => {releaseIntermediateHold();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsindex 6997053ff2..226cc4711d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -225,6 +225,7 @@ export class FloatingSelectionController {});this.deps.history.push({bytes: patch.bytes + (selectionBefore.alpha?.byteLength ?? 0) + (selectionAfter.alpha?.byteLength ?? 0),+ heldAssetRefs: patch.heldAssetRefs,label: patch.label,redo: () => {patch.redo();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.tsindex 1cdd825910..367ebe07d2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts@@ -1,3 +1,4 @@+import { NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { HistoryController } from './historyController';@@ -5,8 +6,20 @@ import { HistoryController } from './historyController';describe('HistoryController', () => {it('owns history and trims it to the inactive byte budget', () => {const controller = new HistoryController({ activeByteBudget: 1_000, inactiveByteBudget: 100 });- controller.history.push({ bytes: 60, label: 'old', redo: () => undefined, undo: () => undefined });- controller.history.push({ bytes: 70, label: 'new', redo: () => undefined, undo: () => undefined });+ controller.history.push({+ bytes: 60,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label: 'old',+ redo: () => undefined,+ undo: () => undefined,+ });+ controller.history.push({+ bytes: 70,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label: 'new',+ redo: () => undefined,+ undo: () => undefined,+ });controller.cooldown();@@ -32,7 +45,7 @@ describe('HistoryController', () => {});const undo = vi.fn();const redo = vi.fn();- controller.history.push({ bytes: 1, label: 'edit', redo, undo });+ controller.history.push({ bytes: 1, heldAssetRefs: NO_HELD_ASSET_REFS, label: 'edit', redo, undo });controller.undo();expect(undo).toHaveBeenCalledOnce();@@ -64,7 +77,13 @@ describe('HistoryController', () => {const controller = new HistoryController({ canRedoStore: canRedo, canUndoStore: canUndo });expect(() =>- controller.history.push({ bytes: 1, label: 'edit', redo: () => undefined, undo: () => undefined })+ controller.history.push({+ bytes: 1,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label: 'edit',+ redo: () => undefined,+ undo: () => undefined,+ })).not.toThrow();expect(canRedo.set).toHaveBeenCalled();controller.dispose();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.tsindex e9e702a26c..be771df1a0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts@@ -2,7 +2,7 @@ import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contractimport type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createHistory } from '@workbench/canvas-engine/history/history';+import { createHistory, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { createCanvasMutationContext, type CanvasMutationContextDeps } from './mutationContext';@@ -161,6 +161,7 @@ describe('createCanvasMutationContext', () => {);history.push({bytes: 1,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'Replay',redo: () => undefined,undo: () =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.tsindex 4429e3fcca..b0dc9ae842 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts@@ -7,7 +7,7 @@ import { removeNodes } from '@workbench/canvas-engine/document/documentTree';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';-import { createHistory } from '@workbench/canvas-engine/history/history';+import { createHistory, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { StagedResultController } from './stagedResultController';@@ -207,7 +207,7 @@ describe('StagedResultController', () => {let reducerCanvas = makeCanvas();let mirrorDocument = reducerCanvas.document;const history = createHistory();- history.push({ bytes: 1, label: 'older edit', redo: vi.fn(), undo: vi.fn() });+ history.push({ bytes: 1, heldAssetRefs: NO_HELD_ASSET_REFS, label: 'older edit', redo: vi.fn(), undo: vi.fn() });history.undo();expect(history.canRedo()).toBe(true);const controller = new StagedResultController({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex ef73364cdd..c63a486289 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@ -12,6 +12,7 @@ import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndeimport { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';+import { NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';@@ -100,6 +101,7 @@ export class TransformEditingController {): HistoryEntry {return {bytes: before.data.byteLength + after.data.byteLength + 256,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'Transform layer',redo: () => {this.deps.dispatch({ id: layerId, patch: { transform: newTransform }, type: 'updateCanvasLayer' });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 516ef6e805..4c94733bd0 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@@ -2,11 +2,12 @@ import { describe, expect, it, vi } from 'vitest';import type { HistoryEntry } from './history';-import { createHistory, HISTORY_BYTE_BUDGET, HISTORY_MAX_ENTRIES } from './history';+import { createHistory, HISTORY_BYTE_BUDGET, HISTORY_MAX_ENTRIES, NO_HELD_ASSET_REFS } from './history';/** A tiny entry that records undo/redo calls into a shared log. */const makeEntry = (label: string, log: string[], bytes = 0): HistoryEntry => ({bytes,+ heldAssetRefs: NO_HELD_ASSET_REFS,label,redo: () => log.push(`redo:${label}`),undo: () => log.push(`undo:${label}`),@@ -223,6 +224,7 @@ describe('createHistory: amendLast', () => {const history = createHistory();const reentrant: HistoryEntry = {bytes: 0,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'reentrant',redo: () => {},undo: () => history.amendLast(makeEntry('sneaky', log)),@@ -248,6 +250,7 @@ describe('createHistory: re-entrancy guard', () => {const reentrant: HistoryEntry = {bytes: 0,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'reentrant',redo: () => {observed.push(history.isApplying());@@ -290,7 +293,14 @@ describe('createHistory: failure-atomic replay', () => {});const redo = vi.fn();history.subscribe(listener);- history.push({ bytes: 17, label: 'fallible', redo, replayFailureAtomic: true, undo });+ history.push({+ bytes: 17,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label: 'fallible',+ redo,+ replayFailureAtomic: true,+ undo,+ });listener.mockClear();expect(() => history.undo()).toThrow('undo preparation failed');@@ -318,7 +328,14 @@ describe('createHistory: failure-atomic replay', () => {}});history.subscribe(listener);- history.push({ bytes: 23, label: 'fallible', redo, replayFailureAtomic: true, undo });+ history.push({+ bytes: 23,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label: 'fallible',+ redo,+ replayFailureAtomic: true,+ undo,+ });history.undo();listener.mockClear();@@ -343,6 +360,7 @@ describe('createHistory: failure-atomic replay', () => {history.push(makeEntry('a', log, 10));history.push({bytes: 10,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'b',redo: () => log.push('redo:b'),replayFailureAtomic: true,@@ -373,6 +391,7 @@ describe('createHistory: failure-atomic replay', () => {history.subscribe(listener);history.push({bytes: 10,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'clear-on-undo',redo: () => {},replayFailureAtomic,@@ -397,6 +416,7 @@ describe('createHistory: failure-atomic replay', () => {history.subscribe(listener);history.push({bytes: 10,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'clear-on-redo',redo: () => {if (clearOnRedo) {@@ -425,6 +445,7 @@ describe('createHistory: failure-atomic replay', () => {history.subscribe(listener);history.push({bytes: 10,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'legacy-fallible-undo',redo: () => applied.push('redo'),undo: () => {@@ -454,6 +475,7 @@ describe('createHistory: failure-atomic replay', () => {history.subscribe(listener);history.push({bytes: 10,+ heldAssetRefs: NO_HELD_ASSET_REFS,label: 'legacy-fallible-redo',redo: () => {applied.push('redo');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.tsindex 2d0fd51f66..5db9ff2667 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts@@ -4,34 +4,25 @@* recording and `push` is a no-op, avoiding recursive history.*/+import { collectRestorableAssetRefs } from '@workbench/projects/projectAssets';+/** Max number of undo entries retained before the oldest is evicted. */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;+export interface HeldAssetRefs {+ readonly images: readonly string[];+ readonly videos: readonly string[];+}++/** For entries that restore pixels or selection state only. */+export const NO_HELD_ASSET_REFS: HeldAssetRefs = { images: [], videos: [] };+/** 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);- }- }- }+export const collectHistoryMediaRefs = (...values: unknown[]): HeldAssetRefs => {+ const { images, videos } = collectRestorableAssetRefs(...values);return { images: [...images], videos: [...videos] };};@@ -41,8 +32,11 @@ export interface HistoryEntry {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[] };+ /**+ * Media names this entry can restore after they leave the current document; cleanup keeps them while the entry is+ * on either stack.+ */+ readonly heldAssetRefs: HeldAssetRefs;/*** Opts into failure-atomic replay. When true, History moves this entry only* after `undo`/`redo` returns successfully, so a preparation failure remains@@ -178,8 +172,8 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {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));+ entry.heldAssetRefs.images.forEach((name) => images.add(name));+ entry.heldAssetRefs.videos.forEach((name) => videos.add(name));}return { images: [...images], videos: [...videos] };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.tsindex 2ff0000eb1..1a97759ef4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts@@ -8,6 +8,8 @@ import type { Rect } from '@workbench/canvas-engine/types';import type { HistoryEntry } from './history';+import { NO_HELD_ASSET_REFS } from './history';+/*** Engine-owned pixel write at the layer-local rect, including invalidation/versioning and dirty persistence* marking.@@ -51,6 +53,7 @@ export const createImagePatchEntry = (opts: CreateImagePatchEntryOptions): Historeturn {bytes,+ heldAssetRefs: NO_HELD_ASSET_REFS,label,redo: () => apply(layerId, patchRect, after),undo: () => apply(layerId, patchRect, before),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.tsindex 8e7dc04a2e..6b66b91e25 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts@@ -6,6 +6,7 @@import type { History } from '@workbench/canvas-engine/history/history';import type { Rect, SelectionOp } from '@workbench/canvas-engine/types';+import { NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { isEmpty } from '@workbench/canvas-engine/math/rect';import type { SelectionCommit, SelectionSnapshot, SelectionState } from './selectionState';@@ -71,6 +72,7 @@ export const withSelectionHistory = (selection: SelectionState, history: HistorylastAfter = after;history.push({bytes: beforeBytes + (after.alpha?.byteLength ?? 0),+ heldAssetRefs: NO_HELD_ASSET_REFS,label,redo: () => selection.restore(after),undo: () => selection.restore(before),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex 25b5b4c9a9..1a6572a1a5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -7,6 +7,7 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCacheimport type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';import type { Rect } from '@workbench/canvas-engine/types';+import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';export interface CreateStrokeCommitDeps {@@ -47,6 +48,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =const bytes = event.beforeImageData.data.byteLength + afterImageData.data.byteLength + 256;return {bytes,+ heldAssetRefs: collectHistoryMediaRefs(created.layer),label,redo: () => {dispatchCanvasMutation({ anchor: created.anchor, layer: created.layer, type: 'addCanvasLayer' });diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex f1eefb1b2e..28df817ebe 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';import {collectHeldAssetRefs,collectLiveAssetRefs,- partitionHeldAssetNames,+ createOpenProjectsHeldMediaReader,remapAssetRefs,selectCoverImageName,stripInstallationState,@@ -50,15 +50,21 @@ it('holds media from unsaved editor state and undo history', () => {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);+it('holds names Canvas undo retains after the project stops naming them, and drops closed projects', () => {+ let projects = [{ canvas: { imageName: 'second.png' }, id: 'project-1', video: { videoName: 'clip.mp4' } }];+ let undo = ['first.png'];+ const read = createOpenProjectsHeldMediaReader(+ () => projects,+ () => ({ images: undo, videos: [] })+ );++ const held = read();+ expect(new Set(held.images)).toEqual(new Set(['first.png', 'second.png']));+ expect(held.videos).toEqual(['clip.mp4']);++ undo = [];+ projects = [];+ expect(read()).toEqual({ images: [], videos: [] });});const projectDocument = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 4df4daf72f..0f4bd9206c 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -3,11 +3,14 @@* includes it.*/-/** Keys whose string values name an image. */-const IMAGE_NAME_KEYS = new Set(['imageName', 'image_name']);+/** Keys whose string values name an image; the server's `media_references` extractor uses the same set. */+const IMAGE_NAME_KEYS: ReadonlySet<string> = new Set(['imageName', 'image_name']);-/** Keys whose string values name a video. */-const VIDEO_NAME_KEYS = new Set(['video_name']);+/** Keys whose string values name a video; the server's `media_references` extractor uses the same set. */+const VIDEO_NAME_KEYS: ReadonlySet<string> = new Set(['videoName', 'video_name']);++/** Server-side names are generated filenames; the cleanup index ignores anything longer. */+const MAX_HELD_NAME_LENGTH = 255;/** Top-level document keys that are history rather than live content. */export const PROJECT_HISTORY_ROOT_KEYS: ReadonlySet<string> = new Set(['events', 'graphHistory', 'queue']);@@ -62,105 +65,99 @@ export const getCanvasHeldAssetRefs = (projectId: string): CanvasHeldAssetRefs |const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);-const collectFrom = (node: unknown, refs: ProjectAssetRefs): void => {- if (Array.isArray(node)) {- for (const item of node) {- collectFrom(item, refs);+/** Every name under a media-name key, at any depth, except subtrees whose key `skipKey` rejects. */+const collectMediaNames = (+ roots: readonly unknown[],+ skipKey: (key: string) => boolean,+ maxLength = Number.POSITIVE_INFINITY+): ProjectAssetRefs => {+ const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };+ const pending = [...roots];+ while (pending.length > 0) {+ const node = pending.pop();+ if (Array.isArray(node)) {+ for (const item of node) {+ pending.push(item);+ }+ continue;}-- return;- }-- if (!isRecord(node)) {- return;- }-- for (const [key, value] of Object.entries(node)) {- if (PROJECT_HISTORY_KEYS.has(key) || GALLERY_SELECTION_KEYS.has(key)) {+ if (!isRecord(node)) {continue;}-- if (typeof value === 'string' && value !== '') {- if (IMAGE_NAME_KEYS.has(key)) {- refs.images.add(value);+ for (const [key, value] of Object.entries(node)) {+ if (skipKey(key)) {continue;}-- if (VIDEO_NAME_KEYS.has(key)) {- refs.videos.add(value);- continue;+ if (typeof value === 'string') {+ if (value !== '' && value.length <= maxLength) {+ if (IMAGE_NAME_KEYS.has(key)) {+ refs.images.add(value);+ } else if (VIDEO_NAME_KEYS.has(key)) {+ refs.videos.add(value);+ }+ }+ } else if (typeof value === 'object' && value !== null) {+ pending.push(value);}}-- collectFrom(value, refs);}+ return refs;};-export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>): ProjectAssetRefs => {- const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };+const withoutHistoryRoots = (projectDocument: object): unknown[] =>+ Object.entries(projectDocument).flatMap(([key, value]) => (PROJECT_HISTORY_ROOT_KEYS.has(key) ? [] : [value]));- for (const [key, value] of Object.entries(projectDocument)) {- if (PROJECT_HISTORY_ROOT_KEYS.has(key)) {- continue;- }+export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>): ProjectAssetRefs =>+ collectMediaNames(+ withoutHistoryRoots(projectDocument),+ (key) => PROJECT_HISTORY_KEYS.has(key) || GALLERY_SELECTION_KEYS.has(key)+ );- collectFrom(value, refs);- }+/** Open editors hold live content and undo state, but not completed queue/event or gallery history. */+export const collectHeldAssetRefs = (projects: readonly object[]): ProjectAssetRefs =>+ collectMediaNames(+ projects.flatMap(withoutHistoryRoots),+ (key) => key === 'recentImages' || GALLERY_SELECTION_KEYS.has(key),+ MAX_HELD_NAME_LENGTH+ );- return refs;-};+/** Every media name in `values`, history included: what an undo entry can restore. */+export const collectRestorableAssetRefs = (...values: unknown[]): ProjectAssetRefs =>+ collectMediaNames(values, () => false, MAX_HELD_NAME_LENGTH);-/** 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);+/**+ * Reads what open editors hold: each project's live content plus the undo state its Canvas engine retains. Project+ * snapshots are immutable, so a project's scan is reused until its object changes.+ */+export const createOpenProjectsHeldMediaReader = (+ getProjects: () => readonly (object & { id: string })[],+ getCanvasRefs: (projectId: string) => CanvasHeldAssetRefs | undefined = getCanvasHeldAssetRefs+): (() => { images: string[]; videos: string[] }) => {+ const scans = new Map<string, { project: object; refs: ProjectAssetRefs }>();+ return () => {+ const images = new Set<string>();+ const videos = new Set<string>();+ const open = new Set<string>();+ for (const project of getProjects()) {+ open.add(project.id);+ let scan = scans.get(project.id);+ if (scan?.project !== project) {+ scan = { project, refs: collectHeldAssetRefs([project]) };+ scans.set(project.id, scan);}+ scan.refs.images.forEach((name) => images.add(name));+ scan.refs.videos.forEach((name) => videos.add(name));+ const retained = getCanvasRefs(project.id);+ retained?.images.forEach((name) => images.add(name));+ retained?.videos.forEach((name) => videos.add(name));}- }- 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);- }+ for (const projectId of scans.keys()) {+ if (!open.has(projectId)) {+ scans.delete(projectId);}}- }- 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;+ return { images: [...images], videos: [...videos] };+ };};/** `{ drop: true }` removes the key, `{ value }` replaces it, `null` recurses into it. */