Skip to content

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

refactor(webv2): follow the ephemeral intermediates cleanup contract

Josh Corbettb819ce55d084
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 2e25592c10..89f0504b02 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -40,7 +40,7 @@ The queue pilot is the first migrated feature. Its private `QueueBackendPort` is
Queue exposes board-independent active backend sessions, including preparation and result settlement. The Gallery progress section includes every unfinished batch slot, including queued work; Preview follows executing and settling sessions. Both use gallery-destination projections of the active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions do not participate in board counts, saved-image selection, or navigation. Saved outputs retain their actual backend board destinations; automatic result selection does not change the browsed board or its paging window.
-Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the manager requests a server preview, which freezes the targets, and confirms it. The client's one input to that policy is a browser hold lease: `holdLease` (a public entry, started by Workbench for the provider's lifetime) keeps the media open editors still need (live content from every open project plus the undo state each live Canvas engine retains) classified as active. Workbench owns the name set: `projects/projectAssets` scans each immutable project subtree once, and each Canvas engine registers its retained undo state with the mounted Workbench, which re-reads it when the history changes; an engine released by one Workbench is replaced, not reused, by the next, and one another Workbench still uses is refused. The lease sends sorted names in batches within the server's per-kind limit, each under an id `<holder>.<part>` sharing one holder per tab because the server caps distinct holders per account, skips unchanged sets without re-serialising them, stages a changed set under a second lease before releasing the old one, refreshes every five minutes and when a tab becomes visible after missing a refresh, and releases with `keepalive` on dispose and `pagehide`; the server expires a lease after 15 minutes, which bounds anything a crash leaves behind. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.
+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 fixes the instant recency is judged at and describes what a cleanup would delete and keep, and confirms it once. "All matching" selections travel as a `matching` scope carrying the summary's filters and the excluded rows, which the server resolves; the client never enumerates pages it has not loaded. Operations are not persisted by the server: a manager that opens with nothing followed lists the account's operations and follows the newest unfinished one, so a reload picks a running cleanup back up, and a settled operation that left failures behind offers to delete its scope again. The client's one input to the policy is a browser hold lease: `holdLease` (a public entry, started by Workbench for the provider's lifetime) keeps the media open editors still need (live content from every open project plus the undo state each live Canvas engine retains) classified as active. Workbench owns the name set: `projects/projectAssets` scans each immutable project subtree once, and each Canvas engine registers its retained undo state with the mounted Workbench, which re-reads it when the history changes; an engine released by one Workbench is replaced, not reused, by the next, and one another Workbench still uses is refused. The lease is one per tab, holding up to the server's per-kind limit of sorted unique names, which the server replaces atomically; it skips unchanged sets without re-serialising them, forgets a send the server did not acknowledge so the next change, heartbeat or return to the foreground sends again while the previous lease still stands, refreshes every five minutes and when a tab becomes visible after missing a refresh, and releases with `keepalive` on dispose and `pagehide`; the server keeps at most eight leases per account and expires a lease after 15 minutes, which bounds anything a crash leaves behind. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.
Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 44968299bc..5a2729391c 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4221,7 +4221,6 @@
"title": "Delete intermediates?",
"forceTitle": "Force delete intermediates?",
"loadingPreview": "Checking what can be deleted…",
- "batchLimit": "This preview includes up to 50,000 eligible items. More remain in this scope; run Delete again after this batch finishes.",
"previewFailed": "Could not check what can be deleted.",
"summary": "Delete {{images}} and {{videos}} from {{projects}}?",
"reclaim": "Approximately {{size}} can be reclaimed.",
@@ -4250,14 +4249,14 @@
"confirm": "Delete",
"forceConfirm": "Force delete",
"startFailed": "Could not start deleting intermediates.",
- "startTimedOut": "The server did not answer in time, so the deletion may already be running. Selecting “{{action}}” again is safe: it resumes this same deletion rather than starting a second one.",
+ "startTimedOut": "The server did not answer in time, and no running deletion was found. Select “{{action}}” again to try once more.",
+ "startUnknown": "The server did not answer in time, and whether the deletion started could not be confirmed. Close this dialog and refresh the list; a running deletion appears above it.",
"keptReasons": "{{reasons}}.",
"keptReferenced": "{{items}} referenced by saved documents",
"keptActive": "{{items}} used by queued or running work",
"keptRecent": "{{items}} created recently",
"forceToggle": "Also delete items that saved documents still reference (advanced)",
- "previewExpired": "This check is no longer current. Check again before deleting.",
- "tooManyRows": "More than {{count, number}} projects match. Narrow the search or clear the selection and choose projects."
+ "previewExpired": "This check is no longer current. Check again before deleting."
},
"operation": {
"regionLabel": "Deletion status",
@@ -4275,10 +4274,10 @@
"failed": "Failed",
"pendingDisk": "Awaiting removal from disk",
"reclaimed": "Reclaimed",
- "retry": "Retry unresolved",
+ "runAgain": "Delete again",
"dismiss": "Dismiss",
- "retryFailed": "Could not retry the deletion.",
"lookupFailed": "Could not load deletion status.",
+ "lookupGone": "The server no longer knows this deletion; it may have restarted. Refresh the list, then delete again if anything remains.",
"pendingDiskNote": "Some files could not be removed yet. They are removed on the next server start and their space is not counted as reclaimed."
},
"empty": {
@@ -4319,9 +4318,6 @@
"measuringNote": "Sizes are still being measured; figures grow as measurement finishes."
},
"selection": {
- "checking": "Checking selection…",
- "estimateFailed": "Could not estimate selection. Refresh to retry.",
- "tooManyRows": "More than {{count, number}} matching projects. Narrow your search to review this selection.",
"estimate": "{{count, number}} selected · {{images}}, {{videos}}, about {{size}}",
"available": "{{images}}, {{videos}} unused · about {{size}} reclaimable"
}
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index bfbed8a5ee..9c589e0be6 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -55,6 +55,21 @@ const INTERMEDIATES_CALLERS = new Set(['admin', 'user']);
const createFaults = () => ({ capabilities: 'ok', intermediatesCaller: 'admin' });
const MOCK_USER_ID = 'fixture-user';
+
+/** The intermediates rows a summary shows under its filters; a `matching` preview scope resolves the same way. */
+const matchingIntermediates = (rows, { isAdmin, ownerFilter, projectId, search }) => {
+ const needle = (search ?? '').toLowerCase();
+ return rows
+ .filter((row) => ownerFilter === null || row.user_id === ownerFilter)
+ .filter((row) => projectId === null || row.project_id === projectId)
+ .filter(
+ (row) =>
+ !needle ||
+ [row.project_name, ...(isAdmin ? [row.user_display_name, row.user_email] : [])].some((value) =>
+ (value ?? '').toLowerCase().includes(needle)
+ )
+ );
+};
const MOCK_USER_TOKEN = 'mock-user-token';
const mockNonAdminUser = () => ({
@@ -111,7 +126,6 @@ const createState = (profile) => {
profile,
projects: new Map(fixture.projects.map((project) => [project.project_id, clone(project)])),
intermediates: fixture.intermediates.map(clone),
- intermediatesIdempotency: new Map(),
intermediatesOperations: new Map(),
intermediatesPreviews: new Map(),
queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),
@@ -1120,25 +1134,18 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(403, { detail: 'Only administrators can inspect other accounts' });
}
const ownerFilter = isAdmin ? ownerId : MOCK_USER_ID;
- const projectId = url.searchParams.get('project_id');
- const search = (url.searchParams.get('search') ?? '').toLowerCase();
const sort = url.searchParams.get('sort') ?? 'reclaimable_bytes';
const descending = (url.searchParams.get('order') ?? 'desc') === 'desc';
const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
const limit = Math.max(1, Number(url.searchParams.get('limit') ?? 50));
- const rows = state.intermediates
- .filter((row) => ownerFilter === null || row.user_id === ownerFilter)
- .filter((row) => projectId === null || row.project_id === projectId)
- .filter(
- (row) =>
- !search ||
- [row.project_name, ...(isAdmin ? [row.user_display_name, row.user_email] : [])].some((value) =>
- (value ?? '').toLowerCase().includes(search)
- )
- )
- .sort((left, right) =>
- (left.project_name ?? '').toLowerCase().localeCompare((right.project_name ?? '').toLowerCase())
- );
+ const rows = matchingIntermediates(state.intermediates, {
+ isAdmin,
+ ownerFilter,
+ projectId: url.searchParams.get('project_id'),
+ search: url.searchParams.get('search'),
+ }).sort((left, right) =>
+ (left.project_name ?? '').toLowerCase().localeCompare((right.project_name ?? '').toLowerCase())
+ );
if (sort === 'reclaimable_bytes') {
rows.sort((left, right) => (right.reclaimable_bytes - left.reclaimable_bytes) * (descending ? 1 : -1));
} else if (descending) {
@@ -1196,6 +1203,12 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
if (scope.kind === 'selection' && !isAdmin && scope.targets.some((target) => target.user_id !== MOCK_USER_ID)) {
return json(403, { detail: "Only administrators can clear another account's intermediates" });
}
+ if (scope.kind === 'matching' && !isAdmin && scope.user_id && scope.user_id !== MOCK_USER_ID) {
+ return json(403, { detail: "Only administrators can delete another account's intermediates" });
+ }
+ if (scope.kind === 'matching' && (scope.excluded?.length ?? 0) > 1000) {
+ return json(422, { detail: 'Too many excluded rows' });
+ }
const previewId = `preview-${state.intermediatesPreviews.size + 1}`;
const targets =
scope.kind === 'selection'
@@ -1206,7 +1219,23 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
)
: scope.kind === 'owner'
? state.intermediates.filter((row) => row.user_id === scope.user_id)
- : state.intermediates;
+ : scope.kind === 'matching'
+ ? // Mirrors IntermediatesService._resolve_scope: the summary's filters minus the excluded rows.
+ matchingIntermediates(state.intermediates, {
+ isAdmin,
+ ownerFilter: isAdmin ? (scope.user_id ?? null) : MOCK_USER_ID,
+ projectId: scope.project_id ?? null,
+ search: scope.search ?? null,
+ }).filter(
+ (row) =>
+ !(scope.excluded ?? []).some(
+ (target) => target.user_id === row.user_id && (target.project_id ?? null) === row.project_id
+ )
+ )
+ : state.intermediates;
+ if (scope.kind === 'matching' && targets.length === 0) {
+ return json(422, { detail: 'No rows match the filter' });
+ }
const force = requested?.mode === 'force';
const affectedDocuments = force
? targets
@@ -1247,13 +1276,19 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
unknown_size_count: 0,
}
);
+ if (force && affectedDocuments.length > 10_000) {
+ return json(422, { detail: 'This force delete would break more than 10000 documents; narrow the scope' });
+ }
const preview = {
preview_id: previewId,
mode: requested?.mode ?? 'safe',
scope: {
- kind: requested?.scope?.kind ?? 'owner',
- targets: requested?.scope?.targets ?? [],
- user_id: requested?.scope?.user_id ?? null,
+ kind: scope.kind ?? 'owner',
+ targets: scope.targets ?? [],
+ user_id: scope.user_id ?? null,
+ project_id: scope.project_id ?? null,
+ search: scope.search ?? null,
+ excluded: scope.excluded ?? [],
},
created_at: new Date().toISOString(),
expires_at: new Date(Date.now() + 600_000).toISOString(),
@@ -1266,16 +1301,14 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(201, preview);
}
+ if (method === 'GET' && path === '/api/v1/intermediates/operations') {
+ // Newest first; the real server retains a handful of settled operations per account.
+ return json(200, { items: [...state.intermediatesOperations.values()].reverse().slice(0, 5) });
+ }
+
if (method === 'POST' && path === '/api/v1/intermediates/operations') {
const requested = await readJsonBody(request);
- // Mirrors IntermediatesService.start_operation: a repeated key replays its operation, even once the
- // single-use preview is gone.
- const settled = state.intermediatesIdempotency.get(requested?.idempotency_key);
- if (settled) {
- return settled.previewId === requested.preview_id
- ? json(202, state.intermediatesOperations.get(settled.operationId))
- : json(409, { detail: 'Idempotency key was used for a different preview' });
- }
+ // Mirrors IntermediatesService.start_operation: a preview is confirmed once.
const frozen = state.intermediatesPreviews.get(requested?.preview_id);
if (!frozen) {
return json(404, { detail: 'Preview expired or unknown; request a new one' });
@@ -1307,11 +1340,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
reclaimed_bytes: impact.reclaimable_bytes,
unknown_size_count: impact.unknown_size_count,
pending_disk_cleanup: 0,
- unresolved_images: 0,
- unresolved_videos: 0,
},
- retried_from_operation_id: null,
- retried_by_operation_id: null,
};
for (const row of frozen.targets) {
row.images = {
@@ -1328,12 +1357,6 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
row.unknown_size_count = 0;
}
state.intermediatesOperations.set(operationId, operation);
- if (typeof requested.idempotency_key === 'string') {
- state.intermediatesIdempotency.set(requested.idempotency_key, {
- operationId,
- previewId: requested.preview_id,
- });
- }
return json(202, operation);
}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
index a1f7ec9026..202a1c66d0 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
@@ -5,14 +5,12 @@ import type { IntermediatesRow } from './types';
import {
EMPTY_SELECTION,
isRowSelected,
- resolveMatchingTargets,
resolveScope,
selectAllMatching,
summarizeSelection,
toggleRowSelection,
withRowSelected,
} from './selection';
-import { getIntermediatesRowKey } from './types';
const row = (projectId: string | null, overrides: Partial<IntermediatesRow> = {}): IntermediatesRow => ({
coverImageName: null,
@@ -31,6 +29,7 @@ const row = (projectId: string | null, overrides: Partial<IntermediatesRow> = {}
const page = [row('a'), row('b'), row(null)];
const totals = { reclaimableBytes: 5_000, rows: 12, safeImages: 40, safeVideos: 4, unknownSizeCount: 2 };
+const noFilters = { ownerId: 'alice', projectId: null, search: '' };
describe('row selection', () => {
it('toggles rows', () => {
@@ -56,8 +55,8 @@ describe('row selection', () => {
let selection = toggleRowSelection(EMPTY_SELECTION, firstPage[0]!);
selection = toggleRowSelection(selection, secondPage[1]!);
- expect(summarizeSelection(selection, totals)?.rows).toBe(2);
- expect(resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection })).toEqual({
+ expect(summarizeSelection(selection, totals).rows).toBe(2);
+ expect(resolveScope({ ...noFilters, selection })).toEqual({
kind: 'selection',
targets: [
{ projectId: 'a', userId: 'alice' },
@@ -68,7 +67,7 @@ describe('row selection', () => {
it('adds a row without disturbing an existing pick or an all-matching selection', () => {
const picked = withRowSelected(withRowSelected(EMPTY_SELECTION, page[0]!), page[0]!);
- expect(summarizeSelection(picked, totals)?.rows).toBe(1);
+ expect(summarizeSelection(picked, totals).rows).toBe(1);
expect(withRowSelected(selectAllMatching(), page[1]!)).toEqual(selectAllMatching());
});
@@ -77,26 +76,21 @@ describe('row selection', () => {
expect(selection.mode).toBe('all-matching');
expect(isRowSelected(selection, row('off-page'))).toBe(true);
- expect(summarizeSelection(selection, totals)).toBeNull();
- expect(summarizeSelection(selection, totals, [...page, row('off-page')])).toMatchObject({
- rows: 3,
- safeImages: 9,
- safeVideos: 6,
- reclaimableBytes: 300,
+ expect(summarizeSelection(selection, totals)).toEqual({
+ reclaimableBytes: 4_900,
+ rows: 11,
+ safeImages: 37,
+ safeVideos: 2,
+ unknownSizeCount: 2,
});
expect(toggleRowSelection(selection, page[1]!)).toEqual(selectAllMatching());
- const request = resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection });
- expect(request).toEqual({ kind: 'matching', excluded: new Set([getIntermediatesRowKey(page[1]!)]) });
- expect(
- resolveMatchingTargets(selection.mode === 'all-matching' ? selection.excluded : new Set(), [
- ...page,
- row('off-page'),
- ])
- ).toEqual([
- { userId: 'alice', projectId: 'a' },
- { userId: 'alice', projectId: null },
- { userId: 'alice', projectId: 'off-page' },
- ]);
+ expect(resolveScope({ ...noFilters, selection })).toEqual({
+ excluded: [{ projectId: 'b', userId: 'alice' }],
+ kind: 'matching',
+ projectId: null,
+ search: null,
+ userId: 'alice',
+ });
expect(isRowSelected(selection, page[0]!)).toBe(true);
expect(isRowSelected(selection, page[1]!)).toBe(false);
expect(isRowSelected(selection, page[2]!)).toBe(true);
@@ -108,9 +102,6 @@ describe('selection summary', () => {
const selection = toggleRowSelection(toggleRowSelection(EMPTY_SELECTION, page[0]!), page[2]!);
expect(summarizeSelection(selection, totals)).toEqual({
- referencedBytes: 20,
- referencedImages: 2,
- referencedVideos: 0,
reclaimableBytes: 200,
rows: 2,
safeImages: 6,
@@ -120,40 +111,75 @@ describe('selection summary', () => {
});
it('uses the server totals for all matching rows, which may exceed the loaded page', () => {
- expect(summarizeSelection(selectAllMatching(), totals)).toMatchObject({
- reclaimableBytes: 5_000,
- rows: 12,
- safeImages: 40,
- safeVideos: 4,
- unknownSizeCount: 2,
+ expect(summarizeSelection(selectAllMatching(), totals)).toEqual(totals);
+ });
+
+ it('refreshes a snapshot from the visible page before counting it', () => {
+ const refreshed = row('b', { images: { active: 0, recent: 0, referenced: 1, safe: 5 }, reclaimableBytes: 1_000 });
+
+ const excluded = toggleRowSelection(selectAllMatching(), page[1]!);
+ expect(summarizeSelection(excluded, totals, [page[0]!, refreshed])).toMatchObject({
+ reclaimableBytes: 4_000,
+ rows: 11,
+ safeImages: 35,
+ });
+ const picked = toggleRowSelection(EMPTY_SELECTION, page[1]!);
+ expect(summarizeSelection(picked, totals, [refreshed])).toMatchObject({ reclaimableBytes: 1_000, safeImages: 5 });
+ });
+
+ it('never estimates all-matching below what is visibly selected when an excluded row has vanished', () => {
+ // Totals now cover one row; the excluded row is gone off-page, but its snapshot would cancel the survivor.
+ const survivor = row('c');
+ const selection = toggleRowSelection(selectAllMatching(), page[0]!);
+ const fewTotals = { reclaimableBytes: 100, rows: 1, safeImages: 3, safeVideos: 2, unknownSizeCount: 0 };
+
+ expect(summarizeSelection(selection, fewTotals, [survivor])).toEqual({
+ reclaimableBytes: 100,
+ rows: 1,
+ safeImages: 3,
+ safeVideos: 2,
+ unknownSizeCount: 0,
+ });
+ expect(summarizeSelection(selection, fewTotals, [])).toEqual({
+ reclaimableBytes: 0,
+ rows: 0,
+ safeImages: 0,
+ safeVideos: 0,
+ unknownSizeCount: 0,
});
});
});
describe('scope resolution', () => {
it('turns all-matching without a filter into the owner or everyone scope', () => {
- expect(resolveScope({ hasSubsetFilter: false, ownerId: 'alice', selection: selectAllMatching() })).toEqual({
+ expect(resolveScope({ ...noFilters, selection: selectAllMatching() })).toEqual({
kind: 'owner',
userId: 'alice',
});
- expect(resolveScope({ hasSubsetFilter: false, ownerId: null, selection: selectAllMatching() })).toEqual({
+ expect(resolveScope({ ...noFilters, ownerId: null, selection: selectAllMatching() })).toEqual({
kind: 'everyone',
});
});
- it('turns picks into explicit targets whichever page showed them', () => {
+ it('turns picks into explicit targets whichever page showed them, ignoring the filters', () => {
const picks = toggleRowSelection(EMPTY_SELECTION, page[2]!);
- expect(resolveScope({ hasSubsetFilter: true, ownerId: 'alice', selection: picks })).toEqual({
+ expect(resolveScope({ ownerId: 'alice', projectId: 'p', search: 'port', selection: picks })).toEqual({
kind: 'selection',
targets: [{ projectId: null, userId: 'alice' }],
});
});
- it('leaves all-matching under a filter unresolved rather than narrowing it to the loaded page', () => {
- expect(resolveScope({ hasSubsetFilter: true, ownerId: 'alice', selection: selectAllMatching() })).toEqual({
+ it('carries the filters of an all-matching selection in a matching scope', () => {
+ expect(
+ resolveScope({ ownerId: 'alice', projectId: null, search: ' port ', selection: selectAllMatching() })
+ ).toEqual({ excluded: [], kind: 'matching', projectId: null, search: 'port', userId: 'alice' });
+ expect(resolveScope({ ownerId: null, projectId: 'p', search: '', selection: selectAllMatching() })).toEqual({
+ excluded: [],
kind: 'matching',
- excluded: new Set(),
+ projectId: 'p',
+ search: null,
+ userId: null,
});
});
});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
index a12b2df9e8..57500a9d22 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
@@ -5,12 +5,12 @@ import { getIntermediatesRowKey } from './types';
/**
* Row selection for the manager. `rows` keeps a snapshot of every picked row, so picks survive paging and can be
* summarized and targeted without the page that showed them; `all-matching` stands for every row the current
- * filters match, including rows never loaded, minus explicit exclusions. It resolves against the server when a
- * preview is requested.
+ * filters match, including rows never loaded, minus the excluded rows, whose snapshots keep the estimate honest. The
+ * server resolves what "all matching" is when a preview is requested.
*/
export type IntermediatesSelection =
| { mode: 'rows'; rows: ReadonlyMap<string, IntermediatesRow> }
- | { mode: 'all-matching'; excluded: ReadonlySet<string> };
+ | { mode: 'all-matching'; excluded: ReadonlyMap<string, IntermediatesRow> };
export const EMPTY_SELECTION: IntermediatesSelection = { mode: 'rows', rows: new Map() };
@@ -29,11 +29,11 @@ export const toggleRowSelection = (
): IntermediatesSelection => {
const key = getIntermediatesRowKey(row);
if (selection.mode === 'all-matching') {
- const excluded = new Set(selection.excluded);
+ const excluded = new Map(selection.excluded);
if (excluded.has(key)) {
excluded.delete(key);
} else {
- excluded.add(key);
+ excluded.set(key, row);
}
return { mode: 'all-matching', excluded };
}
@@ -46,116 +46,90 @@ export const toggleRowSelection = (
return { mode: 'rows', rows };
};
-export const selectAllMatching = (): IntermediatesSelection => ({ mode: 'all-matching', excluded: new Set() });
+export const selectAllMatching = (): IntermediatesSelection => ({ mode: 'all-matching', excluded: new Map() });
export interface SelectionSummary {
rows: number;
safeImages: number;
safeVideos: number;
- referencedImages: number;
- referencedVideos: number;
reclaimableBytes: number;
- referencedBytes: number;
unknownSizeCount: number;
}
-/**
- * Sums the selection. Explicit picks are summed from their snapshots, whichever page showed them; "all matching"
- * uses the server's totals. With exclusions, a complete current matching snapshot is required: old excluded-row
- * snapshots cannot tell us whether those rows still exist or how their counts changed.
- */
-export const summarizeSelection = (
- selection: IntermediatesSelection,
- totals: { rows: number; safeImages: number; safeVideos: number; reclaimableBytes: number; unknownSizeCount: number },
- matchingRows?: readonly IntermediatesRow[],
- visibleRows: readonly IntermediatesRow[] = []
-): SelectionSummary | null => {
- if (selection.mode === 'all-matching') {
- if (selection.excluded.size > 0) {
- return matchingRows
- ? summarizeSelection(
- {
- mode: 'rows',
- rows: new Map(
- matchingRows
- .filter((row) => isRowSelected(selection, row))
- .map((row) => [getIntermediatesRowKey(row), row])
- ),
- },
- totals
- )
- : null;
- }
- return {
- referencedBytes: 0,
- referencedImages: 0,
- referencedVideos: 0,
- reclaimableBytes: totals.reclaimableBytes,
- rows: totals.rows,
- safeImages: totals.safeImages,
- safeVideos: totals.safeVideos,
- unknownSizeCount: totals.unknownSizeCount,
- };
- }
+export type SelectionTotals = SelectionSummary;
- const summary: SelectionSummary = {
- referencedBytes: 0,
- referencedImages: 0,
- referencedVideos: 0,
- reclaimableBytes: 0,
- rows: 0,
- safeImages: 0,
- safeVideos: 0,
- unknownSizeCount: 0,
- };
-
- const freshRows = new Map(visibleRows.map((row) => [getIntermediatesRowKey(row), row]));
- for (const [key, snapshot] of selection.rows) {
- const row = freshRows.get(key) ?? snapshot;
+const sumRows = (rows: Iterable<IntermediatesRow>): SelectionSummary => {
+ const summary: SelectionSummary = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos: 0, unknownSizeCount: 0 };
+ for (const row of rows) {
summary.rows += 1;
summary.safeImages += row.images.safe;
summary.safeVideos += row.videos.safe;
- summary.referencedImages += row.images.referenced;
- summary.referencedVideos += row.videos.referenced;
summary.reclaimableBytes += row.reclaimableBytes;
- summary.referencedBytes += row.referencedBytes;
summary.unknownSizeCount += row.unknownSizeCount;
}
-
return summary;
};
-const toTarget = ({ projectId, userId }: IntermediatesScopeTarget): IntermediatesScopeTarget => ({ projectId, userId });
-
/**
- * What a confirmation acts on before it reaches the server. `matching` is every row the current filters match minus
- * the exclusions; the cleanup scope cannot express filters, so it must be resolved against a complete matching read
- * with `resolveMatchingTargets` before a preview is requested.
+ * Sums the selection. Explicit picks are summed from their snapshots, whichever page showed them; "all matching"
+ * starts from the server's totals and subtracts the excluded rows, never going below what is visibly selected (an
+ * excluded row may have vanished off-page since its snapshot). A row on the current page is read fresh, since its
+ * snapshot may predate a cleanup; the server preview stays the authority for what a delete does.
*/
-export type IntermediatesScopeRequest = IntermediatesScope | { kind: 'matching'; excluded: ReadonlySet<string> };
+export const summarizeSelection = (
+ selection: IntermediatesSelection,
+ totals: SelectionTotals,
+ visibleRows: readonly IntermediatesRow[] = []
+): SelectionSummary => {
+ const freshRows = new Map(visibleRows.map((row) => [getIntermediatesRowKey(row), row]));
+ const fresh = (key: string, snapshot: IntermediatesRow): IntermediatesRow => freshRows.get(key) ?? snapshot;
+ if (selection.mode === 'rows') {
+ return sumRows([...selection.rows].map(([key, snapshot]) => fresh(key, snapshot)));
+ }
+ const excluded = sumRows([...selection.excluded].map(([key, snapshot]) => fresh(key, snapshot)));
+ const visible = sumRows(visibleRows.filter((row) => isRowSelected(selection, row)));
+ const remaining = (field: keyof SelectionSummary): number =>
+ Math.max(totals[field] - excluded[field], visible[field]);
+ return {
+ reclaimableBytes: remaining('reclaimableBytes'),
+ rows: remaining('rows'),
+ safeImages: remaining('safeImages'),
+ safeVideos: remaining('safeVideos'),
+ unknownSizeCount: remaining('unknownSizeCount'),
+ };
+};
-/**
- * Without a row filter or exclusions, "all matching" is exactly the owner filter (or everyone), which the server can
- * freeze without the client enumerating rows. Explicit picks become their targets.
- */
-export const resolveScope = (options: {
- selection: IntermediatesSelection;
- hasSubsetFilter: boolean;
+const toTarget = ({ projectId, userId }: IntermediatesScopeTarget): IntermediatesScopeTarget => ({ projectId, userId });
+
+/** The summary filters a selection was made under; a `matching` scope carries them to the server. */
+export interface IntermediatesScopeFilters {
ownerId: string | null;
-}): IntermediatesScopeRequest => {
- const { hasSubsetFilter, ownerId, selection } = options;
+ projectId: string | null;
+ search: string;
+}
+/**
+ * What a confirmation acts on. Explicit picks become their targets. Without exclusions, a project filter or a
+ * search, "all matching" is exactly the owner filter (or everyone); otherwise the server resolves the filters.
+ */
+export const resolveScope = ({
+ ownerId,
+ projectId,
+ search,
+ selection,
+}: IntermediatesScopeFilters & { selection: IntermediatesSelection }): IntermediatesScope => {
if (selection.mode === 'rows') {
return { kind: 'selection', targets: [...selection.rows.values()].map(toTarget) };
}
- if (selection.excluded.size > 0 || hasSubsetFilter) {
- return { kind: 'matching', excluded: selection.excluded };
+ const trimmed = search.trim();
+ if (selection.excluded.size === 0 && projectId === null && !trimmed) {
+ return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
}
- return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
+ return {
+ excluded: [...selection.excluded.values()].map(toTarget),
+ kind: 'matching',
+ projectId,
+ search: trimmed || null,
+ userId: ownerId,
+ };
};
-
-/** The explicit targets of a `matching` request, given every row the filters match. */
-export const resolveMatchingTargets = (
- excluded: ReadonlySet<string>,
- matchingRows: readonly IntermediatesRow[]
-): IntermediatesScopeTarget[] => matchingRows.filter((row) => !excluded.has(getIntermediatesRowKey(row))).map(toTarget);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
index 4107b3426d..f3d925e8e5 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
@@ -65,10 +65,21 @@ export interface IntermediatesSummary {
canManageEveryone: boolean;
}
+/** Every row the summary filters match minus `excluded`, resolved by the server so no page needs enumerating. */
+export interface IntermediatesMatchingScope {
+ kind: 'matching';
+ /** The owner filter; null is the caller's account, or every account for an administrator. */
+ userId: string | null;
+ projectId: string | null;
+ search: string | null;
+ excluded: IntermediatesScopeTarget[];
+}
+
export type IntermediatesScope =
| { kind: 'selection'; targets: IntermediatesScopeTarget[] }
| { kind: 'owner'; userId: string }
- | { kind: 'everyone' };
+ | { kind: 'everyone' }
+ | IntermediatesMatchingScope;
export interface IntermediatesImpact {
deleteImages: number;
@@ -107,8 +118,8 @@ export interface IntermediatesPreview {
createdAt: string;
expiresAt: string;
targetRows: number;
- hasMoreEligible: boolean;
impact: IntermediatesImpact;
+ /** Confirming acknowledges these; a document saved after the preview keeps its media. */
affectedDocuments: IntermediatesAffectedDocument[];
/** Every affected document; the server lists only the first of them. */
affectedDocumentsTotal: number;
@@ -127,25 +138,24 @@ export interface IntermediatesOperationProgress {
/** Deleted items whose size was never measured; their bytes are not in `reclaimedBytes`. */
unknownSizeCount: number;
pendingDiskCleanup: number;
- unresolvedImages: number;
- unresolvedVideos: number;
}
+/** A cleanup run. The server keeps it in memory only: a restart forgets it, and requesting the scope again is the retry. */
export interface IntermediatesOperation {
operationId: string;
userId: string;
mode: IntermediatesCleanupMode;
+ /** The scope as requested, so the same request can be made again. */
scope: IntermediatesScope;
status: IntermediatesOperationStatus;
createdAt: string;
startedAt: string | null;
completedAt: string | null;
error: string | null;
+ /** Deletions the preview expected. */
targetImages: number;
targetVideos: number;
progress: IntermediatesOperationProgress;
- retriedFromOperationId: string | null;
- retriedByOperationId: string | null;
}
export const getIntermediatesRowKey = (target: IntermediatesScopeTarget): string =>
@@ -166,8 +176,7 @@ export const getOperationProcessed = (operation: IntermediatesOperation): number
export const isOperationSettled = (operation: IntermediatesOperation): boolean =>
operation.status === 'completed' || operation.status === 'failed';
-/** Only unresolved targets can be retried, once the operation has stopped and no retry has taken them over. */
-export const isOperationRetryable = (operation: IntermediatesOperation): boolean =>
+/** A stopped or partly failed run left work behind that requesting the same scope again picks up. */
+export const canRunOperationAgain = (operation: IntermediatesOperation): boolean =>
isOperationSettled(operation) &&
- operation.retriedByOperationId === null &&
- operation.progress.unresolvedImages + operation.progress.unresolvedVideos > 0;
+ (operation.status === 'failed' || operation.progress.failedImages + operation.progress.failedVideos > 0);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
index 9b89db8ccd..78a80253b8 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
@@ -1,6 +1,12 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createIntermediatesPreview, getIntermediatesSummary, mapIntermediatesOperation } from './api';
+import {
+ createIntermediatesPreview,
+ getIntermediatesSummary,
+ listIntermediatesOperations,
+ mapIntermediatesOperation,
+ startIntermediatesOperation,
+} from './api';
const summaryDto = {
can_manage_everyone: false,
@@ -35,6 +41,56 @@ const summaryDto = {
},
};
+const previewDto = (scope: unknown) => ({
+ affected_documents: [],
+ affected_documents_total: 0,
+ created_at: 'now',
+ expires_at: 'later',
+ impact: {
+ delete_images: 1,
+ delete_videos: 0,
+ keep_active_images: 0,
+ keep_active_videos: 0,
+ keep_recent_images: 0,
+ keep_recent_videos: 0,
+ keep_referenced_images: 0,
+ keep_referenced_videos: 0,
+ reclaimable_bytes: 5,
+ unknown_size_count: 0,
+ },
+ mode: 'safe',
+ preview_id: 'p1',
+ scope,
+ target_rows: 1,
+});
+
+const operationDto = {
+ completed_at: null,
+ created_at: 'now',
+ error: null,
+ mode: 'force' as const,
+ operation_id: 'op',
+ progress: {
+ deleted_images: 1,
+ deleted_videos: 0,
+ failed_images: 2,
+ failed_videos: 0,
+ pending_disk_cleanup: 1,
+ processed_images: 3,
+ processed_videos: 0,
+ reclaimed_bytes: 10,
+ retained_images: 0,
+ retained_videos: 0,
+ unknown_size_count: 1,
+ },
+ scope: { kind: 'everyone' as const, targets: [], user_id: null },
+ started_at: 'now',
+ status: 'running' as const,
+ target_images: 3,
+ target_videos: 0,
+ user_id: 'admin',
+};
+
const fetchJson = (body: unknown, status = 200) =>
vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }))
@@ -75,31 +131,9 @@ describe('intermediates transport', () => {
expect(summary.recentGraceSeconds).toBe(1800);
});
- it('serializes a selection scope with snake_case targets', async () => {
+ it('serializes a selection scope with snake_case targets on the flat wire model', async () => {
const fetchMock = fetchJson(
- {
- affected_documents: [],
- affected_documents_total: 0,
- created_at: 'now',
- expires_at: 'later',
- has_more_eligible: true,
- impact: {
- delete_images: 1,
- delete_videos: 0,
- keep_active_images: 0,
- keep_active_videos: 0,
- keep_recent_images: 0,
- keep_recent_videos: 0,
- keep_referenced_images: 0,
- keep_referenced_videos: 0,
- reclaimable_bytes: 5,
- unknown_size_count: 0,
- },
- mode: 'safe',
- preview_id: 'p1',
- scope: { kind: 'selection', targets: [{ project_id: null, user_id: 'a' }], user_id: null },
- target_rows: 1,
- },
+ previewDto({ kind: 'selection', targets: [{ project_id: null, user_id: 'a' }], user_id: null }),
201
);
vi.stubGlobal('fetch', fetchMock);
@@ -112,47 +146,63 @@ describe('intermediates transport', () => {
const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
expect(JSON.parse(String(init.body))).toEqual({
mode: 'safe',
- scope: { kind: 'selection', targets: [{ project_id: null, user_id: 'a' }], user_id: null },
+ scope: {
+ excluded: [],
+ kind: 'selection',
+ project_id: null,
+ search: null,
+ targets: [{ project_id: null, user_id: 'a' }],
+ user_id: null,
+ },
});
expect(preview.scope).toEqual({ kind: 'selection', targets: [{ projectId: null, userId: 'a' }] });
expect(preview.impact.deleteImages).toBe(1);
- expect(preview.hasMoreEligible).toBe(true);
});
- it('maps operation progress including the unresolved counts a retry depends on', () => {
- const operation = mapIntermediatesOperation({
- completed_at: null,
- created_at: 'now',
- error: null,
- mode: 'force',
- operation_id: 'op',
- progress: {
- deleted_images: 1,
- deleted_videos: 0,
- failed_images: 2,
- failed_videos: 0,
- pending_disk_cleanup: 1,
- processed_images: 3,
- processed_videos: 0,
- reclaimed_bytes: 10,
- retained_images: 0,
- retained_videos: 0,
- unknown_size_count: 1,
- unresolved_images: 2,
- unresolved_videos: 0,
- },
- retried_by_operation_id: null,
- retried_from_operation_id: 'previous',
- scope: { kind: 'everyone', targets: [], user_id: null },
- started_at: 'now',
- status: 'running',
- target_images: 3,
- target_videos: 0,
- user_id: 'admin',
- });
+ it('round-trips a matching scope with its filters and exclusions', async () => {
+ const wire = {
+ excluded: [{ project_id: null, user_id: 'a' }],
+ kind: 'matching',
+ project_id: 'p',
+ search: 'port',
+ targets: [],
+ user_id: null,
+ };
+ const fetchMock = fetchJson(previewDto(wire), 201);
+ vi.stubGlobal('fetch', fetchMock);
+ const scope = {
+ excluded: [{ projectId: null, userId: 'a' }],
+ kind: 'matching' as const,
+ projectId: 'p',
+ search: 'port',
+ userId: null,
+ };
+
+ const preview = await createIntermediatesPreview({ mode: 'safe', scope });
+
+ expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body)).scope).toEqual(wire);
+ expect(preview.scope).toEqual(scope);
+ });
- expect(operation.progress).toMatchObject({ pendingDiskCleanup: 1, unknownSizeCount: 1, unresolvedImages: 2 });
+ it('maps operation progress and scope', () => {
+ const operation = mapIntermediatesOperation(operationDto);
+
+ expect(operation.progress).toMatchObject({ failedImages: 2, pendingDiskCleanup: 1, unknownSizeCount: 1 });
expect(operation.scope).toEqual({ kind: 'everyone' });
- expect(operation.retriedFromOperationId).toBe('previous');
+ expect(operation.targetImages).toBe(3);
+ });
+
+ it('starts with only the preview id and lists operations from the items envelope', async () => {
+ const startFetch = fetchJson(operationDto, 202);
+ vi.stubGlobal('fetch', startFetch);
+ const started = await startIntermediatesOperation({ previewId: 'p1' }, new AbortController().signal);
+ expect(JSON.parse(String((startFetch.mock.calls[0]![1] as RequestInit).body))).toEqual({ preview_id: 'p1' });
+ expect(started.operationId).toBe('op');
+
+ const listFetch = fetchJson({ items: [operationDto, { ...operationDto, operation_id: 'older' }] });
+ vi.stubGlobal('fetch', listFetch);
+ const listed = await listIntermediatesOperations();
+ expect(String(listFetch.mock.calls[0]?.[0])).toMatch(/\/api\/v1\/intermediates\/operations$/);
+ expect(listed.map((operation) => operation.operationId)).toEqual(['op', 'older']);
});
});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
index 484c6fb03c..406dbb310a 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
@@ -33,10 +33,14 @@ interface ScopeTargetDTO {
project_id: string | null;
}
+/** One flat model on the wire; each kind reads the fields it needs and the rest stay empty. */
interface ScopeDTO {
- kind: 'selection' | 'owner' | 'everyone';
- targets: ScopeTargetDTO[];
- user_id: string | null;
+ kind: 'selection' | 'owner' | 'everyone' | 'matching';
+ targets?: ScopeTargetDTO[];
+ user_id?: string | null;
+ project_id?: string | null;
+ search?: string | null;
+ excluded?: ScopeTargetDTO[];
}
interface RowDTO extends ScopeTargetDTO {
@@ -100,7 +104,6 @@ interface PreviewDTO {
created_at: string;
expires_at: string;
target_rows: number;
- has_more_eligible: boolean;
impact: ImpactDTO;
affected_documents: AffectedDocumentDTO[];
affected_documents_total: number;
@@ -118,8 +121,6 @@ interface ProgressDTO {
reclaimed_bytes: number;
unknown_size_count: number;
pending_disk_cleanup: number;
- unresolved_images: number;
- unresolved_videos: number;
}
export interface IntermediatesOperationDTO {
@@ -135,8 +136,6 @@ export interface IntermediatesOperationDTO {
target_images: number;
target_videos: number;
progress: ProgressDTO;
- retried_from_operation_id: string | null;
- retried_by_operation_id: string | null;
}
const mapCounts = (dto: KindCountsDTO): IntermediatesKindCounts => ({
@@ -151,6 +150,11 @@ const mapTarget = (dto: ScopeTargetDTO): IntermediatesScopeTarget => ({
userId: dto.user_id,
});
+const toTargetDTO = (target: IntermediatesScopeTarget): ScopeTargetDTO => ({
+ project_id: target.projectId,
+ user_id: target.userId,
+});
+
const mapRow = (dto: RowDTO): IntermediatesRow => ({
coverImageName: dto.cover_image_name,
images: mapCounts(dto.images),
@@ -172,23 +176,45 @@ const mapScope = (dto: ScopeDTO): IntermediatesScope => {
if (dto.kind === 'owner') {
return { kind: 'owner', userId: dto.user_id ?? '' };
}
+ if (dto.kind === 'matching') {
+ return {
+ excluded: (dto.excluded ?? []).map(mapTarget),
+ kind: 'matching',
+ projectId: dto.project_id ?? null,
+ search: dto.search ?? null,
+ userId: dto.user_id ?? null,
+ };
+ }
- return { kind: 'selection', targets: dto.targets.map(mapTarget) };
+ return { kind: 'selection', targets: (dto.targets ?? []).map(mapTarget) };
};
const toScopeDTO = (scope: IntermediatesScope): ScopeDTO => {
- if (scope.kind === 'everyone') {
- return { kind: 'everyone', targets: [], user_id: null };
- }
+ const empty: Required<ScopeDTO> = {
+ excluded: [],
+ kind: scope.kind,
+ project_id: null,
+ search: null,
+ targets: [],
+ user_id: null,
+ };
if (scope.kind === 'owner') {
- return { kind: 'owner', targets: [], user_id: scope.userId };
+ return { ...empty, user_id: scope.userId };
+ }
+ if (scope.kind === 'selection') {
+ return { ...empty, targets: scope.targets.map(toTargetDTO) };
+ }
+ if (scope.kind === 'matching') {
+ return {
+ ...empty,
+ excluded: scope.excluded.map(toTargetDTO),
+ project_id: scope.projectId,
+ search: scope.search,
+ user_id: scope.userId,
+ };
}
- return {
- kind: 'selection',
- targets: scope.targets.map((target) => ({ project_id: target.projectId, user_id: target.userId })),
- user_id: null,
- };
+ return empty;
};
const mapImpact = (dto: ImpactDTO): IntermediatesImpact => ({
@@ -226,8 +252,6 @@ const mapProgress = (dto: ProgressDTO): IntermediatesOperationProgress => ({
retainedImages: dto.retained_images,
retainedVideos: dto.retained_videos,
unknownSizeCount: dto.unknown_size_count,
- unresolvedImages: dto.unresolved_images,
- unresolvedVideos: dto.unresolved_videos,
});
export const mapIntermediatesOperation = (dto: IntermediatesOperationDTO): IntermediatesOperation => ({
@@ -237,8 +261,6 @@ export const mapIntermediatesOperation = (dto: IntermediatesOperationDTO): Inter
mode: dto.mode,
operationId: dto.operation_id,
progress: mapProgress(dto.progress),
- retriedByOperationId: dto.retried_by_operation_id,
- retriedFromOperationId: dto.retried_from_operation_id,
scope: mapScope(dto.scope),
startedAt: dto.started_at,
status: dto.status,
@@ -259,8 +281,6 @@ const PROGRESS_KEYS = [
'reclaimed_bytes',
'unknown_size_count',
'pending_disk_cleanup',
- 'unresolved_images',
- 'unresolved_videos',
] as const satisfies readonly (keyof ProgressDTO)[];
const OPERATION_STATUSES = new Set<unknown>(['pending', 'running', 'completed', 'failed']);
const CLEANUP_MODES = new Set<unknown>(['safe', 'force']);
@@ -268,16 +288,23 @@ const CLEANUP_MODES = new Set<unknown>(['safe', 'force']);
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;
const isCount = (value: unknown): boolean => typeof value === 'number' && Number.isFinite(value);
const isNullableString = (value: unknown): boolean => value === null || typeof value === 'string';
+const isTargetList = (value: unknown): boolean =>
+ value === undefined ||
+ (Array.isArray(value) &&
+ value.every(
+ (target) => isRecord(target) && typeof target.user_id === 'string' && isNullableString(target.project_id)
+ ));
const isScopeDTO = (value: unknown): value is ScopeDTO =>
isRecord(value) &&
(value.kind === 'everyone' ||
(value.kind === 'owner' && isNullableString(value.user_id)) ||
- (value.kind === 'selection' &&
- Array.isArray(value.targets) &&
- value.targets.every(
- (target) => isRecord(target) && typeof target.user_id === 'string' && isNullableString(target.project_id)
- )));
+ (value.kind === 'selection' && isTargetList(value.targets)) ||
+ (value.kind === 'matching' &&
+ [value.user_id, value.project_id, value.search].every(
+ (field) => field === undefined || isNullableString(field)
+ ) &&
+ isTargetList(value.excluded)));
const isOperationDTO = (value: unknown): value is IntermediatesOperationDTO =>
isRecord(value) &&
@@ -290,9 +317,7 @@ const isOperationDTO = (value: unknown): value is IntermediatesOperationDTO =>
isCount(value.target_videos) &&
isRecord(value.progress) &&
PROGRESS_KEYS.every((key) => isCount((value.progress as Record<string, unknown>)[key])) &&
- [value.created_at, value.started_at, value.completed_at, value.error].every(isNullableString) &&
- isNullableString(value.retried_from_operation_id) &&
- isNullableString(value.retried_by_operation_id);
+ [value.created_at, value.started_at, value.completed_at, value.error].every(isNullableString);
/** Reads a socket event's operation, which arrives unvalidated; a malformed event yields null. */
export const parseIntermediatesOperationEvent = (payload: unknown): IntermediatesOperation | null =>
@@ -375,44 +400,41 @@ export const createIntermediatesPreview = async (
previewId: dto.preview_id,
scope: mapScope(dto.scope),
targetRows: dto.target_rows,
- hasMoreEligible: dto.has_more_eligible,
};
};
/** Long enough for a slow server to accept; short enough that a hung request cannot lock the confirmation. */
const START_TIMEOUT_MS = 30_000;
-/** Rejects with a `TimeoutError` DOMException when the server does not answer in time. */
+/**
+ * Confirms a preview, which the server accepts once. Rejects with a `TimeoutError` DOMException when the server does
+ * not answer in time; the run may still have started, and `listIntermediatesOperations` finds it.
+ */
export const startIntermediatesOperation = async (
- request: { previewId: string; idempotencyKey: string },
+ request: { previewId: string },
signal: AbortSignal
): Promise<IntermediatesOperation> =>
mapIntermediatesOperation(
await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations`, {
- body: JSON.stringify({ idempotency_key: request.idempotencyKey, preview_id: request.previewId }),
+ body: JSON.stringify({ preview_id: request.previewId }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.any([signal, AbortSignal.timeout(START_TIMEOUT_MS)]),
})
);
-export const getIntermediatesOperation = async (
- operationId: string,
- signal?: AbortSignal
-): Promise<IntermediatesOperation> =>
- mapIntermediatesOperation(
- await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations/${encodeURIComponent(operationId)}`, {
- signal,
- })
+/** The account's running and recently settled operations, newest first. */
+export const listIntermediatesOperations = async (signal?: AbortSignal): Promise<IntermediatesOperation[]> =>
+ (await apiFetchJson<{ items: IntermediatesOperationDTO[] }>(`${BASE}/operations`, { signal })).items.map(
+ mapIntermediatesOperation
);
-export const retryIntermediatesOperation = async (
+export const getIntermediatesOperation = async (
operationId: string,
signal?: AbortSignal
): Promise<IntermediatesOperation> =>
mapIntermediatesOperation(
- await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations/${encodeURIComponent(operationId)}/retry`, {
- method: 'POST',
+ await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations/${encodeURIComponent(operationId)}`, {
signal,
})
);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
index 7d5b4bf1a2..cbae08dbc9 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
@@ -1,6 +1,7 @@
import type { IntermediatesOperation } from '@features/intermediates/core/types';
import type { QueryClient } from '@tanstack/react-query';
+import { isOperationSettled } from '@features/intermediates/core/types';
import {
captureAccountScope,
isAccountScopeCurrent,
@@ -9,83 +10,24 @@ import {
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
-import { getIntermediatesOperation, startIntermediatesOperation } from './api';
+import { listIntermediatesOperations } from './api';
import { intermediatesKeys } from './keys';
import { attachIntermediatesRealtime } from './realtime';
/**
* The operation the manager is following. Kept outside the component so closing Settings while a cleanup runs and
- * reopening it later shows the same operation, its result and its retry affordance.
+ * reopening it later shows the same operation and its result. The server, not this tab, remembers running work: a
+ * manager that opens with nothing followed asks it, so a reload picks a running cleanup back up.
*/
-export const activeOperationStore = createExternalStore<{
- operationId: string | null;
- /** Why replaying a start whose response was lost failed; cleared when the manager next opens. */
- recoveryError: unknown;
-}>({ operationId: null, recoveryError: null });
-
-interface PendingStart {
- previewId: string;
- idempotencyKey: string;
-}
-
-/**
- * A Confirm whose response never arrived (a reload, a closed section, a timeout) is replayed once when the manager
- * next opens; its idempotency key makes the replay return the same operation. A start that settled with an error is
- * cleared, so only a fresh Confirm in the dialog can run it again.
- */
-interface Receipt {
- operationId?: string;
- pendingStart?: PendingStart;
-}
-
-// Keyed per account so a start fenced by sign-out can still be cleared under the account that made it.
-const receiptKey = (owner: AccountScope = captureAccountScope()): string => {
- return `invokeai:webv2:intermediates-receipt:${owner.accountId ?? 'local'}${owner.storageSuffix}`;
-};
-
-const readReceipt = (owner?: AccountScope): Receipt => {
- try {
- return JSON.parse(sessionStorage.getItem(receiptKey(owner)) ?? '{}') as Receipt;
- } catch {
- return {};
- }
-};
-
-const writeReceipt = (receipt: Receipt, owner?: AccountScope): void => {
- try {
- if (!receipt.operationId && !receipt.pendingStart) {
- sessionStorage.removeItem(receiptKey(owner));
- } else {
- sessionStorage.setItem(receiptKey(owner), JSON.stringify(receipt));
- }
- } catch {
- // A private-mode storage failure still leaves the in-memory operation visible this session.
- }
-};
-
-export const recordPendingIntermediatesStart = (pendingStart: PendingStart): void => {
- writeReceipt({ ...readReceipt(), pendingStart });
-};
-
-const isPendingStartCurrent = (pendingStart: PendingStart, owner?: AccountScope): boolean => {
- const current = readReceipt(owner).pendingStart;
- return current?.previewId === pendingStart.previewId && current.idempotencyKey === pendingStart.idempotencyKey;
-};
-
-/** `owner` defaults to the current account; pass the one that recorded the start once it may have signed out. */
-export const clearPendingIntermediatesStart = (owner?: AccountScope): void => {
- const { operationId } = readReceipt(owner);
- writeReceipt({ operationId }, owner);
-};
+export const activeOperationStore = createExternalStore<{ operationId: string | null }>({ operationId: null });
registerAccountOwnedResource({
- clear: () => activeOperationStore.setSnapshot({ operationId: null, recoveryError: null }),
+ clear: () => activeOperationStore.setSnapshot({ operationId: null }),
name: 'intermediates-active-operation',
});
export const followIntermediatesOperation = (operationId: string | null): void => {
- activeOperationStore.patchSnapshot({ operationId });
- writeReceipt({ operationId: operationId ?? undefined });
+ activeOperationStore.setSnapshot({ operationId });
};
/** Follows an operation the server just returned, seeding its query so the panel needs no extra lookup. */
@@ -98,95 +40,75 @@ export const adoptIntermediatesOperation = (
followIntermediatesOperation(operation.operationId);
};
-/** Walks the retry chain to the operation that currently owns the unresolved targets. */
-export const findLatestIntermediatesRetry = async (
- operationId: string,
- signal: AbortSignal
-): Promise<IntermediatesOperation> => {
- let operation = await getIntermediatesOperation(operationId, signal);
- const visited = new Set<string>([operationId]);
- while (operation.retriedByOperationId && !visited.has(operation.retriedByOperationId)) {
- visited.add(operation.retriedByOperationId);
- operation = await getIntermediatesOperation(operation.retriedByOperationId, signal);
- }
- return operation;
-};
+/** A fresh listing after a timed-out start must answer quickly or not at all; the dialog stays usable either way. */
+const FRESH_LISTING_TIMEOUT_MS = 10_000;
-let attachedManagers = 0;
-// Single-flight per account and receipt, so a remount (or StrictMode's replayed mount) never repeats the request.
-const reconciling = new Set<string>();
+// One listing per account at a time, so a remount (or StrictMode's replayed mount) shares a request; a sign-out and
+// back in gets a fresh one.
+const listings = new Map<string, Promise<IntermediatesOperation[]>>();
-const runOnce = (key: string, work: () => Promise<void>): void => {
- if (reconciling.has(key)) {
- return;
+const listOnce = (owner: AccountScope): Promise<IntermediatesOperation[]> => {
+ const key = `${owner.accountId ?? 'local'}\u0000${owner.epoch}`;
+ let listing = listings.get(key);
+ if (!listing) {
+ listing = listIntermediatesOperations(owner.signal).finally(() => listings.delete(key));
+ listings.set(key, listing);
}
- reconciling.add(key);
- void work().finally(() => reconciling.delete(key));
-};
-
-const replayPendingStart = (queryClient: QueryClient, owner: AccountScope, pending: PendingStart): void => {
- runOnce(`${receiptKey(owner)}\u0000start\u0000${pending.idempotencyKey}`, async () => {
- try {
- const operation = await startIntermediatesOperation(pending, owner.signal);
- if (isAccountScopeCurrent(owner) && isPendingStartCurrent(pending)) {
- adoptIntermediatesOperation(queryClient, owner, operation);
- }
- } catch (error) {
- if (isPendingStartCurrent(pending, owner)) {
- clearPendingIntermediatesStart(owner);
- if (attachedManagers > 0 && isAccountScopeCurrent(owner)) {
- activeOperationStore.patchSnapshot({ recoveryError: error });
- }
- }
- }
- });
-};
-
-const catchUpWithRetry = (queryClient: QueryClient, owner: AccountScope, followed: string): void => {
- runOnce(`${receiptKey(owner)}\u0000retry\u0000${followed}`, async () => {
- try {
- const operation = await findLatestIntermediatesRetry(followed, owner.signal);
- if (
- isAccountScopeCurrent(owner) &&
- activeOperationStore.getSnapshot().operationId === followed &&
- operation.operationId !== followed
- ) {
- adoptIntermediatesOperation(queryClient, owner, operation);
- }
- } catch {
- // The operation query reports lookup failures in the panel.
- }
- });
+ return listing;
};
/**
- * Registers an open manager: attaches realtime updates for its lifetime and reconciles the receipt, replaying a
- * Confirm whose response was lost or catching up with a retry started elsewhere.
+ * Asks the server for the account's operations and follows the newest unsettled one, unless the followed operation
+ * or the account changed meanwhile: a Confirm that lands while the listing is in flight is never overwritten by an
+ * older run. Returns what it adopted, or null when the server listed nothing running; rejects when it could not ask.
*/
-export const attachIntermediatesManager = (queryClient: QueryClient): (() => void) => {
- if (attachedManagers === 0) {
- activeOperationStore.patchSnapshot({ recoveryError: null });
+export const reconcileIntermediatesOperations = async (
+ queryClient: QueryClient,
+ owner: AccountScope = captureAccountScope(),
+ options: {
+ /**
+ * Ask again rather than join a listing already in flight: a listing begun before a Confirm cannot contain the
+ * run it started, and one that hangs must not hold the confirmation open. Bounded by its own timeout. The
+ * server's `created_at` of the confirmed preview: only a run created after it can be the one that Confirm
+ * started, since the server also lists earlier finished runs.
+ */
+ startedAfter?: string;
+ } = {}
+): Promise<IntermediatesOperation | null> => {
+ const followedAtStart = activeOperationStore.getSnapshot().operationId;
+ const { startedAfter } = options;
+ const operations =
+ startedAfter !== undefined
+ ? await listIntermediatesOperations(
+ AbortSignal.any([owner.signal, AbortSignal.timeout(FRESH_LISTING_TIMEOUT_MS)])
+ )
+ : await listOnce(owner);
+ // After a lost start the run counts even when it already finished; a catch-up on open only picks up work still
+ // running, so finished runs from before are not re-shown. Both timestamps are the server's, so they compare.
+ const candidate =
+ startedAfter !== undefined
+ ? (operations.find(
+ (operation) =>
+ operation.operationId !== followedAtStart && Date.parse(operation.createdAt) >= Date.parse(startedAfter)
+ ) ?? null)
+ : (operations.find((operation) => !isOperationSettled(operation)) ?? null);
+ if (
+ candidate === null ||
+ !isAccountScopeCurrent(owner) ||
+ activeOperationStore.getSnapshot().operationId !== followedAtStart
+ ) {
+ return null;
}
- attachedManagers += 1;
+ adoptIntermediatesOperation(queryClient, owner, candidate);
+ return candidate;
+};
+
+/** Registers an open manager: realtime updates for its lifetime, and a catch-up when nothing is followed yet. */
+export const attachIntermediatesManager = (queryClient: QueryClient): (() => void) => {
const detachRealtime = attachIntermediatesRealtime(queryClient);
- const owner = captureAccountScope();
- const receipt = readReceipt(owner);
- if (typeof receipt.operationId === 'string' && receipt.operationId.length > 0) {
- activeOperationStore.patchSnapshot({ operationId: receipt.operationId });
- }
- const followed = activeOperationStore.getSnapshot().operationId;
- if (receipt.pendingStart) {
- replayPendingStart(queryClient, owner, receipt.pendingStart);
- } else if (followed) {
- catchUpWithRetry(queryClient, owner, followed);
+ if (activeOperationStore.getSnapshot().operationId === null) {
+ // A failed catch-up is not an error the section shows; the next open or a Confirm asks again.
+ void reconcileIntermediatesOperations(queryClient).catch(() => undefined);
}
-
- let attached = true;
- return () => {
- if (attached) {
- attached = false;
- attachedManagers -= 1;
- detachRealtime();
- }
- };
+ return detachRealtime;
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts b/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts
index 57f87894f6..c13922db8f 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts
@@ -12,9 +12,6 @@ import { intermediatesKeys } from './keys';
export const INTERMEDIATES_PAGE_SIZE = 50;
-/** The largest single request the API accepts; used to resolve "all matching" into explicit targets. */
-export const INTERMEDIATES_MAX_ROWS = 1000;
-
const fenced = <T>(owner: AccountScope, request: (signal: AbortSignal) => Promise<T>, signal: AbortSignal) =>
request(AbortSignal.any([signal, owner.signal])).then((result) => {
assertAccountScopeCurrent(owner);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
index d12af0c6b0..aad10dba8a 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
@@ -53,11 +53,7 @@ const operationEvent = (status: string, operationId = 'op-1') => ({
retained_images: 0,
retained_videos: 0,
unknown_size_count: 0,
- unresolved_images: 0,
- unresolved_videos: 0,
},
- retried_by_operation_id: null,
- retried_from_operation_id: null,
scope: { kind: 'owner', targets: [], user_id: 'alice' },
started_at: 'now',
status,
diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
index 6f2f289fd0..29701fa0e6 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.browser.test.ts
@@ -5,7 +5,7 @@ import { afterEach, expect, it, vi } from 'vitest';
import type { HeldMediaNames } from './holdLease';
-import { MAX_HOLD_NAMES_PER_KIND, partitionHeldMediaNames, startIntermediatesHoldLease } from './holdLease';
+import { MAX_HOLD_NAMES_PER_KIND, startIntermediatesHoldLease } from './holdLease';
vi.mock('@platform/transport/http', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
@@ -42,7 +42,7 @@ const calls = (method: string) =>
const settle = () =>
new Promise((resolve) => {
- setTimeout(resolve, 20);
+ setTimeout(resolve, 400);
});
afterEach(() => {
@@ -50,18 +50,23 @@ afterEach(() => {
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('holds up to the per-kind limit of sorted unique names under one lease', async () => {
+ const images = Array.from({ length: MAX_HOLD_NAMES_PER_KIND + 1 }, (_, index) => `image-${index}`).reverse();
+ const lease = startWith({ images: [...images, 'image-0'], videos: ['second.mp4', 'first.mp4'] });
+ try {
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));
+ const body = JSON.parse(String(calls('PUT')[0]!.init?.body)) as { images: string[]; videos: string[] };
+ expect(body.images).toHaveLength(MAX_HOLD_NAMES_PER_KIND);
+ expect(body.images).toEqual([...body.images].sort());
+ expect(body.videos).toEqual(['first.mp4', 'second.mp4']);
+ const leaseId = decodeURIComponent(calls('PUT')[0]!.url.split('/').at(-1)!);
+ expect(leaseId).toMatch(/^[A-Za-z0-9_-]+$/);
+ } finally {
+ lease.stop();
+ }
});
-it('replaces current holds and releases names removed from the open editor', async () => {
+it('replaces the lease in place and releases it once nothing is held', async () => {
const lease = startWith({ images: ['first.png'], videos: [] });
try {
await vi.waitFor(() =>
@@ -75,15 +80,37 @@ it('replaces current holds and releases names removed from the open editor', asy
JSON.stringify({ images: ['second.png'], videos: [] })
)
);
- await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(1));
+ expect(new Set(calls('PUT').map(({ url }) => url)).size).toBe(1);
+ expect(calls('DELETE')).toHaveLength(0);
lease.update({ images: [], videos: [] });
- await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(2));
+ await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(1));
+ expect(calls('DELETE')[0]!.url).toBe(calls('PUT')[0]!.url);
} finally {
lease.stop();
}
});
-it('releases its leases with keepalive when disposed', async () => {
+it('releases a lease that lands after it was disposed', async () => {
+ let resolvePut!: () => void;
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<never>((resolve) => {
+ resolvePut = () => resolve(undefined as never);
+ })
+ );
+ const lease = startWith({ images: ['late.png'], videos: [] });
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));
+
+ lease.stop();
+ expect(calls('DELETE')).toHaveLength(0);
+ resolvePut();
+
+ await vi.waitFor(() => expect(calls('DELETE')).toHaveLength(1));
+ expect(calls('DELETE')[0]!.url).toBe(calls('PUT')[0]!.url);
+ expect(calls('DELETE')[0]!.init).toMatchObject({ keepalive: true });
+});
+
+it('releases its lease 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;
@@ -148,42 +175,24 @@ it('refreshes an unchanged hold on becoming visible only after missing a heartbe
}
});
-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: [] });
+it('skips unchanged sets and sends again after a failed send', async () => {
+ const lease = startWith({ images: ['b.png', 'a.png'], 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);
- // The server caps distinct holders per account, grouping every `<holder>.<part>` id under its holder.
- const holders = new Set(calls('PUT').map(({ url }) => decodeURIComponent(url.split('/').at(-1)!).split('.')[0]));
- expect(holders.size).toBe(1);
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(1));
+ lease.update({ images: ['a.png', 'b.png'], videos: [] });
+ await settle();
+ expect(calls('PUT')).toHaveLength(1);
+
+ fetchMock.mockRejectedValueOnce(new Error('temporary network failure'));
+ lease.update({ images: ['a.png', 'b.png', 'c.png'], videos: [] });
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(2));
+ await settle();
+ // The server still holds the previous lease; the next foreground return sends the new set again.
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.waitFor(() => expect(calls('PUT')).toHaveLength(3));
+ expect(calls('PUT')[2]!.init?.body).toBe(JSON.stringify({ images: ['a.png', 'b.png', 'c.png'], videos: [] }));
+ expect(new Set(calls('PUT').map(({ url }) => url)).size).toBe(1);
+ expect(calls('DELETE')).toHaveLength(0);
} finally {
lease.stop();
}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts b/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
index fd376a77cf..982d480b09 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/holdLease.ts
@@ -8,7 +8,7 @@ export interface HeldMediaNames {
videos: readonly string[];
}
-/** Mirrors the server's per-kind `max_length` on a hold request. */
+/** Mirrors the server's per-kind `max_length` on a hold request; names past it are not held. */
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. */
@@ -17,33 +17,17 @@ const HEARTBEAT_MS = 5 * 60_000;
const RESEND_ON_VISIBLE_AFTER_MS = HEARTBEAT_MS;
const CHANGE_DEBOUNCE_MS = 250;
-type Batch = { images: string[]; videos: string[] };
-/** Each batch's request body, which also serves as its signature. */
-type Plan = string[];
-type Slot = 0 | 1;
-
const sameNames = (left: ReadonlySet<string>, right: ReadonlySet<string>): boolean =>
left.size === right.size && [...left].every((name) => right.has(name));
const holdPath = (leaseId: string): string => `/api/v1/intermediates/holds/${encodeURIComponent(leaseId)}`;
-/** Each request stays within the per-kind limit; sorted input keeps unchanged batches byte-identical. */
-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.
+ * alive, under one lease the server replaces atomically. A send the server did not acknowledge is forgotten, so the
+ * next change, heartbeat or return to the foreground sends again while the server keeps the previous lease. The
+ * lease is 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,
@@ -57,145 +41,94 @@ export const startIntermediatesHoldLease = ({
subscribe: (onChange: () => void) => () => void;
}): (() => void) => {
const leaseId = createUuid();
- const leaseSignatures: [string[], string[]] = [[], []];
- let activeSlot: Slot | null = null;
+ // The body the server last accepted, or null once a send failed or the lease was released.
+ let acknowledged: string | null = null;
+ let held = false;
let disposed = false;
let inFlight = false;
let pending = false;
let pendingRefresh = false;
let lastSentAt = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
- let planned: { held: HeldMediaNames; images: Set<string>; plan: Plan; videos: Set<string> } | null = null;
+ let planned: { held: HeldMediaNames; images: Set<string>; body: string; videos: Set<string> } | null = null;
// Releases must authenticate as the account that took the lease, even after sign-out cleared the session.
let leaseToken: string | null = null;
- const batchLeaseId = (slot: Slot, index: number): string => `${leaseId}.${slot}-${index}`;
const isStopped = (): boolean => disposed || owner.signal.aborted;
- const fireRelease = (id: string): void => {
- void apiFetch(holdPath(id), {
+ const fireRelease = (): void => {
+ void apiFetch(holdPath(leaseId), {
headers: leaseToken ? { Authorization: `Bearer ${leaseToken}` } : undefined,
keepalive: true,
method: 'DELETE',
}).catch(() => undefined);
+ held = false;
+ acknowledged = null;
};
- const releaseEverything = (): void => {
- for (const slot of [0, 1] as const) {
- leaseSignatures[slot].forEach((signature, index) => {
- if (signature) {
- fireRelease(batchLeaseId(slot, index));
- }
- });
- leaseSignatures[slot] = [];
+ /** Sorting and serialising up to 50k names per kind is the expensive part; an unchanged set reuses its body. */
+ const bodyFor = (names: HeldMediaNames): string => {
+ if (planned?.held === names) {
+ return planned.body;
}
- activeSlot = null;
+ const imageSet = new Set(names.images);
+ const videoSet = new Set(names.videos);
+ if (planned && sameNames(imageSet, planned.images) && sameNames(videoSet, planned.videos)) {
+ planned.held = names;
+ return planned.body;
+ }
+ const body =
+ imageSet.size === 0 && videoSet.size === 0
+ ? ''
+ : JSON.stringify({
+ images: [...imageSet].sort().slice(0, MAX_HOLD_NAMES_PER_KIND),
+ videos: [...videoSet].sort().slice(0, MAX_HOLD_NAMES_PER_KIND),
+ });
+ planned = { body, held: names, images: imageSet, videos: videoSet };
+ return body;
};
- 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.
- }
+ const sendOnce = async (refresh: boolean): Promise<void> => {
+ const body = bodyFor(read());
+ if (isStopped()) {
+ return;
}
- while (signatures.at(-1) === '') {
- signatures.pop();
+ if (!body) {
+ if (held) {
+ try {
+ await apiFetch(holdPath(leaseId), { method: 'DELETE', signal: owner.signal });
+ held = false;
+ acknowledged = null;
+ } catch {
+ // Still held server-side; the next send or the expiry releases it.
+ }
+ }
+ return;
}
- };
-
- const putBatch = async (slot: Slot, index: number, body: string): Promise<boolean> => {
- if (isStopped()) {
- return false;
+ if (!refresh && body === acknowledged) {
+ return;
}
const token = getHttpAuthToken();
try {
- await apiFetch(holdPath(batchLeaseId(slot, index)), {
+ await apiFetch(holdPath(leaseId), {
body,
headers: { 'Content-Type': 'application/json' },
method: 'PUT',
signal: owner.signal,
});
} catch {
- return false;
+ acknowledged = null;
+ return;
}
leaseToken = token;
if (disposed) {
// Dispose already released what it knew about; this lease landed after.
- fireRelease(batchLeaseId(slot, index));
- return false;
- }
- leaseSignatures[slot][index] = body;
- return true;
- };
-
- /** Sorting and serialising up to 50k names per kind is the expensive part; an unchanged set reuses its plan. */
- const planFor = (held: HeldMediaNames): Plan => {
- if (planned?.held === held) {
- return planned.plan;
- }
- const imageSet = new Set(held.images);
- const videoSet = new Set(held.videos);
- if (planned && sameNames(imageSet, planned.images) && sameNames(videoSet, planned.videos)) {
- planned.held = held;
- return planned.plan;
- }
- const plan = partitionHeldMediaNames([...imageSet].sort(), [...videoSet].sort()).map((batch) =>
- JSON.stringify(batch)
- );
- planned = { held, images: imageSet, plan, videos: videoSet };
- return plan;
- };
-
- const sendOnce = async (refresh: boolean): Promise<void> => {
- const bodies = planFor(read());
- if (!bodies.length) {
- await releaseSlot(0);
- await releaseSlot(1);
- activeSlot = null;
+ fireRelease();
return;
}
- const current = activeSlot === null ? null : leaseSignatures[activeSlot];
- let trimActive = false;
- if (current && current.length === bodies.length && bodies.every((value, i) => value === current[i])) {
- if (refresh) {
- let refreshed = true;
- for (let index = 0; index < bodies.length; index += 1) {
- refreshed = (await putBatch(activeSlot!, index, bodies[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 < bodies.length; index += 1) {
- staged = (await putBatch(nextSlot, index, bodies[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, bodies.length);
- }
- await releaseSlot(activeSlot === 0 ? 1 : 0);
- }
+ held = true;
+ acknowledged = body;
+ lastSentAt = Date.now();
};
const send = async (refresh = false): Promise<void> => {
@@ -233,12 +166,16 @@ export const startIntermediatesHoldLease = ({
const onVisibilityChange = (): void => {
if (
document.visibilityState === 'visible' &&
- (activeSlot === null || Date.now() - lastSentAt >= RESEND_ON_VISIBLE_AFTER_MS)
+ (acknowledged === null || Date.now() - lastSentAt >= RESEND_ON_VISIBLE_AFTER_MS)
) {
void send(true);
}
};
- const onPageHide = (): void => releaseEverything();
+ const onPageHide = (): void => {
+ if (held) {
+ fireRelease();
+ }
+ };
const onPageShow = (event: PageTransitionEvent): void => {
if (event.persisted) {
void send();
@@ -262,6 +199,8 @@ export const startIntermediatesHoldLease = ({
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('pageshow', onPageShow);
- releaseEverything();
+ if (held) {
+ fireRelease();
+ }
};
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
index 30497b6358..f5168f28f5 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
@@ -22,8 +22,6 @@ const AFFECTED_DOCUMENT_LABELS = {
export interface ClearDialogState {
mode: IntermediatesCleanupMode;
- /** Minted with each preview and reused for every Confirm of it, so a lost response replays the same operation. */
- idempotencyKey: string;
/** Null until the server preview arrives; a confirmation is only ever offered for a fresh preview. */
preview: IntermediatesPreview | null;
previewError: string | null;
@@ -191,7 +189,9 @@ export const ClearDialog = ({
);
const handleExitComplete = useCallback(() => {
setConfirmation({ acknowledged: false, previewId: '', typed: '' });
- }, []);
+ // The library's deferred focus return is not reliable once the content has unmounted; land it ourselves.
+ getFinalFocus()?.focus({ preventScroll: true });
+ }, [getFinalFocus]);
return (
<Dialog.Root
@@ -244,14 +244,6 @@ export const ClearDialog = ({
)}
</Box>
</Dialog.Description>
- {preview?.hasMoreEligible ? (
- <Alert.Root size="sm" status="info" variant="surface">
- <Alert.Indicator />
- <Alert.Content>
- <Alert.Description>{t('intermediates.dialog.batchLimit')}</Alert.Description>
- </Alert.Content>
- </Alert.Root>
- ) : null}
<Checkbox.Root
checked={isForce}
colorPalette="red"
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
index ef77403d2c..a35642ee9e 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
@@ -19,7 +19,7 @@ const dependencies = vi.hoisted(() => ({
createIntermediatesPreview: vi.fn(),
getIntermediatesOperation: vi.fn(),
getIntermediatesSummary: vi.fn(),
- retryIntermediatesOperation: vi.fn(),
+ listIntermediatesOperations: vi.fn(),
startIntermediatesOperation: vi.fn(),
}));
@@ -27,7 +27,7 @@ vi.mock('@features/intermediates/data/api', () => ({
createIntermediatesPreview: dependencies.createIntermediatesPreview,
getIntermediatesOperation: dependencies.getIntermediatesOperation,
getIntermediatesSummary: dependencies.getIntermediatesSummary,
- retryIntermediatesOperation: dependencies.retryIntermediatesOperation,
+ listIntermediatesOperations: dependencies.listIntermediatesOperations,
startIntermediatesOperation: dependencies.startIntermediatesOperation,
}));
vi.mock('@features/intermediates/data/realtime', () => ({ attachIntermediatesRealtime: () => () => undefined }));
@@ -94,8 +94,8 @@ const forceAffectedDocuments: IntermediatesPreview['affectedDocuments'] = [
const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesPreview => ({
affectedDocuments: mode === 'force' ? forceAffectedDocuments : [],
affectedDocumentsTotal: mode === 'force' ? forceAffectedDocuments.length : 0,
- createdAt: 'now',
- expiresAt: 'later',
+ createdAt: '2026-09-24T12:00:00.000Z',
+ expiresAt: '2026-09-24T12:10:00.000Z',
impact: {
deleteImages,
deleteVideos: 0,
@@ -109,7 +109,6 @@ const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesP
unknownSizeCount: 0,
},
mode,
- hasMoreEligible: false,
previewId: `preview-${mode}`,
scope: { kind: 'owner', userId: 'alice' },
targetRows: 1,
@@ -117,7 +116,7 @@ const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesP
const operationOf = (status: IntermediatesOperation['status']): IntermediatesOperation => ({
completedAt: status === 'completed' ? 'later' : null,
- createdAt: 'now',
+ createdAt: '2026-09-24T12:00:00.000Z',
error: null,
mode: 'safe',
operationId: 'op-1',
@@ -133,11 +132,7 @@ const operationOf = (status: IntermediatesOperation['status']): IntermediatesOpe
retainedImages: 0,
retainedVideos: 0,
unknownSizeCount: 0,
- unresolvedImages: 0,
- unresolvedVideos: 0,
},
- retriedByOperationId: null,
- retriedFromOperationId: null,
scope: { kind: 'owner', userId: 'alice' },
startedAt: 'now',
status,
@@ -146,6 +141,15 @@ const operationOf = (status: IntermediatesOperation['status']): IntermediatesOpe
userId: 'alice',
});
+const matchingScope = (overrides: Partial<Extract<IntermediatesOperation['scope'], { kind: 'matching' }>> = {}) => ({
+ excluded: [],
+ kind: 'matching' as const,
+ projectId: null,
+ search: null,
+ userId: 'alice',
+ ...overrides,
+});
+
let host: HTMLDivElement;
let root: Root;
let queryClient: QueryClient;
@@ -230,11 +234,7 @@ const setInputValue = (input: HTMLInputElement, value: string) => {
input.dispatchEvent(new Event('input', { bubbles: true }));
};
-const openForceDialogReadyToConfirm = async (
- options: { canClearOthersIntermediates?: boolean } = {}
-): Promise<HTMLElement> => {
- await renderManager({ focusProjectId: 'p1', ...options });
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+const openDialog = async (): Promise<HTMLElement> => {
await act(() => buttonWithText('intermediates.list.delete', host).click());
const dialog = await vi.waitFor(() => {
const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
@@ -242,6 +242,15 @@ const openForceDialogReadyToConfirm = async (
return element!;
});
await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ return dialog;
+};
+
+const openForceDialogReadyToConfirm = async (
+ options: { canClearOthersIntermediates?: boolean } = {}
+): Promise<HTMLElement> => {
+ await renderManager({ focusProjectId: 'p1', ...options });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ const dialog = await openDialog();
const toggles = () => [...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
await act(() => toggles()[0]!.click());
await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.affectedClientState'));
@@ -252,7 +261,6 @@ const openForceDialogReadyToConfirm = async (
describe('IntermediatesManager', () => {
beforeEach(() => {
- sessionStorage.clear();
dependencies.getIntermediatesSummary
.mockReset()
.mockImplementation((params: { search?: string }) =>
@@ -269,10 +277,16 @@ describe('IntermediatesManager', () => {
.mockImplementation(({ mode }: { mode: 'safe' | 'force' }) => Promise.resolve(previewOf(mode, 4)));
dependencies.startIntermediatesOperation.mockReset().mockResolvedValue(operationOf('running'));
dependencies.getIntermediatesOperation.mockReset().mockResolvedValue(operationOf('completed'));
- dependencies.retryIntermediatesOperation.mockReset();
+ dependencies.listIntermediatesOperations.mockReset().mockResolvedValue([]);
});
afterEach(async () => {
+ // A confirmation torn down while open restores focus later, into the next test; close it first.
+ const cancel = document.querySelector<HTMLButtonElement>('[role="alertdialog"] button:not([disabled])');
+ if (cancel && cancel.textContent?.includes('common.cancel')) {
+ await act(() => cancel.click());
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ }
await act(() => root?.unmount());
host?.remove();
const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
@@ -348,44 +362,33 @@ describe('IntermediatesManager', () => {
);
await renderManager({ focusProjectId: 'p1' });
await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ // The focused project is the whole filtered list, so the first click clears; the second selects all matching.
await act(() => checkbox('intermediates.list.selectAll').click());
+ expect(isDeleteUnavailable()).toBe(true);
await act(() => checkbox('intermediates.list.selectAll').click());
await act(() => buttonWithText('intermediates.list.delete', host).click());
await vi.waitFor(() =>
expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
- { mode: 'safe', scope: { kind: 'selection', targets: [{ projectId: 'p1', userId: 'alice' }] } },
+ { mode: 'safe', scope: matchingScope({ projectId: 'p1' }) },
expect.anything()
)
);
});
- it('labels a bounded preview as a repeatable batch', async () => {
- dependencies.createIntermediatesPreview.mockResolvedValue({ ...previewOf('safe', 4), hasMoreEligible: true });
- await renderManager({ focusProjectId: 'p1' });
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- await vi.waitFor(() =>
- expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('intermediates.dialog.batchLimit')
- );
- });
-
it('moves focus to the started operation, whose status the Delete control no longer reflects', async () => {
await renderManager({ focusProjectId: 'p1' });
await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- const dialog = await vi.waitFor(() => {
- const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
- expect(element).not.toBeNull();
- return element!;
- });
- await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ const dialog = await openDialog();
await act(() => buttonWithText('intermediates.dialog.confirm', dialog).click());
await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
- await vi.waitFor(() => {
- const focused = document.activeElement as HTMLElement;
- expect(focused.getAttribute('tabindex')).toBe('-1');
- expect(focused.textContent).toContain('intermediates.operation.status.running');
- });
+ await vi.waitFor(
+ () => {
+ const focused = document.activeElement as HTMLElement;
+ expect(focused.getAttribute('tabindex')).toBe('-1');
+ expect(focused.textContent).toContain('intermediates.operation.status.running');
+ },
+ { timeout: 3_000 }
+ );
});
it.each([
@@ -431,110 +434,45 @@ describe('IntermediatesManager', () => {
expect(labels[0]).toContain('intermediates.owner.unknownAccountWithId(id=0a1b2c3d)');
});
- it('replays a confirmed start receipt after a reload', async () => {
- const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
- recordPendingIntermediatesStart({ idempotencyKey: 'confirmed-key', previewId: 'confirmed-preview' });
+ it('re-follows a running operation after a reload by asking the server', async () => {
+ const { activeOperationStore } = await import('@features/intermediates/data/operationStore');
+ const running = { ...operationOf('running'), operationId: 'op-running' };
+ dependencies.listIntermediatesOperations.mockResolvedValue([
+ running,
+ { ...operationOf('completed'), operationId: 'op-0' },
+ ]);
+ dependencies.getIntermediatesOperation.mockResolvedValue(running);
await renderManager();
- await vi.waitFor(() =>
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
- { idempotencyKey: 'confirmed-key', previewId: 'confirmed-preview' },
- expect.anything()
- )
- );
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('op-1');
+ expect(activeOperationStore.getSnapshot().operationId).toBe('op-running');
+ expect(dependencies.listIntermediatesOperations).toHaveBeenCalledOnce();
+ expect(dependencies.startIntermediatesOperation).not.toHaveBeenCalled();
});
- it('does not let a late start replay replace a newer confirmed operation', async () => {
- const { activeOperationStore, recordPendingIntermediatesStart } =
- await import('@features/intermediates/data/operationStore');
- let resolveOld!: (operation: IntermediatesOperation) => void;
- const oldStart = new Promise<IntermediatesOperation>((resolve) => {
- resolveOld = resolve;
- });
- recordPendingIntermediatesStart({ idempotencyKey: 'old-key', previewId: 'old-preview' });
- dependencies.startIntermediatesOperation.mockImplementation((request: { previewId: string }) =>
- request.previewId === 'old-preview'
- ? oldStart
- : Promise.resolve({ ...operationOf('running'), operationId: 'new-op' })
+ it('does not let a late operations listing replace a newer confirmed operation', async () => {
+ const { activeOperationStore } = await import('@features/intermediates/data/operationStore');
+ let resolveListing!: (operations: IntermediatesOperation[]) => void;
+ dependencies.listIntermediatesOperations.mockImplementation(
+ () =>
+ new Promise<IntermediatesOperation[]>((resolve) => {
+ resolveListing = resolve;
+ })
);
+ dependencies.startIntermediatesOperation.mockResolvedValue({ ...operationOf('running'), operationId: 'new-op' });
await renderManager({ focusProjectId: 'p1' });
- await vi.waitFor(() =>
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
- { idempotencyKey: 'old-key', previewId: 'old-preview' },
- expect.anything()
- )
- );
+ await vi.waitFor(() => expect(dependencies.listIntermediatesOperations).toHaveBeenCalledOnce());
await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- const dialog = await vi.waitFor(() => {
- const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
- expect(element).not.toBeNull();
- return element!;
- });
- await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ const dialog = await openDialog();
await act(() => buttonWithText('intermediates.dialog.confirm', dialog).click());
await vi.waitFor(() => expect(activeOperationStore.getSnapshot().operationId).toBe('new-op'));
- await act(() => resolveOld({ ...operationOf('completed'), operationId: 'old-op' }));
- expect(activeOperationStore.getSnapshot().operationId).toBe('new-op');
- });
-
- it('does not let an old rejected replay erase a newer pending confirmation', async () => {
- const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
- let rejectOld!: (error: Error) => void;
- let resolveNew!: (operation: IntermediatesOperation) => void;
- const oldStart = new Promise<IntermediatesOperation>((_resolve, reject) => {
- rejectOld = reject;
- });
- const newStart = new Promise<IntermediatesOperation>((resolve) => {
- resolveNew = resolve;
- });
- recordPendingIntermediatesStart({ idempotencyKey: 'old-key', previewId: 'old-preview' });
- dependencies.startIntermediatesOperation.mockImplementation((request: { previewId: string }) =>
- request.previewId === 'old-preview' ? oldStart : newStart
- );
- await renderManager({ focusProjectId: 'p1' });
- await vi.waitFor(() =>
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
- { idempotencyKey: 'old-key', previewId: 'old-preview' },
- expect.anything()
- )
- );
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- const dialog = await vi.waitFor(() => {
- const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
- expect(element).not.toBeNull();
- return element!;
- });
- await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
- await act(() => buttonWithText('intermediates.dialog.confirm', dialog).click());
- await vi.waitFor(() =>
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-safe')
- );
- await act(() => rejectOld(new ApiError('Rejected', 409)));
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-safe');
- await act(() => resolveNew({ ...operationOf('running'), operationId: 'new-op' }));
- });
-
- it('replays a lost start on one remount only, even when that replay fails transiently', async () => {
- const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
- recordPendingIntermediatesStart({ idempotencyKey: 'rejected-key', previewId: 'rejected-preview' });
- dependencies.startIntermediatesOperation.mockRejectedValue(new ApiError('Unavailable', 503));
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Unavailable'));
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledOnce();
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toBeNull();
- await act(() => root.unmount());
- host.remove();
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledOnce();
+ await act(() => resolveListing([{ ...operationOf('running'), operationId: 'old-op' }]));
+ expect(activeOperationStore.getSnapshot().operationId).toBe('new-op');
});
- it('forgets a start that sign-out cut off, so signing back in never replays it', async () => {
+ it('re-enables Confirm and follows nothing when sign-out cuts a start off', async () => {
+ const { activeOperationStore } = await import('@features/intermediates/data/operationStore');
accountLifecycle.activate('alice');
try {
dependencies.startIntermediatesOperation.mockImplementation(
@@ -545,30 +483,42 @@ describe('IntermediatesManager', () => {
);
const dialog = await openForceDialogReadyToConfirm();
await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
- await vi.waitFor(() =>
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:alice')).toContain('preview-force')
- );
- expect(buttonWithText('intermediates.dialog.forceConfirm', dialog).disabled).toBe(true);
+ await vi.waitFor(() => expect(buttonWithText('intermediates.dialog.forceConfirm', dialog).disabled).toBe(true));
await act(() => {
accountLifecycle.activate('mallory');
});
- await vi.waitFor(() => expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:alice')).toBeNull());
await vi.waitFor(() => expect(buttonWithText('intermediates.dialog.forceConfirm', dialog).disabled).toBe(false));
-
- await act(() => root.unmount());
- host.remove();
- dependencies.startIntermediatesOperation.mockReset();
- accountLifecycle.activate('alice');
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- expect(dependencies.startIntermediatesOperation).not.toHaveBeenCalled();
+ expect(activeOperationStore.getSnapshot().operationId).toBeNull();
} finally {
accountLifecycle.invalidate();
}
});
- it('explains a timed-out start and lets Confirm resume the same cleanup', async () => {
+ it.each(['running', 'completed'] as const)(
+ 'follows the %s run the server lists when a start timed out',
+ async (status) => {
+ // The mount listing answers before the start; a small cleanup may even finish before the fresh listing.
+ const accepted = { ...operationOf(status), operationId: 'op-accepted' };
+ dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
+ dependencies.listIntermediatesOperations.mockImplementation(() =>
+ Promise.resolve(dependencies.startIntermediatesOperation.mock.calls.length > 0 ? [accepted] : [])
+ );
+ dependencies.getIntermediatesOperation.mockResolvedValue(accepted);
+ const dialog = await openForceDialogReadyToConfirm();
+
+ await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
+
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ await vi.waitFor(() => expect(host.textContent).toContain(`intermediates.operation.status.${status}`));
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect((document.activeElement as HTMLElement).getAttribute('tabindex')).toBe('-1'), {
+ timeout: 3_000,
+ });
+ }
+ );
+
+ it('explains a timed-out start that the server does not list and lets Confirm try again', async () => {
dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
const dialog = await openForceDialogReadyToConfirm();
await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
@@ -580,6 +530,78 @@ describe('IntermediatesManager', () => {
await vi.waitFor(() => expect(dependencies.startIntermediatesOperation).toHaveBeenCalledTimes(2));
const [first, second] = dependencies.startIntermediatesOperation.mock.calls;
expect(second![0]).toEqual(first![0]);
+ expect(first![0]).toEqual({ previewId: 'preview-force' });
+ });
+
+ it('picks up a running operation on Refresh when nothing is followed', async () => {
+ const running = { ...operationOf('running'), operationId: 'op-elsewhere' };
+ dependencies.listIntermediatesOperations.mockResolvedValueOnce([]).mockResolvedValue([running]);
+ dependencies.getIntermediatesOperation.mockResolvedValue(running);
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ expect(host.textContent).not.toContain('intermediates.operation.status.running');
+
+ await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.refresh"]')!.click());
+
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
+ expect(dependencies.listIntermediatesOperations).toHaveBeenCalledTimes(2);
+ });
+
+ it('never mistakes an earlier finished run for a timed-out start', async () => {
+ const { activeOperationStore } = await import('@features/intermediates/data/operationStore');
+ // Retained on the server from before this preview (its created_at is older than the preview's).
+ const earlier = { ...operationOf('completed'), createdAt: '2026-09-24T11:00:00.000Z', operationId: 'op-earlier' };
+ dependencies.listIntermediatesOperations.mockResolvedValue([earlier]);
+ dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
+ const dialog = await openForceDialogReadyToConfirm();
+ // The catch-up on open ignores a settled run; Dismiss-then-Confirm leaves nothing followed.
+ expect(activeOperationStore.getSnapshot().operationId).toBeNull();
+
+ await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
+
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.startTimedOut'));
+ expect(activeOperationStore.getSnapshot().operationId).toBeNull();
+ expect(host.textContent).not.toContain('intermediates.operation.status.completed');
+ });
+
+ it('asks the server afresh after a timed-out start, and says so when that fails too', async () => {
+ let resolveMountListing!: (operations: IntermediatesOperation[]) => void;
+ dependencies.listIntermediatesOperations
+ .mockImplementationOnce(
+ () =>
+ new Promise<IntermediatesOperation[]>((resolve) => {
+ resolveMountListing = resolve;
+ })
+ )
+ .mockRejectedValue(new ApiError('Gateway timeout', 504));
+ dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
+ const dialog = await openForceDialogReadyToConfirm();
+ await vi.waitFor(() => expect(dependencies.listIntermediatesOperations).toHaveBeenCalledOnce());
+
+ await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
+
+ // The listing begun at mount is still pending and could not know about this start: a second one is made.
+ await vi.waitFor(() => expect(dependencies.listIntermediatesOperations).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.startUnknown'));
+ expect(dialog.textContent).not.toContain('intermediates.dialog.startTimedOut');
+ expect(buttonWithText('common.cancel', dialog).disabled).toBe(false);
+ await act(() => resolveMountListing([]));
+ });
+
+ it('offers a fresh check when the confirmed preview is no longer known', async () => {
+ dependencies.startIntermediatesOperation.mockRejectedValueOnce(new ApiError('Preview expired or unknown', 404));
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ const dialog = await openDialog();
+
+ await act(() => buttonWithText('intermediates.dialog.confirm', dialog).click());
+
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.previewExpired'));
+ expect(buttonWithText('intermediates.dialog.confirm', dialog).disabled).toBe(true);
+ await act(() => buttonWithText('common.retry', dialog).click());
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ expect(buttonWithText('intermediates.dialog.confirm', dialog).disabled).toBe(false);
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledTimes(2);
});
it('names the owner of another account’s affected documents for an administrator', async () => {
@@ -602,62 +624,18 @@ describe('IntermediatesManager', () => {
expect(items.at(-1)).toBe('intermediates.dialog.affectedMore(count=200)');
});
- it('never replays a force delete the user cancelled after its start failed', async () => {
+ it('reports a failed start in the dialog and follows nothing', async () => {
+ const { activeOperationStore } = await import('@features/intermediates/data/operationStore');
const dialog = await openForceDialogReadyToConfirm();
expect(dialog.textContent).toContain('intermediates.dialog.affectedQuarantinedProject(count=1,name=Old sketch)');
expect(dialog.textContent).toContain('intermediates.dialog.forceWarningOwn');
dependencies.startIntermediatesOperation.mockRejectedValueOnce(new ApiError('Server error', 500));
- await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
- await vi.waitFor(() => expect(dialog.textContent).toContain('Server error'));
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toBeNull();
-
- await act(() => buttonWithText('common.cancel', dialog).click());
- await act(() => root.unmount());
- host.remove();
- dependencies.startIntermediatesOperation.mockClear();
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- expect(dependencies.startIntermediatesOperation).not.toHaveBeenCalled();
- });
- it('follows a retry whose response was lost before reload', async () => {
- const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
- followIntermediatesOperation('op-1');
- dependencies.getIntermediatesOperation.mockImplementation((operationId: string) =>
- Promise.resolve(
- operationId === 'op-1'
- ? { ...operationOf('failed'), retriedByOperationId: 'op-2' }
- : { ...operationOf('running'), operationId: 'op-2' }
- )
- );
- await renderManager();
- await vi.waitFor(() =>
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('op-2')
- );
- expect(host.textContent).toContain('intermediates.operation.status.running');
- });
+ await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
- it('does not let a late retry lookup replace a newer followed operation', async () => {
- const { activeOperationStore, followIntermediatesOperation } =
- await import('@features/intermediates/data/operationStore');
- let resolveOriginal!: (operation: IntermediatesOperation) => void;
- const original = new Promise<IntermediatesOperation>((resolve) => {
- resolveOriginal = resolve;
- });
- dependencies.getIntermediatesOperation.mockImplementation((operationId: string) =>
- operationId === 'op-1' ? original : Promise.resolve({ ...operationOf('running'), operationId })
- );
- followIntermediatesOperation('op-1');
- await renderManager();
- await vi.waitFor(() =>
- expect(dependencies.getIntermediatesOperation).toHaveBeenCalledWith('op-1', expect.anything())
- );
- await act(() => followIntermediatesOperation('newer-op'));
- await act(() => resolveOriginal({ ...operationOf('failed'), retriedByOperationId: 'op-2' }));
- await vi.waitFor(() =>
- expect(dependencies.getIntermediatesOperation).toHaveBeenCalledWith('op-2', expect.anything())
- );
- expect(activeOperationStore.getSnapshot().operationId).toBe('newer-op');
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Server error'));
+ expect(buttonWithText('intermediates.dialog.forceConfirm', dialog).disabled).toBe(false);
+ expect(activeOperationStore.getSnapshot().operationId).toBeNull();
});
it('lists projects with used and unused counts and keeps Delete disabled until something is selected', async () => {
@@ -742,7 +720,7 @@ describe('IntermediatesManager', () => {
await act(() => confirm.click());
await vi.waitFor(() =>
expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
- expect.objectContaining({ previewId: 'preview-safe' }),
+ { previewId: 'preview-safe' },
expect.anything()
)
);
@@ -751,19 +729,13 @@ describe('IntermediatesManager', () => {
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.completed'), {
timeout: 5_000,
});
- expect(host.textContent).not.toContain('intermediates.operation.retry');
+ expect(host.textContent).not.toContain('intermediates.operation.runAgain');
});
it('gates a force delete behind the disclosure, an acknowledgement and the typed word', async () => {
await renderManager({ focusProjectId: 'p1' });
await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- const dialog = await vi.waitFor(() => {
- const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
- expect(element).not.toBeNull();
- return element!;
- });
- await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ const dialog = await openDialog();
expect(dialog.textContent).toContain('intermediates.dialog.keptReferenced');
const toggles = () => [...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
@@ -802,6 +774,29 @@ describe('IntermediatesManager', () => {
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.empty.title'));
});
+ it('shows a rejected preview with the server’s reason and a retry', async () => {
+ dependencies.createIntermediatesPreview
+ .mockRejectedValueOnce(new ApiError('Too many documents would break; narrow the scope', 422))
+ .mockImplementation(({ mode }: { mode: 'safe' | 'force' }) => Promise.resolve(previewOf(mode, 4)));
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ const dialog = await vi.waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Too many documents would break; narrow the scope'));
+ expect(
+ [...dialog.querySelectorAll('button')].some(
+ (button) => button.textContent?.includes('intermediates.dialog.confirm') && !button.disabled
+ )
+ ).toBe(false);
+
+ await act(() => buttonWithText('common.retry', dialog).click());
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ });
+
it('preselects the requested project in single-user mode, where the session names no account', async () => {
await renderManager({ currentUserId: null, focusProjectId: 'p2' });
await vi.waitFor(() => expect(host.textContent).toContain('Landscapes'));
@@ -907,7 +902,8 @@ describe('IntermediatesManager', () => {
)
);
});
- it('keeps all 119 other projects selected across pages and safe/force previews', async () => {
+
+ it('keeps all 119 other projects selected across pages and sends the exclusion, not the rows', async () => {
const manyRows = Array.from({ length: 120 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
const totals = summaryOf(manyRows).totals;
dependencies.getIntermediatesSummary
@@ -934,22 +930,21 @@ describe('IntermediatesManager', () => {
await vi.waitFor(() => expect(host.textContent).toContain('Project 119'));
expect(checkbox('intermediates.list.selectRow(name=Project 119)').checked).toBe(true);
await act(() => buttonWithText('intermediates.list.delete', host).click());
- const targets = manyRows
- .filter(({ projectId }) => projectId !== 'p1')
- .map(({ projectId, userId }) => ({ projectId, userId }));
+ const scope = matchingScope({ excluded: [{ projectId: 'p1', userId: 'alice' }] });
await vi.waitFor(() =>
expect(dependencies.createIntermediatesPreview).toHaveBeenLastCalledWith(
- { mode: 'safe', scope: { kind: 'selection', targets } },
+ { mode: 'safe', scope },
expect.anything()
)
);
await act(() => document.querySelector<HTMLLabelElement>('[role="alertdialog"] label')!.click());
await vi.waitFor(() =>
expect(dependencies.createIntermediatesPreview).toHaveBeenLastCalledWith(
- { mode: 'force', scope: { kind: 'selection', targets } },
+ { mode: 'force', scope },
expect.anything()
)
);
+ expect(dependencies.getIntermediatesSummary.mock.calls.every(([params]) => (params.limit ?? 50) <= 50)).toBe(true);
});
it('shows a restored operation lookup failure and retries the lookup without starting cleanup', async () => {
@@ -966,16 +961,17 @@ describe('IntermediatesManager', () => {
await act(() => buttonWithText('common.retry', host).click());
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.completed'));
expect(dependencies.startIntermediatesOperation).not.toHaveBeenCalled();
- expect(dependencies.retryIntermediatesOperation).not.toHaveBeenCalled();
+ // Something was followed, so the server was not asked for the account's operations.
+ expect(dependencies.listIntermediatesOperations).not.toHaveBeenCalled();
});
- it('stops polling a missing operation and lets its receipt be dismissed', async () => {
+ it('stops polling an operation the server no longer knows and lets it be dismissed', async () => {
const { followIntermediatesOperation, activeOperationStore } =
await import('@features/intermediates/data/operationStore');
followIntermediatesOperation('missing');
dependencies.getIntermediatesOperation.mockRejectedValue(new ApiError('Operation not found', 404));
await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Operation not found'));
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.lookupGone'));
const calls = dependencies.getIntermediatesOperation.mock.calls.length;
await new Promise((resolve) => {
setTimeout(resolve, 2200);
@@ -983,10 +979,10 @@ describe('IntermediatesManager', () => {
expect(dependencies.getIntermediatesOperation).toHaveBeenCalledTimes(calls);
await act(() => buttonWithText('intermediates.operation.dismiss', host).click());
expect(activeOperationStore.getSnapshot().operationId).toBeNull();
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toBeNull();
expect(document.activeElement).toBe(host.querySelector('[aria-label="intermediates.searchLabel"]'));
});
- it('reconciles excluded rows after refresh across pages without forgetting their identities', async () => {
+
+ it('estimates all-matching from the totals minus the excluded rows, refreshed from the visible page', async () => {
let currentRows = Array.from({ length: 120 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
dependencies.getIntermediatesSummary
.mockReset()
@@ -1003,13 +999,10 @@ describe('IntermediatesManager', () => {
await act(() => checkbox('intermediates.list.selectAll').click());
await act(() => checkbox('intermediates.list.selectRow(name=Project 1)').click());
await vi.waitFor(() => expect(host.textContent).toContain('count=119'));
- const snapshots = () =>
- dependencies.getIntermediatesSummary.mock.calls.filter(([params]) => params.limit === 1000).length;
- const initialSnapshots = snapshots();
await act(() => buttonWithText('common.nextPage', host).click());
await vi.waitFor(() => expect(host.textContent).toContain('Project 55'));
- expect(snapshots()).toBe(initialSnapshots);
+ // The excluded row vanished off-page: the estimate never drops below what is visibly selected.
currentRows = [row('p55', 'Project 55', 1)];
await act(() => host.querySelector<HTMLButtonElement>('[aria-label="intermediates.refresh"]')!.click());
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.selection.estimate(count=1,'));
@@ -1038,38 +1031,12 @@ describe('IntermediatesManager', () => {
await act(() => buttonWithText('intermediates.list.delete', host).click());
await vi.waitFor(() =>
expect(dependencies.createIntermediatesPreview).toHaveBeenLastCalledWith(
- { mode: 'safe', scope: { kind: 'selection', targets: [{ projectId: 'p55', userId: 'alice' }] } },
+ { mode: 'safe', scope: matchingScope({ excluded: [{ projectId: 'p1', userId: 'alice' }] }) },
expect.anything()
)
);
});
- it('bounds exclusion snapshots and reports the preview limit instead of guessing a selection estimate', async () => {
- const manyRows = Array.from({ length: 1001 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
- dependencies.getIntermediatesSummary
- .mockReset()
- .mockImplementation((params: { offset?: number; limit?: number }) => {
- const offset = params.offset ?? 0;
- return Promise.resolve({
- ...summaryOf(manyRows),
- items: manyRows.slice(offset, offset + (params.limit ?? 50)),
- offset,
- });
- });
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('Project 0'));
- await act(() => checkbox('intermediates.list.selectAll').click());
- await act(() => checkbox('intermediates.list.selectRow(name=Project 1)').click());
- await vi.waitFor(() => expect(host.textContent).toContain('intermediates.selection.tooManyRows'));
- expect(dependencies.getIntermediatesSummary.mock.calls.filter(([params]) => params.limit === 1000)).toHaveLength(1);
- expect(isDeleteUnavailable()).toBe(false);
- await act(() => buttonWithText('intermediates.list.delete', host).click());
- await vi.waitFor(() =>
- expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('intermediates.dialog.tooManyRows')
- );
- expect(dependencies.createIntermediatesPreview).not.toHaveBeenCalled();
- });
-
it('debounces search into one request while keeping the input responsive', async () => {
await renderManager();
await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
@@ -1089,7 +1056,7 @@ describe('IntermediatesManager', () => {
expect(searches).toEqual(['Port']);
});
- it('resolves Select all under a search against every matching row, not only the loaded page', async () => {
+ it('sends Select all under a search as a matching scope with its exclusions and no full read', async () => {
const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Match ${index}`, 1));
dependencies.getIntermediatesSummary
.mockReset()
@@ -1114,26 +1081,16 @@ describe('IntermediatesManager', () => {
await vi.waitFor(() => expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBeNull());
await act(() => checkbox('intermediates.list.selectAll').click());
await act(() => checkbox('intermediates.list.selectRow(name=Match 3)').click());
+ await vi.waitFor(() => expect(host.textContent).toContain('count=59'));
await act(() => buttonWithText('intermediates.list.delete', host).click());
await vi.waitFor(() =>
expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
- {
- mode: 'safe',
- scope: {
- kind: 'selection',
- targets: manyRows
- .filter(({ projectId }) => projectId !== 'p3')
- .map(({ projectId, userId }) => ({ projectId, userId })),
- },
- },
+ { mode: 'safe', scope: matchingScope({ excluded: [{ projectId: 'p3', userId: 'alice' }], search: 'Match' }) },
expect.anything()
)
);
- expect(dependencies.getIntermediatesSummary).toHaveBeenCalledWith(
- expect.objectContaining({ limit: 1000, offset: 0, search: 'Match' }),
- expect.anything()
- );
+ expect(dependencies.getIntermediatesSummary.mock.calls.every(([params]) => (params.limit ?? 50) <= 50)).toBe(true);
});
it('keeps keyboard focus on the paging controls while pages load and at the last page', async () => {
@@ -1229,6 +1186,58 @@ describe('IntermediatesManager', () => {
expect(host.textContent).not.toContain('intermediates.list.deleteWaiting');
});
+ it('offers to delete again after a run that left failures, in the same mode and scope', async () => {
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation('op-1');
+ const failed: IntermediatesOperation = {
+ ...operationOf('completed'),
+ mode: 'force',
+ progress: { ...operationOf('completed').progress, failedImages: 2 },
+ scope: matchingScope({ excluded: [{ projectId: 'p2', userId: 'alice' }], search: 'Port' }),
+ };
+ await followOperation(failed);
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.completed'));
+ const runAgain = buttonWithText('intermediates.operation.runAgain', host);
+
+ await act(() => runAgain.click());
+
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
+ { mode: 'force', scope: failed.scope },
+ expect.anything()
+ )
+ );
+ const dialog = await vi.waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+ // A force run repeats as a force preview, behind the same acknowledgement and typed word.
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.affectedClientState'));
+ expect(buttonWithText('intermediates.dialog.forceConfirm', dialog).disabled).toBe(true);
+ await act(() => buttonWithText('common.cancel', dialog).click());
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ await vi.waitFor(() => expect(document.activeElement?.textContent).toBe('intermediates.operation.runAgain'), {
+ timeout: 3_000,
+ });
+ expect(host.contains(document.activeElement)).toBe(true);
+ });
+
+ it('hides Retry for an operation the server has forgotten and announces the loss', async () => {
+ const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
+ followIntermediatesOperation('gone');
+ dependencies.getIntermediatesOperation.mockRejectedValue(new ApiError('Not found', 404));
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.lookupGone'));
+ const region = host.querySelector('[role="status"][aria-live="polite"]');
+ await vi.waitFor(() => expect(region?.textContent).toBe('intermediates.operation.lookupGone'));
+ const panel = host.querySelector('[role="group"]')!;
+ expect([...panel.querySelectorAll('button')].map((button) => button.textContent)).toEqual([
+ 'intermediates.operation.dismiss',
+ ]);
+ });
+
it('announces status changes and coarse progress into one live region that mounts empty', async () => {
const { followIntermediatesOperation } = await import('@features/intermediates/data/operationStore');
followIntermediatesOperation('op-1');
@@ -1271,31 +1280,16 @@ describe('IntermediatesManager', () => {
expect(regions()[0]!.textContent).toBe('intermediates.operation.status.completed');
});
- it('replays a lost start once under StrictMode and consumes the entry point intent on commit', async () => {
- const { recordPendingIntermediatesStart } = await import('@features/intermediates/data/operationStore');
+ it('asks the server once under StrictMode, follows the running operation and consumes the entry point intent on commit', async () => {
const { peekIntermediatesFocus } = await import('@features/intermediates/data/focus');
- recordPendingIntermediatesStart({ idempotencyKey: 'strict-key', previewId: 'strict-preview' });
+ const running = { ...operationOf('running'), operationId: 'op-running' };
+ dependencies.listIntermediatesOperations.mockResolvedValue([running]);
+ dependencies.getIntermediatesOperation.mockResolvedValue(running);
await renderManager({ focusProjectId: 'p2', strict: true });
await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
- expect(dependencies.startIntermediatesOperation).toHaveBeenCalledOnce();
+ expect(dependencies.listIntermediatesOperations).toHaveBeenCalledOnce();
expect(checkbox('intermediates.list.selectRow(name=Landscapes)').checked).toBe(true);
expect(peekIntermediatesFocus()).toBeNull();
});
-
- it('keeps a timed-out start receipt after the dialog closes, so the next visit follows it', async () => {
- dependencies.startIntermediatesOperation.mockRejectedValueOnce(new DOMException('timed out', 'TimeoutError'));
- const dialog = await openForceDialogReadyToConfirm();
- await act(() => buttonWithText('intermediates.dialog.forceConfirm', dialog).click());
- await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.startTimedOut'));
- await act(() => buttonWithText('common.cancel', dialog).click());
- expect(sessionStorage.getItem('invokeai:webv2:intermediates-receipt:local')).toContain('preview-force');
-
- await act(() => root.unmount());
- host.remove();
- await renderManager();
- await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.running'));
- const [first, replay] = dependencies.startIntermediatesOperation.mock.calls;
- expect(replay![0]).toEqual(first![0]);
- });
});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
index 7e50e46908..9756d80bd6 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
@@ -21,14 +21,11 @@ import { isRowSelected, resolveScope } from '@features/intermediates/core/select
import { isOperationSettled } from '@features/intermediates/core/types';
import { consumeIntermediatesFocus, peekIntermediatesFocus } from '@features/intermediates/data/focus';
import { intermediatesKeys } from '@features/intermediates/data/keys';
-import {
- INTERMEDIATES_MAX_ROWS,
- INTERMEDIATES_PAGE_SIZE,
- intermediatesSummaryQueryOptions,
-} from '@features/intermediates/data/queries';
+import { activeOperationStore, reconcileIntermediatesOperations } from '@features/intermediates/data/operationStore';
+import { INTERMEDIATES_PAGE_SIZE, intermediatesSummaryQueryOptions } from '@features/intermediates/data/queries';
import { formatBytes } from '@platform/i18n/languages';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { getApiErrorMessage } from '@platform/transport/http';
+import { ApiError, getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
import { EmptyState } from '@platform/ui/EmptyState';
import { RemovableTag } from '@platform/ui/RemovableTag';
@@ -102,11 +99,20 @@ export const IntermediatesManager = ({
const searchRef = useRef<HTMLInputElement | null>(null);
const operationRegionRef = useRef<HTMLDivElement | null>(null);
const operation = useFollowedOperation({ fallbackFocusRef: searchRef });
+ // Operations live in server memory; after a restart the server no longer knows this one, and asking again cannot help.
+ const isLookupGone =
+ operation.query.isError && operation.query.error instanceof ApiError && operation.query.error.status === 404;
+ const lookupError = !operation.query.isError
+ ? null
+ : isLookupGone
+ ? t('intermediates.operation.lookupGone')
+ : getApiErrorMessage(operation.query.error, t('intermediates.operation.lookupFailed'));
// The live region stays mounted and starts empty; screen readers skip text that arrives with its region.
const announcement = getOperationAnnouncement(
operation.operationId ? (operation.query.data ?? null) : null,
operation.operationId !== null && operation.query.isPending,
- t
+ t,
+ operation.operationId ? lookupError : null
);
const [announced, setAnnounced] = useState({ source: announcement, text: '' });
if (announced.source !== announcement) {
@@ -137,7 +143,6 @@ export const IntermediatesManager = ({
const rows = query.data?.items ?? EMPTY_ROWS;
const totals = query.data?.totals;
const hasSearch = querySearch.trim().length > 0;
- const hasSubsetFilter = hasSearch || projectFilter !== null;
// Rows disappearing (a cleanup, a narrower search) can leave the offset past the end; step back to a valid page.
if (query.data && !query.isPlaceholderData && offset > 0 && offset >= query.data.total) {
setOffset(
@@ -146,7 +151,6 @@ export const IntermediatesManager = ({
}
const selection = useIntermediatesSelection({
initialProjectId: focus?.projectId ?? null,
- params,
rows,
summary: query.data,
});
@@ -195,7 +199,12 @@ export const IntermediatesManager = ({
const handleRefresh = useCallback(() => {
const request = ++refreshRequestRef.current;
setIsRefreshing(true);
- void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all }).finally(() => {
+ // A refresh also asks whether a run this tab does not know about is in progress (a start whose answer was lost).
+ const catchUp =
+ activeOperationStore.getSnapshot().operationId === null
+ ? reconcileIntermediatesOperations(queryClient).catch(() => undefined)
+ : Promise.resolve();
+ void Promise.all([queryClient.invalidateQueries({ queryKey: intermediatesKeys.all }), catchUp]).finally(() => {
if (refreshRequestRef.current === request) {
setIsRefreshing(false);
}
@@ -250,11 +259,6 @@ export const IntermediatesManager = ({
</IconButton>
</Tooltip>
</HStack>
- {operation.recoveryError ? (
- <Text color="fg.error" fontSize="xs" role="alert">
- {operation.recoveryError}
- </Text>
- ) : null}
<HStack flexWrap="wrap" gap="2">
<InputGroup flex="1 1 16rem" minW="0" startElement={SEARCH_ICON}>
<Input
@@ -301,18 +305,17 @@ export const IntermediatesManager = ({
>
<OperationPanel
isLoading={operation.query.isPending}
+ isLookupRetryable={!isLookupGone}
isRefetching={operation.query.isFetching}
- lookupError={
- operation.query.isError
- ? getApiErrorMessage(operation.query.error, t('intermediates.operation.lookupFailed'))
- : null
- }
+ lookupError={lookupError}
onRefetch={() => void operation.query.refetch()}
- isRetrying={operation.isRetrying}
operation={operation.query.data ?? null}
- retryError={operation.retryError}
onDismiss={operation.dismiss}
- onRetry={() => void operation.retry()}
+ onRunAgain={(trigger) => {
+ if (followed) {
+ dialog.open(followed.scope, trigger, followed.mode);
+ }
+ }}
/>
</Box>
) : null}
@@ -339,22 +342,20 @@ export const IntermediatesManager = ({
<Text color="fg.muted" flex="1" fontSize="2xs" id={deleteReasonId} minW="0" textAlign="end" truncate>
{isOperationActive && selection.hasSelection
? t('intermediates.list.deleteWaiting')
- : selection.estimateState && selectionSummary === null
- ? t(`intermediates.selection.${selection.estimateState}`, { count: INTERMEDIATES_MAX_ROWS })
- : selection.hasSelection && selectionSummary
- ? t('intermediates.selection.estimate', {
- count: selectionSummary.rows,
- images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),
- size: formatSummarySize(selectionSummary.reclaimableBytes, selectionSummary.unknownSizeCount, t),
- videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),
+ : selection.hasSelection
+ ? t('intermediates.selection.estimate', {
+ count: selectionSummary.rows,
+ images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),
+ size: formatSummarySize(selectionSummary.reclaimableBytes, selectionSummary.unknownSizeCount, t),
+ videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),
+ })
+ : totals
+ ? t('intermediates.selection.available', {
+ images: t('intermediates.counts.images', { count: totals.safeImages }),
+ size: formatSummarySize(totals.reclaimableBytes, totals.unknownSizeCount, t),
+ videos: t('intermediates.counts.videos', { count: totals.safeVideos }),
})
- : totals
- ? t('intermediates.selection.available', {
- images: t('intermediates.counts.images', { count: totals.safeImages }),
- size: formatSummarySize(totals.reclaimableBytes, totals.unknownSizeCount, t),
- videos: t('intermediates.counts.videos', { count: totals.safeVideos }),
- })
- : ''}
+ : ''}
</Text>
{query.data?.measuring ? (
<Tooltip content={t('intermediates.stats.measuringNote')}>
@@ -373,10 +374,13 @@ export const IntermediatesManager = ({
if (isDeleteUnavailable) {
return;
}
- operation.clearRetryError();
dialog.open(
- resolveScope({ hasSubsetFilter, ownerId, selection: selection.effectiveSelection }),
- params,
+ resolveScope({
+ ownerId,
+ projectId: projectFilter,
+ search: querySearch,
+ selection: selection.effectiveSelection,
+ }),
event.currentTarget
);
}}
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
index d5476f34fe..b1794ca220 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
@@ -1,11 +1,12 @@
import type { IntermediatesOperation } from '@features/intermediates/core/types';
import type { TFunction } from 'i18next';
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
import { Alert, HStack, Progress, Stack, Text } from '@chakra-ui/react';
import {
+ canRunOperationAgain,
getOperationProcessed,
getOperationTotalTargets,
- isOperationRetryable,
isOperationSettled,
} from '@features/intermediates/core/types';
import { formatBytes, formatCount } from '@platform/i18n/languages';
@@ -17,10 +18,11 @@ export interface OperationPanelProps {
isLoading: boolean;
isRefetching: boolean;
lookupError: string | null;
+ /** False once the server has said it no longer knows the operation: asking again cannot help. */
+ isLookupRetryable: boolean;
onRefetch: () => void;
- retryError: string | null;
- isRetrying: boolean;
- onRetry: () => void;
+ /** Requests the operation's scope again; the button that asked is the trigger focus returns to. */
+ onRunAgain: (trigger: HTMLElement) => void;
onDismiss: () => void;
}
@@ -44,8 +46,12 @@ const ANNOUNCED_PROGRESS_STEP = 25;
export const getOperationAnnouncement = (
operation: IntermediatesOperation | null,
isLoading: boolean,
- t: TFunction
+ t: TFunction,
+ lookupError: string | null = null
): string => {
+ if (lookupError) {
+ return lookupError;
+ }
if (!operation) {
return isLoading ? t('intermediates.operation.pending') : '';
}
@@ -63,17 +69,16 @@ export const getOperationAnnouncement = (
});
};
-/** The active or most recent cleanup: progress while it runs, a breakdown once it stops, retry for what failed. */
+/** The active or most recent cleanup: progress while it runs, a breakdown once it stops, another run for what failed. */
export const OperationPanel = ({
isLoading,
+ isLookupRetryable,
isRefetching,
lookupError,
onRefetch,
- isRetrying,
onDismiss,
- onRetry,
+ onRunAgain,
operation,
- retryError,
}: OperationPanelProps) => {
const { t } = useTranslation();
@@ -85,9 +90,11 @@ export const OperationPanel = ({
<Alert.Title>{t('intermediates.operation.lookupFailed')}</Alert.Title>
<Alert.Description>{lookupError}</Alert.Description>
<HStack gap="2" mt="2">
- <Button loading={isRefetching} size="2xs" variant="outline" onClick={onRefetch}>
- {t('common.retry')}
- </Button>
+ {isLookupRetryable ? (
+ <Button loading={isRefetching} size="2xs" variant="outline" onClick={onRefetch}>
+ {t('common.retry')}
+ </Button>
+ ) : null}
<Button size="2xs" variant="ghost" onClick={onDismiss}>
{t('intermediates.operation.dismiss')}
</Button>
@@ -169,16 +176,11 @@ export const OperationPanel = ({
{t('intermediates.operation.pendingDiskNote')}
</Text>
) : null}
- {retryError ? (
- <Text color="fg.error" fontSize="xs" role="alert">
- {retryError}
- </Text>
- ) : null}
{settled ? (
<HStack gap="2">
- {isOperationRetryable(operation) ? (
- <Button loading={isRetrying} size="2xs" variant="outline" onClick={onRetry}>
- {t('intermediates.operation.retry')}
+ {canRunOperationAgain(operation) ? (
+ <Button size="2xs" variant="outline" onClick={(event) => onRunAgain(event.currentTarget)}>
+ {t('intermediates.operation.runAgain')}
</Button>
) : null}
<Button size="2xs" variant="ghost" onClick={onDismiss}>
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
index 81a3db61e5..820593028c 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
@@ -1,25 +1,18 @@
-import type { IntermediatesScopeRequest } from '@features/intermediates/core/selection';
-import type { IntermediatesCleanupMode, IntermediatesScope } from '@features/intermediates/core/types';
-import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
+import type {
+ IntermediatesCleanupMode,
+ IntermediatesOperation,
+ IntermediatesScope,
+} from '@features/intermediates/core/types';
-import { resolveMatchingTargets } from '@features/intermediates/core/selection';
-import {
- createIntermediatesPreview,
- getIntermediatesSummary,
- startIntermediatesOperation,
-} from '@features/intermediates/data/api';
+import { createIntermediatesPreview, startIntermediatesOperation } from '@features/intermediates/data/api';
import {
adoptIntermediatesOperation,
- clearPendingIntermediatesStart,
- recordPendingIntermediatesStart,
+ reconcileIntermediatesOperations,
} from '@features/intermediates/data/operationStore';
-import { INTERMEDIATES_MAX_ROWS } from '@features/intermediates/data/queries';
-import { createUuid } from '@platform/browser/randomUuid';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
- type AccountScope,
} from '@platform/state/accountLifecycle';
import { ApiError, getApiErrorMessage } from '@platform/transport/http';
import { useQueryClient } from '@tanstack/react-query';
@@ -28,13 +21,7 @@ import { useTranslation } from 'react-i18next';
import type { ClearDialogState } from './ClearDialog';
-interface DialogRequest {
- scope: IntermediatesScopeRequest;
- /** The filters the request was made under; a `matching` scope resolves against them. */
- params: IntermediatesSummaryParams;
-}
-
-/** The confirmation flow: preview a scope, optionally switch to force, and start the operation it froze. */
+/** The confirmation flow: preview a scope, optionally switch to force, and start the operation it described. */
export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
@@ -42,46 +29,18 @@ export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
const triggerRef = useRef<HTMLElement | null>(null);
const startedRef = useRef(false);
const requestRef = useRef(0);
- const dialogRequestRef = useRef<DialogRequest | null>(null);
-
- const resolveScope = useCallback(
- async ({ params, scope }: DialogRequest, owner: AccountScope): Promise<IntermediatesScope> => {
- if (scope.kind !== 'matching') {
- return scope;
- }
- const matching = await getIntermediatesSummary(
- { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
- owner.signal
- );
- assertAccountScopeCurrent(owner);
- if (matching.total > matching.items.length) {
- throw new Error(t('intermediates.dialog.tooManyRows', { count: matching.items.length }));
- }
- return { kind: 'selection', targets: resolveMatchingTargets(scope.excluded, matching.items) };
- },
- [t]
- );
+ const scopeRef = useRef<IntermediatesScope | null>(null);
const loadPreview = useCallback(
- async (mode: IntermediatesCleanupMode, request: DialogRequest) => {
+ async (mode: IntermediatesCleanupMode, scope: IntermediatesScope) => {
const requestId = ++requestRef.current;
const owner = captureAccountScope();
- setDialog((current) => ({
- idempotencyKey: current?.idempotencyKey ?? createUuid(),
- isStarting: false,
- mode,
- preview: null,
- previewError: null,
- startError: null,
- }));
+ setDialog({ isStarting: false, mode, preview: null, previewError: null, startError: null });
try {
- const scope = await resolveScope(request, owner);
const preview = await createIntermediatesPreview({ mode, scope }, owner.signal);
assertAccountScopeCurrent(owner);
if (requestRef.current === requestId) {
- // One key per preview: every Confirm of this preview replays the same operation, and a later preview
- // (mode switch, retry) starts clean instead of colliding with a key the server already settled.
- setDialog((current) => (current ? { ...current, idempotencyKey: createUuid(), preview } : current));
+ setDialog((current) => (current ? { ...current, preview } : current));
}
} catch (error) {
if (requestRef.current === requestId && isAccountScopeCurrent(owner)) {
@@ -93,33 +52,32 @@ export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
}
}
},
- [resolveScope, t]
+ [t]
);
const open = useCallback(
- (scope: IntermediatesScopeRequest, params: IntermediatesSummaryParams, trigger: HTMLElement | null) => {
+ (scope: IntermediatesScope, trigger: HTMLElement | null, mode: IntermediatesCleanupMode = 'safe') => {
triggerRef.current = trigger;
startedRef.current = false;
- dialogRequestRef.current = { params, scope };
+ scopeRef.current = scope;
setDialog(null);
- void loadPreview('safe', dialogRequestRef.current);
+ void loadPreview(mode, scope);
},
[loadPreview]
);
- // A timed-out start keeps its receipt: the server may have accepted it, and the next visit replays the same key.
const close = useCallback(() => {
requestRef.current += 1;
setDialog(null);
}, []);
const retryPreview = useCallback(() => {
- if (dialog && dialogRequestRef.current) {
- void loadPreview(dialog.mode, dialogRequestRef.current);
+ if (dialog && scopeRef.current) {
+ void loadPreview(dialog.mode, scopeRef.current);
}
}, [dialog, loadPreview]);
const changeMode = useCallback(
(mode: IntermediatesCleanupMode) => {
- if (dialogRequestRef.current) {
- void loadPreview(mode, dialogRequestRef.current);
+ if (scopeRef.current) {
+ void loadPreview(mode, scopeRef.current);
}
},
[loadPreview]
@@ -130,28 +88,59 @@ export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
return;
}
const owner = captureAccountScope();
- const start = { idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId };
- recordPendingIntermediatesStart(start);
+ const requestId = requestRef.current;
+ const started = () => {
+ startedRef.current = true;
+ onStarted();
+ setDialog(null);
+ };
setDialog((current) => (current ? { ...current, isStarting: true, startError: null } : current));
try {
- const operation = await startIntermediatesOperation(start, owner.signal);
+ const operation = await startIntermediatesOperation({ previewId: preview.previewId }, owner.signal);
assertAccountScopeCurrent(owner);
adoptIntermediatesOperation(queryClient, owner, operation);
- startedRef.current = true;
- onStarted();
- setDialog(null);
+ started();
} catch (error) {
- const timedOut = error instanceof DOMException && error.name === 'TimeoutError';
- // Any other outcome settles this start; nothing may replay it, including after signing back in.
- if (!timedOut) {
- clearPendingIntermediatesStart(owner);
- }
if (!isAccountScopeCurrent(owner) || (error instanceof DOMException && error.name === 'AbortError')) {
setDialog((current) => (current ? { ...current, isStarting: false } : current));
return;
}
- // A 404 means the preview expired or was consumed by a request whose response was lost; only a new
- // preview can move forward, so offer that instead of a dead Confirm.
+ if (error instanceof DOMException && error.name === 'TimeoutError') {
+ // The server may have accepted the start; if it is running, follow it as if the answer had arrived. A
+ // listing that fails too leaves that unknown, which is not the same as "nothing is running".
+ let adopted: IntermediatesOperation | null = null;
+ let listed = true;
+ try {
+ adopted = await reconcileIntermediatesOperations(queryClient, owner, { startedAfter: preview.createdAt });
+ } catch {
+ listed = false;
+ }
+ if (!isAccountScopeCurrent(owner) || requestRef.current !== requestId) {
+ return;
+ }
+ if (adopted) {
+ started();
+ return;
+ }
+ setDialog((current) =>
+ current
+ ? {
+ ...current,
+ isStarting: false,
+ startError: listed
+ ? t('intermediates.dialog.startTimedOut', {
+ action: t(
+ current.mode === 'force' ? 'intermediates.dialog.forceConfirm' : 'intermediates.dialog.confirm'
+ ),
+ })
+ : t('intermediates.dialog.startUnknown'),
+ }
+ : current
+ );
+ return;
+ }
+ // A 404 means the preview expired or was already confirmed; only a new preview can move forward, so offer
+ // that instead of a dead Confirm.
const previewGone = error instanceof ApiError && error.status === 404;
setDialog((current) =>
current
@@ -160,15 +149,7 @@ export const useCleanupDialog = ({ onStarted }: { onStarted: () => void }) => {
isStarting: false,
preview: previewGone ? null : current.preview,
previewError: previewGone ? t('intermediates.dialog.previewExpired') : current.previewError,
- startError: previewGone
- ? null
- : timedOut
- ? t('intermediates.dialog.startTimedOut', {
- action: t(
- current.mode === 'force' ? 'intermediates.dialog.forceConfirm' : 'intermediates.dialog.confirm'
- ),
- })
- : getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
+ startError: previewGone ? null : getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
}
: current
);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
index bb6a001575..9d333d5d19 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
@@ -1,87 +1,28 @@
import type { RefObject } from 'react';
-import { retryIntermediatesOperation } from '@features/intermediates/data/api';
import {
activeOperationStore,
- adoptIntermediatesOperation,
attachIntermediatesManager,
- findLatestIntermediatesRetry,
followIntermediatesOperation,
} from '@features/intermediates/data/operationStore';
import { intermediatesOperationQueryOptions } from '@features/intermediates/data/queries';
import { useMountEffect } from '@platform/react/useMountEffect';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
-import { getApiErrorMessage } from '@platform/transport/http';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { useCallback } from 'react';
/** The operation the section follows, kept across visits by the operation store, which this hook subscribes to. */
export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: RefObject<HTMLElement | null> }) => {
- const { t } = useTranslation();
const queryClient = useQueryClient();
const operationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
- const recoveryError = activeOperationStore.useSelector((snapshot) => snapshot.recoveryError);
- const [retryError, setRetryError] = useState<string | null>(null);
- const [isRetrying, setIsRetrying] = useState(false);
const query = useQuery({ ...intermediatesOperationQueryOptions(operationId ?? ''), enabled: operationId !== null });
useMountEffect(() => attachIntermediatesManager(queryClient));
- const retry = useCallback(async () => {
- if (!operationId) {
- return;
- }
- const owner = captureAccountScope();
- setIsRetrying(true);
- setRetryError(null);
- try {
- const operation = await retryIntermediatesOperation(operationId, owner.signal);
- assertAccountScopeCurrent(owner);
- adoptIntermediatesOperation(queryClient, owner, operation);
- } catch (error) {
- if (isAccountScopeCurrent(owner)) {
- try {
- const latest = await findLatestIntermediatesRetry(operationId, owner.signal);
- if (
- latest.operationId !== operationId &&
- isAccountScopeCurrent(owner) &&
- activeOperationStore.getSnapshot().operationId === operationId
- ) {
- adoptIntermediatesOperation(queryClient, owner, latest);
- return;
- }
- } catch {
- // Preserve the original retry error when reconciliation is unavailable.
- }
- setRetryError(getApiErrorMessage(error, t('intermediates.operation.retryFailed')));
- }
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsRetrying(false);
- }
- }
- }, [operationId, queryClient, t]);
const dismiss = useCallback(() => {
followIntermediatesOperation(null);
- setRetryError(null);
// The Dismiss button unmounts with the panel; keep keyboard focus in the section.
fallbackFocusRef.current?.focus();
}, [fallbackFocusRef]);
- const clearRetryError = useCallback(() => setRetryError(null), []);
- return {
- clearRetryError,
- dismiss,
- isRetrying,
- operationId,
- query,
- recoveryError: recoveryError ? getApiErrorMessage(recoveryError, t('intermediates.dialog.startFailed')) : null,
- retry,
- retryError,
- };
+ return { dismiss, operationId, query };
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
index cb11149c6d..82064e46b2 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
@@ -1,5 +1,4 @@
import type { IntermediatesRow, IntermediatesSummary } from '@features/intermediates/core/types';
-import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
import {
EMPTY_SELECTION,
@@ -9,55 +8,35 @@ import {
withRowSelected,
type IntermediatesSelection,
} from '@features/intermediates/core/selection';
-import { INTERMEDIATES_MAX_ROWS, intermediatesSummaryQueryOptions } from '@features/intermediates/data/queries';
-import { useQuery } from '@tanstack/react-query';
import { useCallback, useMemo, useState } from 'react';
const EMPTY_TOTALS = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos: 0, unknownSizeCount: 0 };
/**
- * Row selection across pages. An entry point's project stays selected until the user changes the selection; with
- * exclusions, "all matching" is summarized from one bounded read of every matching row.
+ * Row selection across pages. An entry point's project stays selected until the user changes the selection; "all
+ * matching" is estimated from the server's totals minus the excluded rows, and resolved by the server on preview.
*/
export const useIntermediatesSelection = ({
initialProjectId,
- params,
rows,
summary,
}: {
initialProjectId: string | null;
- params: IntermediatesSummaryParams;
rows: readonly IntermediatesRow[];
summary: IntermediatesSummary | undefined;
}) => {
const [selection, setSelection] = useState<IntermediatesSelection>(EMPTY_SELECTION);
// The manager filters to the focused project, so pagination cannot hide the entry point's selection.
const [pendingProjectId, setPendingProjectId] = useState<string | null>(initialProjectId);
- const totals = summary?.totals;
+ const totals = summary?.totals ?? EMPTY_TOTALS;
const focusedRow = pendingProjectId ? rows.find((row) => row.projectId === pendingProjectId) : undefined;
const effectiveSelection = focusedRow ? withRowSelected(selection, focusedRow) : selection;
- const hasExclusions = effectiveSelection.mode === 'all-matching' && effectiveSelection.excluded.size > 0;
- // One bounded read, shared across UI pages and refreshed by the same summary invalidations.
- const matchingSnapshotQuery = useQuery({
- ...intermediatesSummaryQueryOptions({ ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 }),
- enabled: hasExclusions && summary !== undefined,
- });
- const matchingSnapshot = matchingSnapshotQuery.data;
- const isOverLimit =
- hasExclusions && matchingSnapshot !== undefined && matchingSnapshot.total > matchingSnapshot.items.length;
const selectionSummary = useMemo(
- () =>
- summarizeSelection(
- effectiveSelection,
- totals ?? EMPTY_TOTALS,
- matchingSnapshot && !matchingSnapshotQuery.isError && !isOverLimit ? matchingSnapshot.items : undefined,
- rows
- ),
- [effectiveSelection, isOverLimit, matchingSnapshot, matchingSnapshotQuery.isError, rows, totals]
+ () => summarizeSelection(effectiveSelection, totals, rows),
+ [effectiveSelection, rows, totals]
);
- const matchingRowCount = hasExclusions ? matchingSnapshot?.total : totals?.rows;
- const hasSelection = selectionSummary ? selectionSummary.rows > 0 : hasExclusions && (totals?.rows ?? 0) > 0;
- const isComplete = selectionSummary !== null && selectionSummary.rows === matchingRowCount;
+ const hasSelection = selectionSummary.rows > 0;
+ const isComplete = hasSelection && selectionSummary.rows === totals.rows;
const reset = useCallback(() => {
setPendingProjectId(null);
@@ -78,14 +57,6 @@ export const useIntermediatesSelection = ({
return {
effectiveSelection,
- /** Why an "all matching" estimate is unavailable, when it is. */
- estimateState: !hasExclusions
- ? null
- : isOverLimit
- ? ('tooManyRows' as const)
- : matchingSnapshotQuery.isError
- ? ('estimateFailed' as const)
- : ('checking' as const),
hasSelection,
reset,
selectionState: hasSelection ? (isComplete ? ('all' as const) : ('some' as const)) : ('none' as const),