Skip to content

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

fix(intermediates): stop cancelled starts from replaying and keep stale rows inert

Josh Corbette9e09f8cfcd7
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 766acaecba..9fe1683a46 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4231,21 +4231,29 @@
"kept_one": "{{count}} in-use item will be kept.",
"kept_other": "{{count}} in-use items will be kept.",
"nothing": "Nothing is safe to clear right now.",
- "forceWarning": "Force clearing also deletes intermediates that saved projects or workflows still reference. Those documents will show missing images and undo may no longer restore them. Queued, running and recently created work stays protected. Deletion cannot be undone.",
+ "forceWarning": "Force clearing also deletes intermediates that saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Queued, running and recently created work stays protected. Deletion cannot be undone.",
+ "forceWarningOwn": "Force clearing also deletes intermediates that your saved documents still reference: projects, workflows, legacy editor state and recovered projects. Those documents will show missing images and undo may no longer restore them. Items another account's documents use are always kept, as are queued, running and recently created work. Deletion cannot be undone.",
"affected": "Documents that will lose references",
"affectedProject_one": "Project “{{name}}” ({{count}} item)",
"affectedProject_other": "Project “{{name}}” ({{count}} items)",
"affectedWorkflow_one": "Workflow “{{name}}” ({{count}} item)",
"affectedWorkflow_other": "Workflow “{{name}}” ({{count}} items)",
- "affectedHidden_one": "{{count}} document in another account",
- "affectedHidden_other": "{{count}} documents in other accounts",
- "acknowledge": "I understand this may break saved projects and workflows and cannot be undone.",
+ "affectedOwner": "· {{owner}}",
+ "affectedClientState_one": "Legacy editor state ({{count}} item)",
+ "affectedClientState_other": "Legacy editor state ({{count}} items)",
+ "affectedQuarantinedProject_one": "Recovered project “{{name}}” ({{count}} item)",
+ "affectedQuarantinedProject_other": "Recovered project “{{name}}” ({{count}} items)",
+ "acknowledge": "I understand this may break saved documents and cannot be undone.",
"typeToConfirm": "Type {{word}} to confirm",
"confirm": "Delete",
"forceConfirm": "Force delete",
"startFailed": "Could not start the cleanup.",
- "keptReasons": "{{referenced}} referenced by saved projects or workflows, {{active}} used by queued or running work, {{recent}} created recently.",
- "forceToggle": "Also delete items that saved projects or workflows still reference (advanced)",
+ "startTimedOut": "The server did not answer in time. Pressing Confirm again is safe: it resumes this same cleanup rather than starting a second one.",
+ "keptReasons": "{{reasons}}.",
+ "keptReferenced": "{{items}} referenced by saved documents",
+ "keptActive": "{{items}} used by queued or running work",
+ "keptRecent": "{{items}} created recently",
+ "forceToggle": "Also delete items that saved documents still reference (advanced)",
"previewExpired": "This check is no longer current. Check again before deleting.",
"tooManyRows": "More than {{count}} projects match. Narrow the search or clear the selection and choose projects."
},
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 213f81ac19..9b09b77338 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -1172,12 +1172,13 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
.map((row) => ({
kind: 'project',
user_id: row.user_id,
+ user_display_name: row.user_display_name,
+ user_email: row.user_email,
owner_id: row.project_id ?? 'unassigned',
name: row.project_name,
references: row.images.referenced + row.videos.referenced,
}))
: [],
- affected_documents_hidden: 0,
};
state.intermediatesPreviews.set(previewId, { preview, targets });
return json(201, preview);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
index f83460f85e..fa02601f20 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
@@ -2,7 +2,7 @@
* Read models of the intermediates manager. Pure: no transport, React or UI imports.
*
* An intermediate is classified once by the server under the cleanup policy: `safe` (deleted by either mode),
- * `referenced` (named by a saved project or workflow; deleted only by a force clear), `active` (produced or
+ * `referenced` (named by a saved document or persisted editor state; deleted only by a force clear), `active` (produced or
* consumed by queued or running work) and `recent` (inside the grace window). The last two are never deleted.
*/
@@ -83,9 +83,18 @@ export interface IntermediatesImpact {
unknownSizeCount: number;
}
+/**
+ * What names the media: a saved project or library workflow, the legacy editor's persisted state (`ownerId` is its
+ * state key), or a project set aside for repair by an earlier migration.
+ */
+export type IntermediatesAffectedDocumentKind = 'project' | 'workflow' | 'client_state' | 'quarantined_project';
+
export interface IntermediatesAffectedDocument {
- kind: 'project' | 'workflow';
+ kind: IntermediatesAffectedDocumentKind;
+ /** The document's owner. */
userId: string;
+ userDisplayName: string | null;
+ userEmail: string | null;
ownerId: string;
name: string | null;
references: number;
@@ -101,7 +110,6 @@ export interface IntermediatesPreview {
hasMoreEligible: boolean;
impact: IntermediatesImpact;
affectedDocuments: IntermediatesAffectedDocument[];
- affectedDocumentsHidden: number;
}
export interface IntermediatesOperationProgress {
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
index fa17bc4469..121a9808fb 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
@@ -79,7 +79,6 @@ describe('intermediates transport', () => {
const fetchMock = fetchJson(
{
affected_documents: [],
- affected_documents_hidden: 0,
created_at: 'now',
expires_at: 'later',
has_more_eligible: true,
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
index 367a05fc5d..fd39fec410 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
@@ -1,5 +1,6 @@
import type {
IntermediatesAffectedDocument,
+ IntermediatesAffectedDocumentKind,
IntermediatesCleanupMode,
IntermediatesImpact,
IntermediatesKindCounts,
@@ -83,8 +84,10 @@ interface ImpactDTO {
}
interface AffectedDocumentDTO {
- kind: 'project' | 'workflow';
+ kind: IntermediatesAffectedDocumentKind;
user_id: string;
+ user_display_name: string | null;
+ user_email: string | null;
owner_id: string;
name: string | null;
references: number;
@@ -100,7 +103,6 @@ interface PreviewDTO {
has_more_eligible: boolean;
impact: ImpactDTO;
affected_documents: AffectedDocumentDTO[];
- affected_documents_hidden: number;
}
interface ProgressDTO {
@@ -206,6 +208,8 @@ const mapAffectedDocument = (dto: AffectedDocumentDTO): IntermediatesAffectedDoc
name: dto.name,
ownerId: dto.owner_id,
references: dto.references,
+ userDisplayName: dto.user_display_name,
+ userEmail: dto.user_email,
userId: dto.user_id,
});
@@ -311,7 +315,6 @@ export const createIntermediatesPreview = async (
return {
affectedDocuments: dto.affected_documents.map(mapAffectedDocument),
- affectedDocumentsHidden: dto.affected_documents_hidden,
createdAt: dto.created_at,
expiresAt: dto.expires_at,
impact: mapImpact(dto.impact),
@@ -323,16 +326,20 @@ export const createIntermediatesPreview = async (
};
};
+/** 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. */
export const startIntermediatesOperation = async (
request: { previewId: string; idempotencyKey: string },
- signal?: AbortSignal
+ signal: AbortSignal
): Promise<IntermediatesOperation> =>
mapIntermediatesOperation(
await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations`, {
body: JSON.stringify({ idempotency_key: request.idempotencyKey, preview_id: request.previewId }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
- signal,
+ signal: AbortSignal.any([signal, AbortSignal.timeout(START_TIMEOUT_MS)]),
})
);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
index 50afe25382..e19dddb931 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
@@ -1,4 +1,4 @@
-import { captureAccountScope, registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { captureAccountScope, registerAccountOwnedResource, type AccountScope } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -12,34 +12,42 @@ interface PendingStart {
idempotencyKey: string;
}
-const receiptKey = (): string => {
- const owner = captureAccountScope();
+/**
+ * A Confirm still in flight when the page reloads or the section closes is replayed once on the next mount; its
+ * idempotency key makes the replay return the same operation. A start that settled with an error is cleared, so only
+ * a fresh Confirm in the dialog can run it again.
+ */
+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 = (): { operationId?: string; pendingStart?: PendingStart } => {
+const readReceipt = (owner?: AccountScope): Receipt => {
try {
- return JSON.parse(sessionStorage.getItem(receiptKey()) ?? '{}') as {
- operationId?: string;
- pendingStart?: PendingStart;
- };
+ return JSON.parse(sessionStorage.getItem(receiptKey(owner)) ?? '{}') as Receipt;
} catch {
return {};
}
};
-const writeReceipt = (receipt: { operationId?: string; pendingStart?: PendingStart }): void => {
+const writeReceipt = (receipt: Receipt, owner?: AccountScope): void => {
try {
if (!receipt.operationId && !receipt.pendingStart) {
- sessionStorage.removeItem(receiptKey());
+ sessionStorage.removeItem(receiptKey(owner));
} else {
- sessionStorage.setItem(receiptKey(), JSON.stringify(receipt));
+ sessionStorage.setItem(receiptKey(owner), JSON.stringify(receipt));
}
} catch {
// A private-mode storage failure still leaves the in-memory operation visible this session.
}
};
+/** Restores the followed operation and returns a start whose response was lost, if any. */
export const restoreIntermediatesReceipt = (): PendingStart | null => {
const receipt = readReceipt();
if (typeof receipt.operationId === 'string' && receipt.operationId.length > 0) {
@@ -52,14 +60,15 @@ export const recordPendingIntermediatesStart = (pendingStart: PendingStart): voi
writeReceipt({ ...readReceipt(), pendingStart });
};
-export const isPendingIntermediatesStartCurrent = (pendingStart: PendingStart): boolean => {
- const current = readReceipt().pendingStart;
+export const isPendingIntermediatesStartCurrent = (pendingStart: PendingStart, owner?: AccountScope): boolean => {
+ const current = readReceipt(owner).pendingStart;
return current?.previewId === pendingStart.previewId && current.idempotencyKey === pendingStart.idempotencyKey;
};
-export const clearPendingIntermediatesStart = (): void => {
- const { operationId } = readReceipt();
- writeReceipt({ operationId });
+/** `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);
};
registerAccountOwnedResource({
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
new file mode 100644
index 0000000000..ca4dd0404a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.test.ts
@@ -0,0 +1,52 @@
+import type { ConnectionListener } from '@platform/transport/socketHub';
+import type { BackendConnectionStatus } from '@platform/transport/types';
+
+import { QueryClient } from '@tanstack/react-query';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const hub = vi.hoisted(() => ({
+ connection: null as ConnectionListener | null,
+ status: 'connected' as BackendConnectionStatus,
+}));
+
+vi.mock('@platform/transport/socketHub', () => ({
+ socketHub: {
+ on: () => () => undefined,
+ onConnectionChange: (listener: ConnectionListener) => {
+ hub.connection = listener;
+ listener(hub.status);
+ return () => {
+ hub.connection = null;
+ };
+ },
+ },
+}));
+
+const { attachIntermediatesRealtime } = await import('./realtime');
+
+afterEach(() => {
+ hub.status = 'connected';
+});
+
+it('does not refetch on open when the socket is already connected, but does after a reconnect', () => {
+ const queryClient = new QueryClient();
+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries');
+ const detach = attachIntermediatesRealtime(queryClient);
+
+ expect(invalidate).not.toHaveBeenCalled();
+ hub.connection!('disconnected');
+ hub.connection!('connected');
+ expect(invalidate).toHaveBeenCalledOnce();
+ detach();
+});
+
+it('refetches once the socket connects after opening while disconnected', () => {
+ hub.status = 'disconnected';
+ const queryClient = new QueryClient();
+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries');
+ const detach = attachIntermediatesRealtime(queryClient);
+
+ hub.connection!('connected');
+ expect(invalidate).toHaveBeenCalledOnce();
+ detach();
+});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
index ccb5ef3c08..b5b05eb4d4 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
@@ -61,11 +61,12 @@ export const attachIntermediatesRealtime = (queryClient: QueryClient): (() => vo
noteSettled(operation);
});
- let wasConnected = false;
+ // The hub reports the current status on subscribe; only a later transition to connected is a reconnect.
+ let wasConnected: boolean | null = null;
const detachConnection = socketHub.onConnectionChange((status) => {
const isConnected = status === 'connected';
- if (isConnected && !wasConnected && isAccountScopeCurrent(owner)) {
+ if (isConnected && wasConnected === false && isAccountScopeCurrent(owner)) {
void queryClient.invalidateQueries({ queryKey: accountKey });
}
wasConnected = isConnected;
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
index 0246329516..933c2e98ae 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
@@ -1,4 +1,9 @@
-import type { IntermediatesCleanupMode, IntermediatesPreview } from '@features/intermediates/core/types';
+import type {
+ IntermediatesAffectedDocument,
+ IntermediatesAffectedDocumentKind,
+ IntermediatesCleanupMode,
+ IntermediatesPreview,
+} from '@features/intermediates/core/types';
/* eslint-disable react-perf/jsx-no-new-function-as-prop */
import type { RefObject } from 'react';
@@ -11,6 +16,13 @@ import { formatBytes } from './format';
const CONFIRM_WORD = 'CLEAR';
+const AFFECTED_DOCUMENT_LABELS = {
+ client_state: 'intermediates.dialog.affectedClientState',
+ project: 'intermediates.dialog.affectedProject',
+ quarantined_project: 'intermediates.dialog.affectedQuarantinedProject',
+ workflow: 'intermediates.dialog.affectedWorkflow',
+} as const satisfies Record<IntermediatesAffectedDocumentKind, string>;
+
export interface ClearDialogState {
mode: IntermediatesCleanupMode;
/** Minted with each preview and reused for every Confirm of it, so a lost response replays the same operation. */
@@ -24,6 +36,10 @@ export interface ClearDialogState {
export interface ClearDialogProps {
state: ClearDialogState | null;
+ /** Documents owned by anyone else name their owner; null in single-user mode. */
+ currentUserId: string | null;
+ /** Force previews for administrators may include other accounts' documents; others' are never touched. */
+ canManageEveryone: boolean;
finalFocusRef: RefObject<HTMLElement | null>;
/** Receives focus when the trigger can no longer take it, e.g. a Delete button disabled by the cleared selection. */
fallbackFocusRef: RefObject<HTMLElement | null>;
@@ -35,7 +51,7 @@ export interface ClearDialogProps {
}
const Impact = ({ preview }: { preview: IntermediatesPreview }) => {
- const { t } = useTranslation();
+ const { i18n, t } = useTranslation();
const { impact } = preview;
const referenced = impact.keepReferencedImages + impact.keepReferencedVideos;
const active = impact.keepActiveImages + impact.keepActiveVideos;
@@ -68,9 +84,19 @@ const Impact = ({ preview }: { preview: IntermediatesPreview }) => {
<Text color="fg.muted" fontSize="xs">
{t('intermediates.dialog.kept', { count: kept })}{' '}
{t('intermediates.dialog.keptReasons', {
- active: t('intermediates.counts.items', { count: active }),
- recent: t('intermediates.counts.items', { count: recent }),
- referenced: t('intermediates.counts.items', { count: referenced }),
+ reasons: new Intl.ListFormat(i18n.resolvedLanguage, { style: 'long', type: 'conjunction' }).format(
+ (
+ [
+ ['keptReferenced', referenced],
+ ['keptActive', active],
+ ['keptRecent', recent],
+ ] as const
+ )
+ .filter(([, count]) => count > 0)
+ .map(([key, count]) =>
+ t(`intermediates.dialog.${key}`, { items: t('intermediates.counts.items', { count }) })
+ )
+ ),
})}
</Text>
) : null}
@@ -78,10 +104,19 @@ const Impact = ({ preview }: { preview: IntermediatesPreview }) => {
);
};
-const AffectedDocuments = ({ preview }: { preview: IntermediatesPreview }) => {
+const getDocumentOwnerLabel = (document: IntermediatesAffectedDocument): string =>
+ document.userDisplayName || document.userEmail || document.userId;
+
+const AffectedDocuments = ({
+ currentUserId,
+ preview,
+}: {
+ currentUserId: string | null;
+ preview: IntermediatesPreview;
+}) => {
const { t } = useTranslation();
- if (preview.affectedDocuments.length === 0 && preview.affectedDocumentsHidden === 0) {
+ if (preview.affectedDocuments.length === 0) {
return null;
}
@@ -93,19 +128,18 @@ const AffectedDocuments = ({ preview }: { preview: IntermediatesPreview }) => {
<Stack as="ul" gap="0.5" maxH="32" overflowY="auto" ps="4">
{preview.affectedDocuments.map((document) => (
<Text as="li" fontSize="xs" key={`${document.kind}:${document.userId}:${document.ownerId}`}>
- {t(
- document.kind === 'project'
- ? 'intermediates.dialog.affectedProject'
- : 'intermediates.dialog.affectedWorkflow',
- { count: document.references, name: document.name ?? document.ownerId }
- )}
+ {t(AFFECTED_DOCUMENT_LABELS[document.kind], {
+ count: document.references,
+ name: document.name ?? document.ownerId,
+ })}
+ {currentUserId !== null && document.userId !== currentUserId ? (
+ <Text as="span" color="fg.muted">
+ {' '}
+ {t('intermediates.dialog.affectedOwner', { owner: getDocumentOwnerLabel(document) })}
+ </Text>
+ ) : null}
</Text>
))}
- {preview.affectedDocumentsHidden > 0 ? (
- <Text as="li" color="fg.muted" fontSize="xs">
- {t('intermediates.dialog.affectedHidden', { count: preview.affectedDocumentsHidden })}
- </Text>
- ) : null}
</Stack>
</Stack>
);
@@ -116,6 +150,8 @@ const AffectedDocuments = ({ preview }: { preview: IntermediatesPreview }) => {
* force preview, which adds the affected documents, an acknowledgement and a typed confirmation.
*/
export const ClearDialog = ({
+ canManageEveryone,
+ currentUserId,
fallbackFocusRef,
finalFocusRef,
onClose,
@@ -232,11 +268,17 @@ export const ClearDialog = ({
<Alert.Root size="sm" status="warning" variant="surface">
<Alert.Indicator />
<Alert.Content>
- <Alert.Description>{t('intermediates.dialog.forceWarning')}</Alert.Description>
+ <Alert.Description>
+ {t(
+ canManageEveryone
+ ? 'intermediates.dialog.forceWarning'
+ : 'intermediates.dialog.forceWarningOwn'
+ )}
+ </Alert.Description>
</Alert.Content>
</Alert.Root>
) : null}
- {isForce && preview ? <AffectedDocuments preview={preview} /> : null}
+ {isForce && preview ? <AffectedDocuments currentUserId={currentUserId} preview={preview} /> : null}
{isForce && preview && !nothingToDelete ? (
<Stack gap="2">
<Checkbox.Root
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
index d64a7ba5b1..530e0ef459 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
@@ -70,6 +70,8 @@ const describeRow = (row: IntermediatesRow, showOwner: boolean, t: TFunction): s
};
export interface IntermediatesListProps {
+ /** The previous page stays visible while the next loads; it is shown, not selectable. */
+ isBusy: boolean;
rows: readonly IntermediatesRow[];
showOwner: boolean;
isSelected: (row: IntermediatesRow) => boolean;
@@ -77,12 +79,21 @@ export interface IntermediatesListProps {
}
/** One row per project, as the sketch: checkbox, cover, name over owner, then the used and unused counts. */
-export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }: IntermediatesListProps) => {
+export const IntermediatesList = ({ isBusy, isSelected, onToggleRow, rows, showOwner }: IntermediatesListProps) => {
const { t } = useTranslation();
const unassigned = t('intermediates.list.unassigned');
return (
- <Stack as="ul" aria-label={t('intermediates.title')} gap="0.5" listStyleType="none" m="0" p="0" role="list">
+ <Stack
+ as="ul"
+ aria-busy={isBusy || undefined}
+ aria-label={t('intermediates.title')}
+ gap="0.5"
+ listStyleType="none"
+ m="0"
+ p="0"
+ role="list"
+ >
{rows.map((row) => {
const label = getRowLabel(row, unassigned);
const selected = isSelected(row);
@@ -93,7 +104,7 @@ export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }:
<Row
as="li"
active={selected ? 'selected' : 'none'}
- cursor="pointer"
+ cursor={isBusy ? 'progress' : 'pointer'}
data-selected={selected || undefined}
gap="2.5"
key={getIntermediatesRowKey(row)}
@@ -101,7 +112,7 @@ export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }:
px="2"
py="1.5"
rounded="md"
- onClick={() => onToggleRow(row)}
+ onClick={isBusy ? undefined : () => onToggleRow(row)}
>
<Checkbox.Root
aria-label={
@@ -115,6 +126,7 @@ export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }:
}
checked={selected}
colorPalette="accent"
+ disabled={isBusy}
size="xs"
onCheckedChange={() => onToggleRow(row)}
onClick={(event) => event.stopPropagation()}
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 5e822c289c..0c17676cd6 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
@@ -6,6 +6,7 @@ import type {
} from '@features/intermediates/core/types';
import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -32,6 +33,7 @@ vi.mock('@features/intermediates/data/api', () => ({
vi.mock('@features/intermediates/data/realtime', () => ({ attachIntermediatesRealtime: () => () => undefined }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
+ i18n: { resolvedLanguage: 'en' },
t: (key: string, options?: Record<string, unknown>) =>
options && Object.keys(options).length > 0
? `${key}(${Object.entries(options)
@@ -76,10 +78,22 @@ const summaryOf = (items: IntermediatesRow[]): IntermediatesSummary => ({
},
});
+const documentOf = (userId: string) => ({
+ userDisplayName: userId === 'bob' ? 'Bob' : 'Alice',
+ userEmail: `${userId}@example.com`,
+ userId,
+});
+
const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesPreview => ({
affectedDocuments:
- mode === 'force' ? [{ kind: 'project', name: 'Portraits', ownerId: 'p1', references: 2, userId: 'alice' }] : [],
- affectedDocumentsHidden: 0,
+ mode === 'force'
+ ? [
+ { ...documentOf('alice'), kind: 'project', name: 'Portraits', ownerId: 'p1', references: 2 },
+ { ...documentOf('alice'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
+ { ...documentOf('alice'), kind: 'quarantined_project', name: 'Old sketch', ownerId: 'q1', references: 1 },
+ { ...documentOf('bob'), kind: 'client_state', name: null, ownerId: 'canvas', references: 1 },
+ ]
+ : [],
createdAt: 'now',
expiresAt: 'later',
impact: {
@@ -190,6 +204,26 @@ 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'));
+ 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 toggles = () => [...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
+ await act(() => toggles()[0]!.click());
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.affectedClientState'));
+ await act(() => toggles()[1]!.click());
+ await act(() => setInputValue(dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])')!, 'CLEAR'));
+ return dialog;
+};
+
describe('IntermediatesManager', () => {
beforeEach(() => {
sessionStorage.clear();
@@ -393,13 +427,96 @@ describe('IntermediatesManager', () => {
await act(() => resolveNew({ ...operationOf('running'), operationId: 'new-op' }));
});
- it('drops a definitively rejected start receipt', async () => {
+ 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', 409));
+ 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();
+ });
+
+ it('forgets a start that sign-out cut off, so signing back in never replays it', async () => {
+ accountLifecycle.activate('alice');
+ try {
+ dependencies.startIntermediatesOperation.mockImplementation(
+ (_request: unknown, signal: AbortSignal) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
+ })
+ );
+ 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 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();
+ } finally {
+ accountLifecycle.invalidate();
+ }
+ });
+
+ it('explains a timed-out start and lets Confirm resume the same cleanup', 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'));
+ const confirm = buttonWithText('intermediates.dialog.forceConfirm', dialog);
+ expect(confirm.disabled).toBe(false);
+
+ await act(() => confirm.click());
+ await vi.waitFor(() => expect(dependencies.startIntermediatesOperation).toHaveBeenCalledTimes(2));
+ const [first, second] = dependencies.startIntermediatesOperation.mock.calls;
+ expect(second![0]).toEqual(first![0]);
+ });
+
+ it('names the owner of another account’s affected documents for an administrator', async () => {
+ const dialog = await openForceDialogReadyToConfirm({ canClearOthersIntermediates: true });
+ const items = [...dialog.querySelectorAll('li')].map((item) => item.textContent ?? '');
+ expect(items.filter((text) => text.includes('affectedOwner'))).toEqual([
+ expect.stringContaining('intermediates.dialog.affectedOwner(owner=Bob)'),
+ ]);
+ expect(dialog.textContent).toContain('intermediates.dialog.forceWarning');
+ expect(dialog.textContent).not.toContain('intermediates.dialog.forceWarningOwn');
+ });
+
+ it('never replays a force delete the user cancelled after its start failed', async () => {
+ const dialog = await openForceDialogReadyToConfirm();
+ expect(dialog.textContent).toContain('intermediates.dialog.affectedQuarantinedProject(count=1,name=Old sketch)');
+ 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 () => {
@@ -544,6 +661,7 @@ describe('IntermediatesManager', () => {
return element!;
});
await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+ expect(dialog.textContent).toContain('intermediates.dialog.keptReferenced');
const toggles = () => [...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
await act(() => toggles()[0]!.click());
@@ -554,6 +672,9 @@ describe('IntermediatesManager', () => {
)
);
await vi.waitFor(() => expect(dialog.textContent).toContain('Portraits'));
+ // Force mode keeps nothing for being referenced, so that reason is not listed at zero.
+ expect(dialog.textContent).not.toContain('intermediates.dialog.keptReferenced');
+ expect(dialog.textContent).toContain('intermediates.dialog.keptActive');
const confirm = () => buttonWithText('intermediates.dialog.forceConfirm', dialog);
expect(confirm().disabled).toBe(true);
@@ -588,6 +709,60 @@ describe('IntermediatesManager', () => {
expect(host.textContent).toContain('count=1');
});
+ it('keeps the current page visible but inert while the next loads, and never shows stale rows for a new search', async () => {
+ const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
+ let releaseNextPage!: () => void;
+ const nextPageGate = new Promise<void>((resolve) => {
+ releaseNextPage = resolve;
+ });
+ let releaseSearch!: () => void;
+ const searchGate = new Promise<void>((resolve) => {
+ releaseSearch = resolve;
+ });
+ dependencies.getIntermediatesSummary
+ .mockReset()
+ .mockImplementation(async (params: { offset?: number; search?: string }) => {
+ const offset = params.offset ?? 0;
+ if (params.search?.trim()) {
+ await searchGate;
+ return summaryOf([row('p1', 'Project 1', 1)]);
+ }
+ if (offset > 0) {
+ await nextPageGate;
+ }
+ return { ...summaryOf(manyRows.slice(offset, offset + 50)), offset, total: manyRows.length };
+ });
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 0'));
+
+ await act(() => buttonWithText('common.nextPage', host).click());
+ const list = host.querySelector('[role="list"]')!;
+ await vi.waitFor(() => expect(list.getAttribute('aria-busy')).toBe('true'));
+ expect(host.textContent).toContain('Project 0');
+ expect(host.textContent).toContain('common.pageNumber(page=1)');
+ const staleRow = host
+ .querySelector('[aria-label="intermediates.list.selectRow(name=Project 0)"]')!
+ .querySelector<HTMLInputElement>('input')!;
+ expect(staleRow.disabled).toBe(true);
+ expect(checkbox('intermediates.list.selectAll').checked).toBe(false);
+ expect(host.querySelector('[aria-label="intermediates.list.selectAll"]')!.querySelector('input')!.disabled).toBe(
+ true
+ );
+
+ await act(() => releaseNextPage());
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 55'));
+ expect(host.querySelector('[role="list"]')!.getAttribute('aria-busy')).toBeNull();
+ expect(host.textContent).toContain('common.pageNumber(page=2)');
+
+ await act(() =>
+ setInputValue(host.querySelector<HTMLInputElement>('input[aria-label="intermediates.searchLabel"]')!, 'one')
+ );
+ await vi.waitFor(() => expect(host.textContent).not.toContain('Project 55'));
+ expect(host.querySelector('[role="list"]')).toBeNull();
+ await act(() => releaseSearch());
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 1'));
+ });
+
it('keeps picks from another page in the estimate and the targets', async () => {
const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
dependencies.getIntermediatesSummary.mockReset().mockImplementation((params: { offset?: number }) => {
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
index 3b712f485e..e8378bc6af 100644
--- a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
@@ -1,9 +1,4 @@
-import type {
- IntermediatesCleanupMode,
- IntermediatesPreview,
- IntermediatesRow,
- IntermediatesScope,
-} from '@features/intermediates/core/types';
+import type { IntermediatesRow } from '@features/intermediates/core/types';
/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */
import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
import type { TFunction } from 'i18next';
@@ -22,47 +17,15 @@ import {
Stack,
Text,
} from '@chakra-ui/react';
-import {
- EMPTY_SELECTION,
- isRowSelected,
- resolveScope,
- selectAllMatching,
- summarizeSelection,
- toggleRowSelection,
- withRowSelected,
- type IntermediatesSelection,
-} from '@features/intermediates/core/selection';
-import {
- createIntermediatesPreview,
- getIntermediatesOperation,
- getIntermediatesSummary,
- retryIntermediatesOperation,
- startIntermediatesOperation,
-} from '@features/intermediates/data/api';
+import { isRowSelected, resolveScope } from '@features/intermediates/core/selection';
import { takeIntermediatesFocus } from '@features/intermediates/data/focus';
import { intermediatesKeys } from '@features/intermediates/data/keys';
-import {
- activeOperationStore,
- clearPendingIntermediatesStart,
- followIntermediatesOperation,
- isPendingIntermediatesStartCurrent,
- recordPendingIntermediatesStart,
- restoreIntermediatesReceipt,
-} from '@features/intermediates/data/operationStore';
import {
INTERMEDIATES_MAX_ROWS,
INTERMEDIATES_PAGE_SIZE,
- intermediatesOperationQueryOptions,
intermediatesSummaryQueryOptions,
} from '@features/intermediates/data/queries';
-import { attachIntermediatesRealtime } from '@features/intermediates/data/realtime';
-import { useMountEffect } from '@platform/react/useMountEffect';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
-import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
import { EmptyState } from '@platform/ui/EmptyState';
import { Scrollable } from '@platform/ui/Scrollable';
@@ -72,12 +35,13 @@ import { BrushCleaningIcon, RefreshCwIcon, SearchIcon, Trash2Icon, XIcon } from
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { ClearDialogState } from './ClearDialog';
-
import { ClearDialog } from './ClearDialog';
import { formatBytes } from './format';
import { getOwnerLabel, IntermediatesList } from './IntermediatesList';
import { OperationPanel } from './OperationPanel';
+import { useCleanupDialog } from './useCleanupDialog';
+import { useFollowedOperation } from './useFollowedOperation';
+import { useIntermediatesSelection } from './useIntermediatesSelection';
export interface IntermediatesManagerProps {
/** The current account, or null in single-user mode where the install is the only account. */
@@ -87,29 +51,22 @@ export interface IntermediatesManagerProps {
const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;
const EMPTY_ROWS: readonly IntermediatesRow[] = [];
-const EMPTY_TOTALS = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos: 0, unknownSizeCount: 0 };
+
+const isSameListExceptOffset = (previous: unknown, next: IntermediatesSummaryParams): boolean => {
+ if (typeof previous !== 'object' || previous === null) {
+ return false;
+ }
+ const { offset: _previousOffset, ...previousRest } = previous as IntermediatesSummaryParams;
+ const { offset: _nextOffset, ...nextRest } = next;
+ const keys = new Set([...Object.keys(previousRest), ...Object.keys(nextRest)]) as Set<keyof typeof nextRest>;
+ return [...keys].every((key) => previousRest[key] === nextRest[key]);
+};
const formatSummarySize = (bytes: number, unknownCount: number, t: TFunction): string =>
unknownCount > 0
? `${formatBytes(bytes)} ${t('intermediates.list.unmeasured', { count: unknownCount })}`
: formatBytes(bytes);
-let nextIdempotencyKey = 1;
-const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;
-
-const isDefinitiveStartRejection = (error: unknown): boolean =>
- error instanceof ApiError && error.status >= 400 && error.status < 500 && error.status !== 408;
-
-const getLatestRetry = async (operationId: string, signal: AbortSignal) => {
- let operation = await getIntermediatesOperation(operationId, signal);
- const visited = new Set<string>([operationId]);
- while (operation.retriedByOperationId && !visited.has(operation.retriedByOperationId)) {
- visited.add(operation.retriedByOperationId);
- operation = await getIntermediatesOperation(operation.retriedByOperationId, signal);
- }
- return operation;
-};
-
/** The Settings section: search, a select-all row with the delete action, and one row per project. */
export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserId }: IntermediatesManagerProps) => {
const { t } = useTranslation();
@@ -122,64 +79,8 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
);
const [projectFilter, setProjectFilter] = useState<string | null>(focus?.projectId ?? null);
const [offset, setOffset] = useState(0);
- const [selection, setSelection] = useState<IntermediatesSelection>(EMPTY_SELECTION);
- // The focused project is queried directly, so pagination cannot hide the entry point's selection.
- const [pendingProjectId, setPendingProjectId] = useState<string | null>(focus?.projectId ?? null);
- const [dialog, setDialog] = useState<ClearDialogState | null>(null);
- const activeOperationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
- const [retryError, setRetryError] = useState<string | null>(null);
- const [recoveryError, setRecoveryError] = useState<string | null>(null);
- const [isRetrying, setIsRetrying] = useState(false);
- const dialogTriggerRef = useRef<HTMLElement | null>(null);
const searchRef = useRef<HTMLInputElement | null>(null);
- const previewRequestRef = useRef(0);
- const pendingScopeRef = useRef<IntermediatesScope | null>(null);
-
- useMountEffect(() => {
- let mounted = true;
- const detach = attachIntermediatesRealtime(queryClient);
- const pending = restoreIntermediatesReceipt();
- if (pending) {
- const owner = captureAccountScope();
- void startIntermediatesOperation(pending, owner.signal)
- .then((operation) => {
- if (mounted && isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
- }
- })
- .catch((error: unknown) => {
- if (mounted && isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
- if (isDefinitiveStartRejection(error)) {
- clearPendingIntermediatesStart();
- }
- setRecoveryError(getApiErrorMessage(error, t('intermediates.dialog.startFailed')));
- }
- });
- } else {
- const operationId = activeOperationStore.getSnapshot().operationId;
- if (operationId) {
- const owner = captureAccountScope();
- void getLatestRetry(operationId, owner.signal)
- .then((operation) => {
- if (
- mounted &&
- isAccountScopeCurrent(owner) &&
- activeOperationStore.getSnapshot().operationId === operationId &&
- operation.operationId !== operationId
- ) {
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
- }
- })
- .catch(() => undefined); // The operation query reports lookup failures in the panel.
- }
- }
- return () => {
- mounted = false;
- detach();
- };
- });
+ const operation = useFollowedOperation({ fallbackFocusRef: searchRef });
// Non-admins are confined to their own rows by the server whatever is sent.
const ownerId: string | null = canClearOthersIntermediates ? ownerFilter : currentUserId;
@@ -195,37 +96,32 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
}),
[offset, ownerId, projectFilter, search]
);
- const query = useQuery(intermediatesSummaryQueryOptions(params));
+ // Paging keeps the current rows on screen until the next page arrives; any other change is a different list.
+ const query = useQuery({
+ ...intermediatesSummaryQueryOptions(params),
+ placeholderData: (previous, previousQuery) =>
+ previousQuery && isSameListExceptOffset(previousQuery.queryKey.at(-1), params) ? previous : undefined,
+ });
+ const isPaging = query.isPlaceholderData;
const rows = query.data?.items ?? EMPTY_ROWS;
const totals = query.data?.totals;
const hasSearch = search.trim().length > 0;
const hasSubsetFilter = hasSearch || projectFilter !== null;
// Rows disappearing (a cleanup, a narrower search) can leave the offset past the end; step back to a valid page.
- if (query.data && offset > 0 && offset >= query.data.total) {
+ if (query.data && !query.isPlaceholderData && offset > 0 && offset >= query.data.total) {
setOffset(
Math.max(0, Math.floor(Math.max(query.data.total - 1, 0) / INTERMEDIATES_PAGE_SIZE) * INTERMEDIATES_PAGE_SIZE)
);
}
- 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 && query.data !== undefined,
- });
- const matchingSnapshot = matchingSnapshotQuery.data;
- const selectionOverLimit =
- hasExclusions && matchingSnapshot !== undefined && matchingSnapshot.total > matchingSnapshot.items.length;
- const operationQuery = useQuery({
- ...intermediatesOperationQueryOptions(activeOperationId ?? ''),
- enabled: activeOperationId !== null,
+ const selection = useIntermediatesSelection({
+ initialProjectId: focus?.projectId ?? null,
+ params,
+ rows,
+ summary: query.data,
});
+ const dialog = useCleanupDialog({ onStarted: selection.reset, params, selection: selection.effectiveSelection });
+ const { reset: resetSelection } = selection;
- const resetSelection = useCallback(() => {
- setPendingProjectId(null);
- setSelection(EMPTY_SELECTION);
- }, []);
const handleSearchChange = useCallback(
(value: string) => {
setSearch(value);
@@ -251,205 +147,17 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
setOffset(0);
resetSelection();
}, [resetSelection]);
- const handleToggleRow = useCallback(
- (row: IntermediatesRow) => {
- setPendingProjectId(null);
- setSelection(toggleRowSelection(effectiveSelection, row));
- },
- [effectiveSelection]
- );
- const selectionSummary = useMemo(
- () =>
- summarizeSelection(
- effectiveSelection,
- totals ?? EMPTY_TOTALS,
- matchingSnapshot && !matchingSnapshotQuery.isError && !selectionOverLimit ? matchingSnapshot.items : undefined,
- rows
- ),
- [effectiveSelection, matchingSnapshot, matchingSnapshotQuery.isError, rows, selectionOverLimit, totals]
- );
- const matchingRowCount = hasExclusions ? matchingSnapshot?.total : totals?.rows;
- // Select all selects every matching row, including pages not loaded; only a complete selection clears.
- const handleToggleAll = useCallback(() => {
- setPendingProjectId(null);
- setSelection(
- selectionSummary !== null && selectionSummary.rows === matchingRowCount ? EMPTY_SELECTION : selectAllMatching()
- );
- }, [selectionSummary, matchingRowCount]);
-
- const loadPreview = useCallback(
- async (mode: IntermediatesCleanupMode, scope: IntermediatesScope) => {
- const requestId = ++previewRequestRef.current;
- const owner = captureAccountScope();
- setDialog((current) => ({
- idempotencyKey: current?.idempotencyKey ?? createIdempotencyKey(),
- isStarting: false,
- mode,
- preview: null,
- previewError: null,
- startError: null,
- }));
- try {
- let resolvedScope = scope;
- // Filters and exclusions cannot be expressed by the cleanup scope; resolve them to explicit rows.
- if (effectiveSelection.mode === 'all-matching' && scope.kind === 'selection') {
- const everything = await getIntermediatesSummary(
- { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
- owner.signal
- );
- assertAccountScopeCurrent(owner);
- if (everything.total > everything.items.length) {
- throw new Error(t('intermediates.dialog.tooManyRows', { count: everything.items.length }));
- }
- resolvedScope = {
- kind: 'selection',
- targets: everything.items
- .filter((row) => isRowSelected(effectiveSelection, row))
- .map(({ projectId, userId }) => ({ projectId, userId })),
- };
- }
- const preview = await createIntermediatesPreview({ mode, scope: resolvedScope }, owner.signal);
- assertAccountScopeCurrent(owner);
- if (previewRequestRef.current === requestId) {
- // One key per preview: every Confirm of this preview replays the same operation, and a later preview
- // (mode switch, retry) starts clean instead of colliding with a key the server already settled.
- setDialog((current) => (current ? { ...current, idempotencyKey: createIdempotencyKey(), preview } : current));
- }
- } catch (error) {
- if (previewRequestRef.current === requestId && isAccountScopeCurrent(owner)) {
- setDialog((current) =>
- current
- ? { ...current, previewError: getApiErrorMessage(error, t('intermediates.dialog.previewFailed')) }
- : current
- );
- }
- }
- },
- [effectiveSelection, params, t]
- );
- const openDialog = useCallback(
- (scope: IntermediatesScope, trigger: HTMLElement | null) => {
- dialogTriggerRef.current = trigger;
- pendingScopeRef.current = scope;
- setRetryError(null);
- setDialog(null);
- void loadPreview('safe', scope);
- },
- [loadPreview]
- );
- const closeDialog = useCallback(() => {
- previewRequestRef.current += 1;
- setDialog(null);
- }, []);
- const retryPreview = useCallback(() => {
- if (dialog && pendingScopeRef.current) {
- void loadPreview(dialog.mode, pendingScopeRef.current);
- }
- }, [dialog, loadPreview]);
- const changeMode = useCallback(
- (mode: IntermediatesCleanupMode) => {
- if (pendingScopeRef.current) {
- void loadPreview(mode, pendingScopeRef.current);
- }
- },
- [loadPreview]
- );
- const confirmDialog = useCallback(async () => {
- const preview: IntermediatesPreview | null = dialog?.preview ?? null;
-
- if (!dialog || !preview) {
- return;
- }
- const owner = captureAccountScope();
- recordPendingIntermediatesStart({ idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId });
- setDialog((current) => (current ? { ...current, isStarting: true, startError: null } : current));
- try {
- const operation = await startIntermediatesOperation(
- { idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId },
- owner.signal
- );
- assertAccountScopeCurrent(owner);
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
- resetSelection();
- setDialog(null);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- 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.
- const previewGone = error instanceof ApiError && error.status === 404;
- if (isDefinitiveStartRejection(error)) {
- clearPendingIntermediatesStart();
- }
- setDialog((current) =>
- current
- ? {
- ...current,
- isStarting: false,
- preview: previewGone ? null : current.preview,
- previewError: previewGone ? t('intermediates.dialog.previewExpired') : current.previewError,
- startError: previewGone ? null : getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
- }
- : current
- );
- }
- }, [dialog, queryClient, resetSelection, t]);
-
- const handleRetry = useCallback(async () => {
- if (!activeOperationId) {
- return;
- }
- const owner = captureAccountScope();
- setIsRetrying(true);
- setRetryError(null);
- try {
- const operation = await retryIntermediatesOperation(activeOperationId, owner.signal);
- assertAccountScopeCurrent(owner);
- queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
- followIntermediatesOperation(operation.operationId);
- } catch (error) {
- if (isAccountScopeCurrent(owner)) {
- try {
- const latest = await getLatestRetry(activeOperationId, owner.signal);
- if (
- latest.operationId !== activeOperationId &&
- isAccountScopeCurrent(owner) &&
- activeOperationStore.getSnapshot().operationId === activeOperationId
- ) {
- queryClient.setQueryData(intermediatesKeys.operation(owner, latest.operationId), latest);
- followIntermediatesOperation(latest.operationId);
- return;
- }
- } catch {
- // Preserve the original retry error when reconciliation is unavailable.
- }
- setRetryError(getApiErrorMessage(error, t('intermediates.operation.retryFailed')));
- }
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsRetrying(false);
- }
- }
- }, [activeOperationId, queryClient, t]);
- const dismissOperation = useCallback(() => {
- followIntermediatesOperation(null);
- setRetryError(null);
- // The Dismiss button unmounts with the panel; keep keyboard focus in the section.
- searchRef.current?.focus();
- }, []);
const handleRefresh = useCallback(() => {
void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all });
}, [queryClient]);
- const selectedScope = resolveScope({ hasSubsetFilter, loadedRows: rows, ownerId, selection: effectiveSelection });
- const hasSelection = selectionSummary ? selectionSummary.rows > 0 : hasExclusions && (totals?.rows ?? 0) > 0;
- const selectionState = hasSelection
- ? selectionSummary !== null && selectionSummary.rows === matchingRowCount
- ? 'all'
- : 'some'
- : 'none';
+ const selectedScope = resolveScope({
+ hasSubsetFilter,
+ loadedRows: rows,
+ ownerId,
+ selection: selection.effectiveSelection,
+ });
+ const { selectionSummary } = selection;
const filteredOwnerRow = ownerFilter ? rows[0] : undefined;
const hasPreviousPage = offset > 0;
const hasNextPage = query.data !== undefined && offset + rows.length < query.data.total;
@@ -479,9 +187,9 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</IconButton>
</Tooltip>
</HStack>
- {recoveryError ? (
+ {operation.recoveryError ? (
<Text color="fg.error" fontSize="xs" role="alert">
- {recoveryError}
+ {operation.recoveryError}
</Text>
) : null}
<HStack flexWrap="wrap" gap="2">
@@ -524,7 +232,7 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
) : null}
{projectFilter ? (
<Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
- {focusedRow?.projectName ?? t('intermediates.owner.projectFilter')}
+ {selection.focusedRow?.projectName ?? t('intermediates.owner.projectFilter')}
<Tooltip content={t('intermediates.owner.showAllProjects')}>
<IconButton
aria-label={t('intermediates.owner.showAllProjects')}
@@ -539,21 +247,21 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Badge>
) : null}
</HStack>
- {activeOperationId ? (
+ {operation.operationId ? (
<OperationPanel
- isLoading={operationQuery.isPending}
- isRefetching={operationQuery.isFetching}
+ isLoading={operation.query.isPending}
+ isRefetching={operation.query.isFetching}
lookupError={
- operationQuery.isError
- ? getApiErrorMessage(operationQuery.error, t('intermediates.operation.lookupFailed'))
+ operation.query.isError
+ ? getApiErrorMessage(operation.query.error, t('intermediates.operation.lookupFailed'))
: null
}
- onRefetch={() => void operationQuery.refetch()}
- isRetrying={isRetrying}
- operation={operationQuery.data ?? null}
- retryError={retryError}
- onDismiss={dismissOperation}
- onRetry={() => void handleRetry()}
+ onRefetch={() => void operation.query.refetch()}
+ isRetrying={operation.isRetrying}
+ operation={operation.query.data ?? null}
+ retryError={operation.retryError}
+ onDismiss={operation.dismiss}
+ onRetry={() => void operation.retry()}
/>
) : null}
<Stack flex="1" gap="0" minH="0" mt="-3">
@@ -561,11 +269,13 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
<HStack borderBottomWidth="1px" borderColor="border.subtle" flexShrink={0} gap="2" minH="8" py="1.5">
<Checkbox.Root
aria-label={t('intermediates.list.selectAll')}
- checked={selectionState === 'all' ? true : selectionState === 'some' ? 'indeterminate' : false}
+ checked={
+ selection.selectionState === 'all' ? true : selection.selectionState === 'some' ? 'indeterminate' : false
+ }
colorPalette="accent"
- disabled={rows.length === 0}
+ disabled={rows.length === 0 || isPaging}
size="xs"
- onCheckedChange={handleToggleAll}
+ onCheckedChange={selection.toggleAll}
pl="2"
>
<Checkbox.HiddenInput />
@@ -575,16 +285,9 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
</Checkbox.Label>
</Checkbox.Root>
<Text color="fg.muted" flex="1" fontSize="2xs" minW="0" textAlign="end" truncate>
- {hasExclusions && selectionSummary === null
- ? t(
- selectionOverLimit
- ? 'intermediates.selection.tooManyRows'
- : matchingSnapshotQuery.isError
- ? 'intermediates.selection.estimateFailed'
- : 'intermediates.selection.checking',
- { count: INTERMEDIATES_MAX_ROWS }
- )
- : hasSelection && selectionSummary
+ {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 }),
@@ -607,10 +310,13 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
<Separator borderColor="border.subtle" h="4" orientation="vertical" />
<Button
colorPalette="red"
- disabled={!hasSelection}
+ disabled={!selection.hasSelection}
size="2xs"
variant="ghost"
- onClick={(event) => openDialog(selectedScope, event.currentTarget)}
+ onClick={(event) => {
+ operation.clearRetryError();
+ dialog.open(selectedScope, event.currentTarget);
+ }}
>
<Icon as={Trash2Icon} boxSize="3" />
{t('intermediates.list.delete')}
@@ -652,10 +358,11 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
<Scrollable flex="1" h="full" label={t('intermediates.title')} minH="0">
<Box py="1">
<IntermediatesList
- isSelected={(row) => isRowSelected(effectiveSelection, row)}
+ isBusy={isPaging}
+ isSelected={(row) => isRowSelected(selection.effectiveSelection, row)}
rows={rows}
showOwner={canClearOthersIntermediates && ownerId === null}
- onToggleRow={handleToggleRow}
+ onToggleRow={selection.toggleRow}
/>
</Box>
</Scrollable>
@@ -672,7 +379,9 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
{t('common.previousPage')}
</Button>
<Text aria-live="polite" color="fg.muted" fontSize="2xs">
- {t('common.pageNumber', { page: Math.floor(offset / INTERMEDIATES_PAGE_SIZE) + 1 })}
+ {t('common.pageNumber', {
+ page: Math.floor((query.data?.offset ?? offset) / INTERMEDIATES_PAGE_SIZE) + 1,
+ })}
</Text>
<Button
aria-label={t('common.nextPage')}
@@ -687,13 +396,15 @@ export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserI
) : null}
</Stack>
<ClearDialog
+ canManageEveryone={canClearOthersIntermediates}
+ currentUserId={currentUserId}
fallbackFocusRef={searchRef}
- finalFocusRef={dialogTriggerRef}
- state={dialog}
- onClose={closeDialog}
- onConfirm={() => void confirmDialog()}
- onModeChange={changeMode}
- onRetryPreview={retryPreview}
+ finalFocusRef={dialog.triggerRef}
+ state={dialog.state}
+ onClose={dialog.close}
+ onConfirm={() => void dialog.confirm()}
+ onModeChange={dialog.changeMode}
+ onRetryPreview={dialog.retryPreview}
/>
</Stack>
);
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
new file mode 100644
index 0000000000..63c671d247
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useCleanupDialog.ts
@@ -0,0 +1,175 @@
+import type { IntermediatesSelection } from '@features/intermediates/core/selection';
+import type { IntermediatesCleanupMode, IntermediatesScope } from '@features/intermediates/core/types';
+import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
+
+import { isRowSelected } from '@features/intermediates/core/selection';
+import {
+ createIntermediatesPreview,
+ getIntermediatesSummary,
+ startIntermediatesOperation,
+} from '@features/intermediates/data/api';
+import { intermediatesKeys } from '@features/intermediates/data/keys';
+import {
+ clearPendingIntermediatesStart,
+ followIntermediatesOperation,
+ recordPendingIntermediatesStart,
+} from '@features/intermediates/data/operationStore';
+import { INTERMEDIATES_MAX_ROWS } from '@features/intermediates/data/queries';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { useQueryClient } from '@tanstack/react-query';
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ClearDialogState } from './ClearDialog';
+
+let nextIdempotencyKey = 1;
+const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;
+
+/** The confirmation flow: preview a scope, optionally switch to force, and start the operation it froze. */
+export const useCleanupDialog = ({
+ onStarted,
+ params,
+ selection,
+}: {
+ onStarted: () => void;
+ params: IntermediatesSummaryParams;
+ selection: IntermediatesSelection;
+}) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const [dialog, setDialog] = useState<ClearDialogState | null>(null);
+ const triggerRef = useRef<HTMLElement | null>(null);
+ const requestRef = useRef(0);
+ const scopeRef = useRef<IntermediatesScope | null>(null);
+
+ const loadPreview = useCallback(
+ async (mode: IntermediatesCleanupMode, scope: IntermediatesScope) => {
+ const requestId = ++requestRef.current;
+ const owner = captureAccountScope();
+ setDialog((current) => ({
+ idempotencyKey: current?.idempotencyKey ?? createIdempotencyKey(),
+ isStarting: false,
+ mode,
+ preview: null,
+ previewError: null,
+ startError: null,
+ }));
+ try {
+ let resolvedScope = scope;
+ // Filters and exclusions cannot be expressed by the cleanup scope; resolve them to explicit rows.
+ if (selection.mode === 'all-matching' && scope.kind === 'selection') {
+ const everything = await getIntermediatesSummary(
+ { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
+ if (everything.total > everything.items.length) {
+ throw new Error(t('intermediates.dialog.tooManyRows', { count: everything.items.length }));
+ }
+ resolvedScope = {
+ kind: 'selection',
+ targets: everything.items
+ .filter((row) => isRowSelected(selection, row))
+ .map(({ projectId, userId }) => ({ projectId, userId })),
+ };
+ }
+ const preview = await createIntermediatesPreview({ mode, scope: resolvedScope }, owner.signal);
+ assertAccountScopeCurrent(owner);
+ if (requestRef.current === requestId) {
+ // One key per preview: every Confirm of this preview replays the same operation, and a later preview
+ // (mode switch, retry) starts clean instead of colliding with a key the server already settled.
+ setDialog((current) => (current ? { ...current, idempotencyKey: createIdempotencyKey(), preview } : current));
+ }
+ } catch (error) {
+ if (requestRef.current === requestId && isAccountScopeCurrent(owner)) {
+ setDialog((current) =>
+ current
+ ? { ...current, previewError: getApiErrorMessage(error, t('intermediates.dialog.previewFailed')) }
+ : current
+ );
+ }
+ }
+ },
+ [params, selection, t]
+ );
+
+ const open = useCallback(
+ (scope: IntermediatesScope, trigger: HTMLElement | null) => {
+ triggerRef.current = trigger;
+ scopeRef.current = scope;
+ setDialog(null);
+ void loadPreview('safe', scope);
+ },
+ [loadPreview]
+ );
+ const close = useCallback(() => {
+ requestRef.current += 1;
+ // Walking away from a failed start must not let a later visit replay it.
+ clearPendingIntermediatesStart();
+ setDialog(null);
+ }, []);
+ const retryPreview = useCallback(() => {
+ if (dialog && scopeRef.current) {
+ void loadPreview(dialog.mode, scopeRef.current);
+ }
+ }, [dialog, loadPreview]);
+ const changeMode = useCallback(
+ (mode: IntermediatesCleanupMode) => {
+ if (scopeRef.current) {
+ void loadPreview(mode, scopeRef.current);
+ }
+ },
+ [loadPreview]
+ );
+ const confirm = useCallback(async () => {
+ const preview = dialog?.preview ?? null;
+ if (!dialog || !preview) {
+ return;
+ }
+ const owner = captureAccountScope();
+ const start = { idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId };
+ recordPendingIntermediatesStart(start);
+ setDialog((current) => (current ? { ...current, isStarting: true, startError: null } : current));
+ try {
+ const operation = await startIntermediatesOperation(start, owner.signal);
+ assertAccountScopeCurrent(owner);
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ onStarted();
+ setDialog(null);
+ } catch (error) {
+ // Whatever settled it, this start is over; nothing may replay it, including after signing back in.
+ 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.
+ const previewGone = error instanceof ApiError && error.status === 404;
+ const timedOut = error instanceof DOMException && error.name === 'TimeoutError';
+ setDialog((current) =>
+ current
+ ? {
+ ...current,
+ isStarting: false,
+ preview: previewGone ? null : current.preview,
+ previewError: previewGone ? t('intermediates.dialog.previewExpired') : current.previewError,
+ startError: previewGone
+ ? null
+ : timedOut
+ ? t('intermediates.dialog.startTimedOut')
+ : getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
+ }
+ : current
+ );
+ }
+ }, [dialog, onStarted, queryClient, t]);
+
+ return { changeMode, close, confirm, open, retryPreview, state: dialog, triggerRef };
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
new file mode 100644
index 0000000000..2f1d180caa
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useFollowedOperation.ts
@@ -0,0 +1,147 @@
+import type { IntermediatesOperation } from '@features/intermediates/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type { RefObject } from 'react';
+
+import {
+ getIntermediatesOperation,
+ retryIntermediatesOperation,
+ startIntermediatesOperation,
+} from '@features/intermediates/data/api';
+import { intermediatesKeys } from '@features/intermediates/data/keys';
+import {
+ activeOperationStore,
+ clearPendingIntermediatesStart,
+ followIntermediatesOperation,
+ isPendingIntermediatesStartCurrent,
+ restoreIntermediatesReceipt,
+} from '@features/intermediates/data/operationStore';
+import { intermediatesOperationQueryOptions } from '@features/intermediates/data/queries';
+import { attachIntermediatesRealtime } from '@features/intermediates/data/realtime';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ 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';
+
+const getLatestRetry = async (operationId: string, signal: AbortSignal): Promise<IntermediatesOperation> => {
+ let operation = await getIntermediatesOperation(operationId, signal);
+ const visited = new Set<string>([operationId]);
+ while (operation.retriedByOperationId && !visited.has(operation.retriedByOperationId)) {
+ visited.add(operation.retriedByOperationId);
+ operation = await getIntermediatesOperation(operation.retriedByOperationId, signal);
+ }
+ return operation;
+};
+
+/**
+ * The operation the section follows, kept across visits. On mount it attaches realtime updates, replays a Confirm
+ * whose response was lost, and otherwise catches up with a retry started elsewhere.
+ */
+export const useFollowedOperation = ({ fallbackFocusRef }: { fallbackFocusRef: RefObject<HTMLElement | null> }) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const operationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
+ const [retryError, setRetryError] = useState<string | null>(null);
+ const [recoveryError, setRecoveryError] = useState<string | null>(null);
+ const [isRetrying, setIsRetrying] = useState(false);
+ const query = useQuery({ ...intermediatesOperationQueryOptions(operationId ?? ''), enabled: operationId !== null });
+
+ const follow = useCallback(
+ (owner: AccountScope, operation: IntermediatesOperation) => {
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ },
+ [queryClient]
+ );
+
+ useMountEffect(() => {
+ let mounted = true;
+ const detach = attachIntermediatesRealtime(queryClient);
+ const owner = captureAccountScope();
+ const pending = restoreIntermediatesReceipt();
+ if (pending) {
+ void startIntermediatesOperation(pending, owner.signal)
+ .then((operation) => {
+ if (isAccountScopeCurrent(owner) && isPendingIntermediatesStartCurrent(pending)) {
+ follow(owner, operation);
+ }
+ })
+ .catch((error: unknown) => {
+ if (isPendingIntermediatesStartCurrent(pending, owner)) {
+ clearPendingIntermediatesStart(owner);
+ if (mounted && isAccountScopeCurrent(owner)) {
+ setRecoveryError(getApiErrorMessage(error, t('intermediates.dialog.startFailed')));
+ }
+ }
+ });
+ } else {
+ const followed = activeOperationStore.getSnapshot().operationId;
+ if (followed) {
+ void getLatestRetry(followed, owner.signal)
+ .then((operation) => {
+ if (
+ isAccountScopeCurrent(owner) &&
+ activeOperationStore.getSnapshot().operationId === followed &&
+ operation.operationId !== followed
+ ) {
+ follow(owner, operation);
+ }
+ })
+ .catch(() => undefined); // The operation query reports lookup failures in the panel.
+ }
+ }
+ return () => {
+ mounted = false;
+ detach();
+ };
+ });
+
+ const retry = useCallback(async () => {
+ if (!operationId) {
+ return;
+ }
+ const owner = captureAccountScope();
+ setIsRetrying(true);
+ setRetryError(null);
+ try {
+ const operation = await retryIntermediatesOperation(operationId, owner.signal);
+ assertAccountScopeCurrent(owner);
+ follow(owner, operation);
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ try {
+ const latest = await getLatestRetry(operationId, owner.signal);
+ if (
+ latest.operationId !== operationId &&
+ isAccountScopeCurrent(owner) &&
+ activeOperationStore.getSnapshot().operationId === operationId
+ ) {
+ follow(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);
+ }
+ }
+ }, [follow, operationId, 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, retry, retryError };
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
new file mode 100644
index 0000000000..2f7e5ff7df
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/useIntermediatesSelection.ts
@@ -0,0 +1,97 @@
+import type { IntermediatesRow, IntermediatesSummary } from '@features/intermediates/core/types';
+import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
+
+import {
+ EMPTY_SELECTION,
+ selectAllMatching,
+ summarizeSelection,
+ toggleRowSelection,
+ 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.
+ */
+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 focused project is queried directly, so pagination cannot hide the entry point's selection.
+ const [pendingProjectId, setPendingProjectId] = useState<string | null>(initialProjectId);
+ const totals = summary?.totals;
+ const focusedRow = pendingProjectId ? rows.find((row) => row.projectId === pendingProjectId) : undefined;
+ 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]
+ );
+ 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 reset = useCallback(() => {
+ setPendingProjectId(null);
+ setSelection(EMPTY_SELECTION);
+ }, []);
+ const toggleRow = useCallback(
+ (row: IntermediatesRow) => {
+ setPendingProjectId(null);
+ setSelection(toggleRowSelection(effectiveSelection, row));
+ },
+ [effectiveSelection]
+ );
+ // Select all selects every matching row, including pages not loaded; only a complete selection clears.
+ const toggleAll = useCallback(() => {
+ setPendingProjectId(null);
+ setSelection(isComplete ? EMPTY_SELECTION : selectAllMatching());
+ }, [isComplete]);
+
+ 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),
+ focusedRow,
+ hasSelection,
+ reset,
+ selectionState: hasSelection ? (isComplete ? ('all' as const) : ('some' as const)) : ('none' as const),
+ selectionSummary,
+ toggleAll,
+ toggleRow,
+ };
+};