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(ui): make scoped actions report success and block re-entry

joshistoast0ec359673787
diff --git a/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx
index e34d78528d..2761675a39 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx
@@ -113,7 +113,7 @@ const ExternalProviderKeyCard = ({
const runProviderAction = (
action: () => Promise<ExternalProviderConfig>,
onSuccess?: (next: ExternalProviderConfig, owner: AccountScope) => void
- ): Promise<void> =>
+ ): Promise<boolean> =>
run(
async (owner) => {
const nextConfig = await action();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
index a31e2189c3..d3c32e21d7 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
@@ -331,8 +331,9 @@ const ModelDetailActions = ({
title={t('models.deleteModel')}
onClose={() => setPendingAction(null)}
onConfirm={async () => {
- await remove(model);
- onDeleted();
+ if (await remove(model)) {
+ onDeleted();
+ }
}}
/>
{/* Destructive styling: the original checkpoint file is replaced. */}
@@ -342,7 +343,9 @@ const ModelDetailActions = ({
isOpen={pendingAction === 'convert'}
title={t('models.convertToDiffusers')}
onClose={() => setPendingAction(null)}
- onConfirm={() => convert(model)}
+ onConfirm={async () => {
+ await convert(model);
+ }}
/>
</HStack>
);
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 10c07d1778..7c35933b3d 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
@@ -20,13 +20,16 @@ type ModelActionTarget = Pick<ModelConfig, 'key' | 'name'>;
export const useModelActions = () => {
const { t } = useTranslation();
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();
+ // Separate instances: `run` ignores calls while its own action is in
+ // flight, so sharing one would let a slow convert swallow a remove.
+ // The busy flags stay unused.
+ const { run: runRemove } = useScopedAction();
+ const { run: runConvert } = useScopedAction();
+ const { run: runReidentify } = useScopedAction();
const remove = useCallback(
(model: ModelActionTarget) =>
- run(
+ runRemove(
async (owner) => {
await deleteModel(model.key, owner.signal);
@@ -38,12 +41,12 @@ export const useModelActions = () => {
},
(message) => notify.error(t('models.deleteFailed'), message)
),
- [notify, run, t]
+ [notify, runRemove, t]
);
const convert = useCallback(
(model: ModelActionTarget) =>
- run(
+ runConvert(
async (owner) => {
const converted = await convertModelToDiffusers(model.key, owner.signal);
@@ -53,12 +56,12 @@ export const useModelActions = () => {
},
(message) => notify.error(t('models.conversionFailed'), message)
),
- [notify, run, t]
+ [notify, runConvert, t]
);
const reidentify = useCallback(
(model: ModelActionTarget) =>
- run(
+ runReidentify(
async (owner) => {
const identified = await reidentifyModel(model.key, owner.signal);
@@ -68,7 +71,7 @@ export const useModelActions = () => {
},
(message) => notify.error(t('models.reidentifyFailed'), message)
),
- [notify, run, t]
+ [notify, runReidentify, t]
);
return { convert, reidentify, remove };
diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.browser.test.tsx
new file mode 100644
index 0000000000..fd079791a3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.browser.test.tsx
@@ -0,0 +1,169 @@
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+
+import { useScopedAction } from './useScopedAction';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const deferred = <T,>() => {
+ let reject!: (reason?: unknown) => void;
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+
+ return { promise, reject, resolve };
+};
+
+const Harness = ({
+ action,
+ onError,
+ onResult,
+}: {
+ action: (owner: AccountScope) => Promise<void>;
+ onError: (message: string, error: unknown) => void;
+ onResult: (result: Promise<boolean>) => void;
+}) => {
+ const { isBusy, run } = useScopedAction();
+
+ return (
+ <button
+ data-busy={isBusy}
+ type="button"
+ onClick={() => {
+ onResult(run(action, onError));
+ }}
+ >
+ run
+ </button>
+ );
+};
+
+describe('useScopedAction', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let action: Mock<(owner: AccountScope) => Promise<void>>;
+ let onError: Mock<(message: string, error: unknown) => void>;
+ let onResult: Mock<(result: Promise<boolean>) => void>;
+
+ const mount = async () => {
+ await act(() => {
+ root.render(<Harness action={action} onError={onError} onResult={onResult} />);
+ });
+ };
+
+ const button = () => host.querySelector<HTMLButtonElement>('button')!;
+
+ const click = async () => {
+ await act(async () => {
+ button().click();
+ await Promise.resolve();
+ });
+ };
+
+ const result = (index: number): Promise<boolean> => onResult.mock.calls[index]![0];
+
+ beforeEach(() => {
+ accountLifecycle.activate('scoped-action-test-a', ':user:scoped-action-test-a');
+ action = vi.fn();
+ onError = vi.fn();
+ onResult = vi.fn();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('resolves true on success and releases the busy flag', async () => {
+ const request = deferred<void>();
+ action.mockReturnValue(request.promise);
+ await mount();
+
+ await click();
+ expect(button().dataset.busy).toBe('true');
+
+ await act(async () => {
+ request.resolve();
+ await request.promise;
+ });
+
+ await expect(result(0)).resolves.toBe(true);
+ expect(button().dataset.busy).toBe('false');
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('resolves false and routes the failure to onError', async () => {
+ action.mockRejectedValue(new Error('save exploded'));
+ await mount();
+
+ await click();
+
+ await expect(result(0)).resolves.toBe(false);
+ expect(onError).toHaveBeenCalledWith('save exploded', expect.any(Error));
+ expect(button().dataset.busy).toBe('false');
+ });
+
+ it('ignores a second run while the first is in flight', async () => {
+ const request = deferred<void>();
+ action.mockReturnValue(request.promise);
+ await mount();
+
+ await click();
+ await click();
+
+ expect(action).toHaveBeenCalledTimes(1);
+ await expect(result(1)).resolves.toBe(false);
+
+ await act(async () => {
+ request.resolve();
+ await request.promise;
+ });
+
+ await expect(result(0)).resolves.toBe(true);
+ expect(button().dataset.busy).toBe('false');
+ });
+
+ it('resolves false without onError when the account changes before success settles', async () => {
+ const request = deferred<void>();
+ action.mockReturnValue(request.promise);
+ await mount();
+
+ await click();
+ accountLifecycle.activate('scoped-action-test-b', ':user:scoped-action-test-b');
+
+ await act(async () => {
+ request.resolve();
+ await request.promise;
+ });
+
+ await expect(result(0)).resolves.toBe(false);
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('does not report failures from a dead account scope', async () => {
+ const request = deferred<void>();
+ action.mockReturnValue(request.promise);
+ await mount();
+
+ await click();
+ accountLifecycle.activate('scoped-action-test-b', ':user:scoped-action-test-b');
+
+ await act(async () => {
+ request.reject(new Error('failed after switch'));
+ await request.promise.catch(() => undefined);
+ });
+
+ await expect(result(0)).resolves.toBe(false);
+ expect(onError).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts
index 98c16a137a..aac9b82b3e 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useScopedAction.ts
@@ -1,5 +1,5 @@
import { type AccountScope, captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
-import { useCallback, useState } from 'react';
+import { useCallback, useRef, useState } from 'react';
export const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
@@ -9,29 +9,44 @@ export const getErrorMessage = (error: unknown): string => (error instanceof Err
* scope, flip the busy flag, drop results that settle after an account
* switch, and route failures to the caller's error sink.
*
+ * `run` resolves `true` only when the action completed in the current account
+ * scope, so callers can gate follow-up UI (navigation, closing a pane) on
+ * success. While an action is in flight, further `run` calls resolve `false`
+ * without invoking their action — keyboard paths that bypass a button's
+ * `loading` state cannot double-submit.
+ *
* 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 isBusyRef = useRef(false);
const run = useCallback(
async (
action: (owner: AccountScope) => Promise<void>,
onError?: (message: string, error: unknown) => void
- ): Promise<void> => {
+ ): Promise<boolean> => {
+ if (isBusyRef.current) {
+ return false;
+ }
+
const owner = captureAccountScope();
+ isBusyRef.current = true;
setIsBusy(true);
try {
await action(owner);
+ return isAccountScopeCurrent(owner);
} catch (error) {
if (isAccountScopeCurrent(owner)) {
onError?.(getErrorMessage(error), error);
}
+ return false;
} finally {
+ isBusyRef.current = false;
if (isAccountScopeCurrent(owner)) {
setIsBusy(false);
}