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(ui): extract useScopedAction for account-scoped mutations

Josh Corbett4c4554aca87f
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx
index 4f999a53af..b792b9d40c 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx
@@ -6,11 +6,8 @@ import { createListCollection, Grid, HStack, Icon, NumberInput, Stack, Switch, T
import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/models/core/schemas';
import { updateModel } from '@features/models/data/api';
import { replaceModelInStore } from '@features/models/data/modelsStore';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { Button, Combobox, FieldLabel, Panel, Select } from '@platform/ui';
import { MoveHorizontalIcon } from 'lucide-react';
import { useMemo, useState, type ReactNode } from 'react';
@@ -345,7 +342,7 @@ export const DefaultSettingsSection = ({
source: model.default_settings,
}));
const [error, setError] = useState<string | null>(null);
- const [isSaving, setIsSaving] = useState(false);
+ const { isBusy: isSaving, run } = useScopedAction();
const isDraftCurrent = draft.modelKey === model.key && draft.source === model.default_settings;
const savedSettingsDraft = useMemo(() => ({ ...model.default_settings }), [model.default_settings]);
const settings = isDraftCurrent ? draft.settings : savedSettingsDraft;
@@ -368,7 +365,6 @@ export const DefaultSettingsSection = ({
};
const handleSave = async () => {
- const owner = captureAccountScope();
const validationError = validateDefaults(model, settings, t);
if (validationError) {
@@ -376,25 +372,17 @@ export const DefaultSettingsSection = ({
return;
}
- setIsSaving(true);
-
- try {
- const updated = await updateModel(model.key, { default_settings: settings }, owner.signal);
-
- assertAccountScopeCurrent(owner);
- replaceModelInStore(updated);
- onSaved();
- } catch (saveError) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- onError(saveError instanceof Error ? saveError.message : t('models.failedToSaveDefaults'));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsSaving(false);
- }
- }
+ await run(
+ async (owner) => {
+ const updated = await updateModel(model.key, { default_settings: settings }, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
+ onSaved();
+ },
+ (_message, saveError) =>
+ onError(saveError instanceof Error ? saveError.message : t('models.failedToSaveDefaults'))
+ );
};
return (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
index bf7dd7ddd3..375ccf2384 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
@@ -4,11 +4,8 @@ import type { ModelConfig } from '@features/models/core/types';
import { Box, Flex, Icon, Image, Stack, Text } from '@chakra-ui/react';
import { deleteModelImage, getModelImageUrl, updateModelImage } from '@features/models/data/api';
import { markCoverImageChanged, useModelsSelector } from '@features/models/data/modelsStore';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { DropZone, IconButton, Tooltip } from '@platform/ui';
import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';
import { useRef, useState, type DragEvent } from 'react';
@@ -39,8 +36,9 @@ const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploa
const dragDepthRef = useRef(0);
const imageVersion = useModelsSelector((snapshot) => snapshot.coverImageVersions[model.key]);
const [hasImage, setHasImage] = useState(Boolean(model.cover_image));
- const [isBusy, setIsBusy] = useState(false);
const [isDropActive, setIsDropActive] = useState(false);
+ // Upload and delete share one busy flag: the tile hosts one action at a time.
+ const { isBusy, run } = useScopedAction();
const handleFile = async (file: File | undefined) => {
if (!file) {
@@ -52,56 +50,36 @@ const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploa
return;
}
- const owner = captureAccountScope();
const modelKey = model.key;
- setIsBusy(true);
-
- try {
- await updateModelImage(modelKey, file, owner.signal);
-
- assertAccountScopeCurrent(owner);
- setHasImage(true);
- // Bumps the cache-bust version so this tile and list thumbnails reload.
- markCoverImageChanged(modelKey, true);
- onUpdated();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- onError(error instanceof Error ? error.message : t('models.failedToUploadModelImage'));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsBusy(false);
- }
- }
+ await run(
+ async (owner) => {
+ await updateModelImage(modelKey, file, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ setHasImage(true);
+ // Bumps the cache-bust version so this tile and list thumbnails reload.
+ markCoverImageChanged(modelKey, true);
+ onUpdated();
+ },
+ (_message, error) => onError(error instanceof Error ? error.message : t('models.failedToUploadModelImage'))
+ );
};
const handleDelete = async () => {
- const owner = captureAccountScope();
const modelKey = model.key;
- setIsBusy(true);
-
- try {
- await deleteModelImage(modelKey, owner.signal);
-
- assertAccountScopeCurrent(owner);
- setHasImage(false);
- markCoverImageChanged(modelKey, false);
- onUpdated();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- onError(error instanceof Error ? error.message : t('models.failedToRemoveModelImage'));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsBusy(false);
- }
- }
+ await run(
+ async (owner) => {
+ await deleteModelImage(modelKey, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ setHasImage(false);
+ markCoverImageChanged(modelKey, false);
+ onUpdated();
+ },
+ (_message, error) => onError(error instanceof Error ? error.message : t('models.failedToRemoveModelImage'))
+ );
};
return (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx
index dacd056e6a..4abd72579e 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx
@@ -3,12 +3,8 @@ import { HStack, Icon, Input, Tag, Text, Wrap } from '@chakra-ui/react';
import { triggerPhraseSchema } from '@features/models/core/schemas';
import { updateModel } from '@features/models/data/api';
import { replaceModelInStore } from '@features/models/data/modelsStore';
-import {
- type AccountScope,
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { Button, Field } from '@platform/ui';
import { PlusIcon } from 'lucide-react';
import { memo, useState } from 'react';
@@ -45,8 +41,11 @@ export const TriggerPhrasesEditor = ({
const draft = isEditorCurrent ? editor.draft : '';
const error = isEditorCurrent ? editor.error : null;
const isSaving = isEditorCurrent ? editor.isSaving : false;
+ // The saving flag lives in the modelKey-scoped editor state (so it resets on
+ // model switch); the hook's own isBusy is unused, only its scope plumbing.
+ const { run } = useScopedAction();
- const persist = async (nextPhrases: string[], owner: AccountScope = captureAccountScope()): Promise<boolean> => {
+ const persist = async (nextPhrases: string[]): Promise<boolean> => {
setEditor((current) => ({
draft: current.modelKey === modelKey ? current.draft : '',
error: current.modelKey === modelKey ? current.error : null,
@@ -54,25 +53,26 @@ export const TriggerPhrasesEditor = ({
modelKey,
}));
- try {
- const updated = await updateModel(modelKey, { trigger_phrases: nextPhrases }, owner.signal);
+ const stopSaving = () =>
+ setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));
+ let saved = false;
- assertAccountScopeCurrent(owner);
- replaceModelInStore(updated);
- return true;
- } catch (persistError) {
- if (!isAccountScopeCurrent(owner)) {
- return false;
- }
-
- onError(persistError instanceof Error ? persistError.message : t('models.failedToUpdateTriggerPhrases'));
+ await run(
+ async (owner) => {
+ const updated = await updateModel(modelKey, { trigger_phrases: nextPhrases }, owner.signal);
- return false;
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
+ saved = true;
+ stopSaving();
+ },
+ (_message, persistError) => {
+ onError(persistError instanceof Error ? persistError.message : t('models.failedToUpdateTriggerPhrases'));
+ stopSaving();
}
- }
+ );
+
+ return saved;
};
const addPhrase = async () => {
@@ -96,9 +96,7 @@ export const TriggerPhrasesEditor = ({
setEditor({ draft, error: null, isSaving, modelKey });
// Clear the draft only once it is saved, so a failure never eats the text.
- const owner = captureAccountScope();
-
- if ((await persist([...phrases, parsed.data], owner)) && isAccountScopeCurrent(owner)) {
+ if (await persist([...phrases, parsed.data])) {
setEditor((current) => (current.modelKey === modelKey ? { ...current, draft: '' } : current));
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx
index 474bf230a6..5e17cbc18c 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx
@@ -3,13 +3,10 @@ import type { ModelConfig } from '@features/models/core/types';
import { Stack, Switch, Text } from '@chakra-ui/react';
import { updateModel } from '@features/models/data/api';
import { patchModelInStore, replaceModelInStore } from '@features/models/data/modelsStore';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
-import { useCallback, useState } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
export type VaeCpuOnlyModel = Pick<ModelConfig, 'cpu_only' | 'key' | 'name'>;
@@ -27,7 +24,7 @@ export const VaeCpuOnlySetting = ({
onSaved: () => void;
}) => {
const { t } = useTranslation();
- const [isPending, setIsPending] = useState(false);
+ const { isBusy: isPending, run } = useScopedAction();
const handleCheckedChange = useCallback(
async (details: { checked: boolean }) => {
@@ -35,33 +32,26 @@ export const VaeCpuOnlySetting = ({
return;
}
- const owner = captureAccountScope();
const previousCpuOnly = model.cpu_only;
const cpuOnly = details.checked ? true : null;
- setIsPending(true);
patchModelInStore(model.key, { cpu_only: cpuOnly });
- try {
- const updated = await updateModel(model.key, { cpu_only: cpuOnly }, owner.signal);
+ await run(
+ async (owner) => {
+ const updated = await updateModel(model.key, { cpu_only: cpuOnly }, owner.signal);
- assertAccountScopeCurrent(owner);
- replaceModelInStore(updated);
- onSaved();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
+ onSaved();
+ },
+ (_message, error) => {
+ patchModelInStore(model.key, { cpu_only: previousCpuOnly });
+ onError(getApiErrorMessage(error, t('models.failedToSaveVaeCpuSetting')));
}
-
- patchModelInStore(model.key, { cpu_only: previousCpuOnly });
- onError(getApiErrorMessage(error, t('models.failedToSaveVaeCpuSetting')));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsPending(false);
- }
- }
+ );
},
- [isPending, model.cpu_only, model.key, onError, onSaved, t]
+ [isPending, model.cpu_only, model.key, onError, onSaved, run, t]
);
return (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
index 3e16d06319..f726afd045 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
@@ -3,13 +3,10 @@ import type { ModelConfig } from '@features/models/core/types';
import { convertModelToDiffusers, deleteModel, reidentifyModel } from '@features/models/data/api';
import { removeModelsFromStore, replaceModelInStore } from '@features/models/data/modelsStore';
import { removeModelsFromRelationships } from '@features/models/data/relationshipsStore';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
import { pruneModelsUiKeys } from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { useCallback } from 'react';
/**
@@ -21,70 +18,55 @@ type ModelActionTarget = Pick<ModelConfig, 'key' | 'name'>;
export const useModelActions = () => {
const notify = useNotify();
+ // None of these actions surface a busy flag, so one shared instance's `run`
+ // covers all three and its isBusy is simply ignored.
+ const { run } = useScopedAction();
const remove = useCallback(
- async (model: ModelActionTarget) => {
- const owner = captureAccountScope();
-
- try {
- await deleteModel(model.key, owner.signal);
-
- assertAccountScopeCurrent(owner);
- removeModelsFromStore([model.key]);
- removeModelsFromRelationships([model.key]);
- pruneModelsUiKeys([model.key]);
- notify.success('Model deleted', model.name);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error('Delete failed', error instanceof Error ? error.message : String(error));
- }
- },
- [notify]
+ (model: ModelActionTarget) =>
+ run(
+ async (owner) => {
+ await deleteModel(model.key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ removeModelsFromStore([model.key]);
+ removeModelsFromRelationships([model.key]);
+ pruneModelsUiKeys([model.key]);
+ notify.success('Model deleted', model.name);
+ },
+ (message) => notify.error('Delete failed', message)
+ ),
+ [notify, run]
);
const convert = useCallback(
- async (model: ModelActionTarget) => {
- const owner = captureAccountScope();
-
- try {
- const converted = await convertModelToDiffusers(model.key, owner.signal);
-
- assertAccountScopeCurrent(owner);
- replaceModelInStore(converted);
- notify.success('Converted to diffusers', model.name);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error('Conversion failed', error instanceof Error ? error.message : String(error));
- }
- },
- [notify]
+ (model: ModelActionTarget) =>
+ run(
+ async (owner) => {
+ const converted = await convertModelToDiffusers(model.key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(converted);
+ notify.success('Converted to diffusers', model.name);
+ },
+ (message) => notify.error('Conversion failed', message)
+ ),
+ [notify, run]
);
const reidentify = useCallback(
- async (model: ModelActionTarget) => {
- const owner = captureAccountScope();
-
- try {
- const identified = await reidentifyModel(model.key, owner.signal);
-
- assertAccountScopeCurrent(owner);
- replaceModelInStore(identified);
- notify.success('Model re-identified', model.name);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error('Re-identify failed', error instanceof Error ? error.message : String(error));
- }
- },
- [notify]
+ (model: ModelActionTarget) =>
+ run(
+ async (owner) => {
+ const identified = await reidentifyModel(model.key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(identified);
+ notify.success('Model re-identified', model.name);
+ },
+ (message) => notify.error('Re-identify failed', message)
+ ),
+ [notify, run]
);
return { convert, reidentify, remove };
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
index 7d48be3453..7ddccfde3e 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx
@@ -11,15 +11,11 @@ import {
resumeModelInstall,
} from '@features/models/data/api';
import { isActiveInstallStatus, refreshInstalls, replaceInstallJob } from '@features/models/data/installsStore';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { useConnectionStatusSelector } from '@platform/transport/connectionStore';
import { IconButton, Tooltip } from '@platform/ui';
import { PauseIcon, PlayIcon, RotateCcwIcon, TriangleAlertIcon, XIcon } from 'lucide-react';
-import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { InstallJobProgress } from './InstallJobProgress';
@@ -36,7 +32,7 @@ export const InstallJobRow = ({
onError: (title: string, message: string) => void;
}) => {
const { t } = useTranslation();
- const [isActing, setIsActing] = useState(false);
+ const { isBusy: isActing, run } = useScopedAction();
const connectionStatus = useConnectionStatusSelector((snapshot) => snapshot.status);
const badge = STATUS_BADGES[job.status] ?? { label: job.status, palette: 'gray' };
const sourceLabel = getInstallSourceLabel(job.source);
@@ -47,32 +43,20 @@ export const InstallJobRow = ({
);
const showDisconnected = connectionStatus !== 'connected' && isActiveInstallStatus(job.status);
- const runAction = async (action: (signal: AbortSignal) => Promise<unknown>, failureTitle: string) => {
- const owner = captureAccountScope();
-
- setIsActing(true);
-
- try {
- const result = await action(owner.signal);
-
- assertAccountScopeCurrent(owner);
- if (result && typeof result === 'object' && 'id' in (result as ModelInstallJob)) {
- replaceInstallJob(result as ModelInstallJob);
- } else {
- await refreshInstalls(owner);
- }
- } catch (actionError) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ const runAction = (action: (signal: AbortSignal) => Promise<unknown>, failureTitle: string) =>
+ run(
+ async (owner) => {
+ const result = await action(owner.signal);
- onError(failureTitle, actionError instanceof Error ? actionError.message : String(actionError));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsActing(false);
- }
- }
- };
+ assertAccountScopeCurrent(owner);
+ if (result && typeof result === 'object' && 'id' in (result as ModelInstallJob)) {
+ replaceInstallJob(result as ModelInstallJob);
+ } else {
+ await refreshInstalls(owner);
+ }
+ },
+ (message) => onError(failureTitle, message)
+ );
return (
<Stack
diff --git a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
index 133fd06fdc..abddb04e2d 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx
@@ -13,17 +13,14 @@ import {
refreshInstalls,
useInstallsSelector,
} from '@features/models/data/installsStore';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
import { setQueueExpanded, useModelsUiSelector } from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { useMountEffect } from '@platform/react/useMountEffect';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { Button, IconButton, Tooltip } from '@platform/ui';
import { ChevronUpIcon, ListOrderedIcon, PauseIcon, PlayIcon, RefreshCcwIcon, Trash2Icon, XIcon } from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { InstallQueueList } from './InstallQueueList';
@@ -54,77 +51,62 @@ export const InstallQueueBar = () => {
);
const settledCount = jobs.filter((job) => !isActiveInstallStatus(job.status) && job.status !== 'paused').length;
- const [busyAction, setBusyAction] = useState<'pause' | 'resume' | 'cancel' | 'prune' | 'refresh' | null>(null);
+ // One busy flag per queue-wide control so each button tracks its own action.
+ const { isBusy: isPausingAll, run: runPauseAll } = useScopedAction();
+ const { isBusy: isResumingAll, run: runResumeAll } = useScopedAction();
+ const { isBusy: isCancellingAll, run: runCancelAll } = useScopedAction();
+ const { isBusy: isPruning, run: runPrune } = useScopedAction();
+ const { isBusy: isRefreshing, run: runRefresh } = useScopedAction();
const runBulk = useCallback(
- async (action: 'pause' | 'resume' | 'cancel', targets: ModelInstallJob[]) => {
- const call =
- action === 'pause' ? pauseModelInstall : action === 'resume' ? resumeModelInstall : cancelModelInstall;
- const owner = captureAccountScope();
-
- setBusyAction(action);
-
- try {
- await Promise.all(targets.map((job) => call(job.id, owner.signal)));
- assertAccountScopeCurrent(owner);
- await refreshInstalls(owner);
- assertAccountScopeCurrent(owner);
- } catch (bulkError) {
- if (!isAccountScopeCurrent(owner)) {
- return;
+ (
+ run: ReturnType<typeof useScopedAction>['run'],
+ call: (id: ModelInstallJob['id'], signal: AbortSignal) => Promise<unknown>,
+ targets: ModelInstallJob[]
+ ) =>
+ run(
+ async (owner) => {
+ await Promise.all(targets.map((job) => call(job.id, owner.signal)));
+ assertAccountScopeCurrent(owner);
+ await refreshInstalls(owner);
+ assertAccountScopeCurrent(owner);
+ },
+ (message) => {
+ notify.error(t('models.queueActionFailed'), message);
+ void refreshInstalls();
}
-
- notify.error(t('models.queueActionFailed'), bulkError instanceof Error ? bulkError.message : String(bulkError));
- void refreshInstalls(owner);
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setBusyAction(null);
- }
- }
- },
+ ),
[notify, t]
);
- const handlePrune = useCallback(async () => {
- const owner = captureAccountScope();
-
- setBusyAction('prune');
-
- try {
- await pruneCompletedModelInstalls(owner.signal);
- assertAccountScopeCurrent(owner);
- await refreshInstalls(owner);
- assertAccountScopeCurrent(owner);
- } catch (pruneError) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error(t('models.pruneFailed'), pruneError instanceof Error ? pruneError.message : String(pruneError));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setBusyAction(null);
- }
- }
- }, [notify, t]);
-
- const handleRefresh = useCallback(async () => {
- const owner = captureAccountScope();
-
- setBusyAction('refresh');
+ const handlePrune = useCallback(
+ () =>
+ runPrune(
+ async (owner) => {
+ await pruneCompletedModelInstalls(owner.signal);
+ assertAccountScopeCurrent(owner);
+ await refreshInstalls(owner);
+ assertAccountScopeCurrent(owner);
+ },
+ (message) => notify.error(t('models.pruneFailed'), message)
+ ),
+ [notify, runPrune, t]
+ );
- try {
- await refreshInstalls(owner);
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setBusyAction(null);
- }
- }
- }, []);
+ const handleRefresh = useCallback(() => runRefresh((owner) => refreshInstalls(owner)), [runRefresh]);
const handleOpenChange = useCallback((event: { open: boolean }) => setQueueExpanded(event.open), []);
- const handlePauseAll = useCallback(() => void runBulk('pause', pausableJobs), [pausableJobs, runBulk]);
- const handleResumeAll = useCallback(() => void runBulk('resume', pausedJobs), [pausedJobs, runBulk]);
- const handleCancelAll = useCallback(() => void runBulk('cancel', cancellableJobs), [cancellableJobs, runBulk]);
+ const handlePauseAll = useCallback(
+ () => void runBulk(runPauseAll, pauseModelInstall, pausableJobs),
+ [pausableJobs, runBulk, runPauseAll]
+ );
+ const handleResumeAll = useCallback(
+ () => void runBulk(runResumeAll, resumeModelInstall, pausedJobs),
+ [pausedJobs, runBulk, runResumeAll]
+ );
+ const handleCancelAll = useCallback(
+ () => void runBulk(runCancelAll, cancelModelInstall, cancellableJobs),
+ [cancellableJobs, runBulk, runCancelAll]
+ );
const summary =
activeJobs.length > 0
@@ -149,13 +131,13 @@ export const InstallQueueBar = () => {
{t('models.installQueue')}
</Text>
<HStack gap="1">
- <Button loading={busyAction === 'refresh'} size="2xs" variant="ghost" onClick={handleRefresh}>
+ <Button loading={isRefreshing} size="2xs" variant="ghost" onClick={handleRefresh}>
<Icon as={RefreshCcwIcon} boxSize="3" />
{t('common.refresh')}
</Button>
<Button
disabled={settledCount === 0}
- loading={busyAction === 'prune'}
+ loading={isPruning}
size="2xs"
variant="ghost"
onClick={handlePrune}
@@ -207,7 +189,7 @@ export const InstallQueueBar = () => {
<Tooltip content={t('models.pauseAllDownloads')}>
<IconButton
aria-label={t('models.pauseAllInstalls')}
- loading={busyAction === 'pause'}
+ loading={isPausingAll}
size="2xs"
variant="ghost"
onClick={handlePauseAll}
@@ -220,7 +202,7 @@ export const InstallQueueBar = () => {
<Tooltip content={t('models.resumeAllPausedDownloads')}>
<IconButton
aria-label={t('models.resumeAllInstalls')}
- loading={busyAction === 'resume'}
+ loading={isResumingAll}
size="2xs"
variant="ghost"
onClick={handleResumeAll}
@@ -233,7 +215,7 @@ export const InstallQueueBar = () => {
<Tooltip content={t('models.cancelAllInstalls')}>
<IconButton
aria-label={t('models.cancelAllInstalls')}
- loading={busyAction === 'cancel'}
+ loading={isCancellingAll}
size="2xs"
variant="ghost"
onClick={handleCancelAll}
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
index d9299f87cf..814ffb6da5 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
@@ -5,6 +5,7 @@ import { Checkbox, Dialog, Flex, Icon, Menu, Portal, Spinner, Stack, Text } from
import { formatBytes } from '@features/models/core/taxonomy';
import { deleteOrphanedModels, emptyModelCache, getOrphanedModels } from '@features/models/data/api';
import { refreshModels } from '@features/models/data/modelsStore';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
@@ -25,23 +26,18 @@ export const MaintenanceMenu = () => {
const { t } = useTranslation();
const notify = useNotify();
const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false);
+ const { run } = useScopedAction();
- const handleEmptyCache = async () => {
- const owner = captureAccountScope();
-
- try {
- await emptyModelCache(owner.signal);
-
- assertAccountScopeCurrent(owner);
- notify.success(t('models.cacheEmptied'));
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ const handleEmptyCache = () =>
+ run(
+ async (owner) => {
+ await emptyModelCache(owner.signal);
- notify.error(t('models.failedToEmptyCache'), error instanceof Error ? error.message : String(error));
- }
- };
+ assertAccountScopeCurrent(owner);
+ notify.success(t('models.cacheEmptied'));
+ },
+ (message) => notify.error(t('models.failedToEmptyCache'), message)
+ );
const handleRefresh = () => {
const owner = captureAccountScope();
@@ -88,7 +84,7 @@ const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
const [loadError, setLoadError] = useState<string | null>(null);
// Nothing pre-selected: deleting files on disk must be an explicit choice.
const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string>>(new Set());
- const [isDeleting, setIsDeleting] = useState(false);
+ const { isBusy: isDeleting, run } = useScopedAction();
useMountEffect(() => {
const owner = captureAccountScope();
@@ -125,47 +121,35 @@ const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
});
};
- const handleDelete = async () => {
- const owner = captureAccountScope();
-
- setIsDeleting(true);
-
- try {
- const result = await deleteOrphanedModels([...selectedPaths], owner.signal);
+ const handleDelete = () =>
+ run(
+ async (owner) => {
+ const result = await deleteOrphanedModels([...selectedPaths], owner.signal);
- assertAccountScopeCurrent(owner);
- const errorCount = Object.keys(result.errors).length;
+ assertAccountScopeCurrent(owner);
+ const errorCount = Object.keys(result.errors).length;
- if (errorCount > 0) {
- notify.error(
- t('models.orphanedCleanup'),
- t('models.orphanedCleanupPartialDescription', {
- deleted: result.deleted.length,
- error: Object.values(result.errors)[0],
- failed: errorCount,
- })
- );
- } else {
- notify.success(
- t('models.orphanedCleanup'),
- t('models.orphanedDeletedDescription', { count: result.deleted.length })
- );
- }
-
- void refreshModels(owner);
- onClose();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ if (errorCount > 0) {
+ notify.error(
+ t('models.orphanedCleanup'),
+ t('models.orphanedCleanupPartialDescription', {
+ deleted: result.deleted.length,
+ error: Object.values(result.errors)[0],
+ failed: errorCount,
+ })
+ );
+ } else {
+ notify.success(
+ t('models.orphanedCleanup'),
+ t('models.orphanedDeletedDescription', { count: result.deleted.length })
+ );
+ }
- notify.error(t('models.orphanedCleanupFailed'), error instanceof Error ? error.message : String(error));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsDeleting(false);
- }
- }
- };
+ void refreshModels(owner);
+ onClose();
+ },
+ (message) => notify.error(t('models.orphanedCleanupFailed'), message)
+ );
const totalSelectedBytes =
orphans?.filter((orphan) => selectedPaths.has(orphan.path)).reduce((sum, orphan) => sum + orphan.size_bytes, 0) ??
diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
index 234b5765e3..327ad7a081 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
@@ -7,6 +7,7 @@ import { removeModelsFromRelationships } from '@features/models/data/relationshi
import { MaintenanceMenu } from '@features/models/ui/library/MaintenanceMenu';
import { ModelFilterBar } from '@features/models/ui/library/ModelFilterBar';
import { ModelLibraryList } from '@features/models/ui/library/ModelLibraryList';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
import {
openModelDetail,
pruneModelsUiKeys,
@@ -15,11 +16,7 @@ import {
useModelsUiSelector,
} from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { Button, IconButton, ConfirmDialog } from '@platform/ui';
import { Trash2Icon, XIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
@@ -45,6 +42,7 @@ export const LibraryColumn = () => {
left.selectedKeys === right.selectedKeys
);
const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);
+ const { run } = useScopedAction();
const availableTypes = useMemo(() => collectTypes(models), [models]);
const availableBases = useMemo(() => collectBases(models), [models]);
@@ -52,38 +50,38 @@ export const LibraryColumn = () => {
const handleToggleSelected = useCallback((modelKey: string) => toggleModelSelection(modelKey), []);
const handleBulkDelete = async () => {
- const owner = captureAccountScope();
const keys = [...selectedKeys];
- try {
- const result = await bulkDeleteModels(keys, owner.signal);
+ await run(
+ async (owner) => {
+ const result = await bulkDeleteModels(keys, owner.signal);
- assertAccountScopeCurrent(owner);
- removeModelsFromStore(result.deleted);
- removeModelsFromRelationships(result.deleted);
- pruneModelsUiKeys(result.deleted);
- updateModelsUi({ selectedKeys: new Set(result.failed.map((failure) => failure.key)) });
+ assertAccountScopeCurrent(owner);
+ removeModelsFromStore(result.deleted);
+ removeModelsFromRelationships(result.deleted);
+ pruneModelsUiKeys(result.deleted);
+ updateModelsUi({ selectedKeys: new Set(result.failed.map((failure) => failure.key)) });
- if (result.failed.length > 0) {
- notify.error(
- t('models.someCouldNotBeDeleted'),
- t('models.bulkDeletePartialDescription', {
- deleted: result.deleted.length,
- error: result.failed[0]?.error ?? '',
- failed: result.failed.length,
- })
- );
- } else {
- notify.success(t('models.deleted'), t('models.deletedDescription', { count: result.deleted.length }));
- }
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
+ if (result.failed.length > 0) {
+ notify.error(
+ t('models.someCouldNotBeDeleted'),
+ t('models.bulkDeletePartialDescription', {
+ deleted: result.deleted.length,
+ error: result.failed[0]?.error ?? '',
+ failed: result.failed.length,
+ })
+ );
+ } else {
+ notify.success(t('models.deleted'), t('models.deletedDescription', { count: result.deleted.length }));
+ }
+ },
+ (message) => {
+ notify.error(t('models.bulkDeleteFailed'), message);
+ // The scope is current when onError runs, so the default capture inside
+ // refreshModels targets the same account the failed call did.
+ void refreshModels();
}
-
- notify.error(t('models.bulkDeleteFailed'), error instanceof Error ? error.message : String(error));
- void refreshModels(owner);
- }
+ );
};
return (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts
new file mode 100644
index 0000000000..98c16a137a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts
@@ -0,0 +1,44 @@
+import { type AccountScope, captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { useCallback, useState } from 'react';
+
+export const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+/**
+ * Busy-tracked wrapper for account-scoped async UI actions. Owns the
+ * boilerplate every mutation handler otherwise repeats: capture the account
+ * scope, flip the busy flag, drop results that settle after an account
+ * switch, and route failures to the caller's error sink.
+ *
+ * The action still calls `assertAccountScopeCurrent(owner)` itself before
+ * patching stores on success — the throw lands here and is swallowed when the
+ * scope is gone.
+ */
+export const useScopedAction = () => {
+ const [isBusy, setIsBusy] = useState(false);
+
+ const run = useCallback(
+ async (
+ action: (owner: AccountScope) => Promise<void>,
+ onError?: (message: string, error: unknown) => void
+ ): Promise<void> => {
+ const owner = captureAccountScope();
+
+ setIsBusy(true);
+
+ try {
+ await action(owner);
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ onError?.(getErrorMessage(error), error);
+ }
+ } finally {
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
+ }
+ },
+ []
+ );
+
+ return { isBusy, run };
+};