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(identity): isolate account-lived state

joshistoaste334d498f556
diff --git a/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx
new file mode 100644
index 0000000000..db38acd7f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx
@@ -0,0 +1,272 @@
+import { RouterProvider } from '@tanstack/react-router';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const identityErrors = vi.hoisted(() => ({
+ AuthSessionUnavailableError: class AuthSessionUnavailableError extends Error {},
+}));
+
+const unavailableScreen = vi.hoisted(() => {
+ let retry: (() => Promise<void> | void) | null = null;
+
+ return {
+ getRetry: () => retry,
+ reset: () => {
+ retry = null;
+ },
+ setRetry: (nextRetry: () => Promise<void> | void) => {
+ retry = nextRetry;
+ },
+ };
+});
+
+type SessionSnapshot = {
+ accountEpoch: number;
+ multiuserEnabled: boolean;
+ phase: 'unavailable' | 'ready';
+ sessionExpired: boolean;
+ setupRequired: boolean;
+ strictPasswordChecking: boolean;
+ user: { user_id: string } | null;
+};
+
+const sessionStore = vi.hoisted(() => {
+ type Snapshot = {
+ accountEpoch: number;
+ multiuserEnabled: boolean;
+ phase: 'unavailable' | 'ready';
+ sessionExpired: boolean;
+ setupRequired: boolean;
+ strictPasswordChecking: boolean;
+ user: { user_id: string } | null;
+ };
+
+ let snapshot: Snapshot = {
+ accountEpoch: 0,
+ multiuserEnabled: true,
+ phase: 'ready',
+ sessionExpired: false,
+ setupRequired: false,
+ strictPasswordChecking: true,
+ user: { user_id: 'user-a' },
+ };
+ const listeners = new Set<() => void>();
+
+ return {
+ getSnapshot: () => snapshot,
+ reset: () => {
+ listeners.clear();
+ },
+ setSnapshot: (nextSnapshot: Snapshot) => {
+ snapshot = nextSnapshot;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+});
+
+vi.mock('@features/identity', async () => {
+ const React = await import('react');
+
+ return {
+ AuthSessionUnavailableError: identityErrors.AuthSessionUnavailableError,
+ AuthUnavailableScreen: ({ onRetry }: { onRetry: () => Promise<void> | void }) => {
+ unavailableScreen.setRetry(onRetry);
+
+ return React.createElement('div', { 'data-testid': 'auth-unavailable-screen' }, 'Auth unavailable');
+ },
+ ensureReadyAuthSession: () => {
+ const snapshot = sessionStore.getSnapshot();
+
+ return snapshot.phase === 'ready'
+ ? Promise.resolve(snapshot)
+ : Promise.reject(new identityErrors.AuthSessionUnavailableError());
+ },
+ getCapabilities: () => ({
+ canManageModels: true,
+ canManageNodes: true,
+ canManageUsers: true,
+ }),
+ LoginScreen: () => React.createElement('div', { 'data-testid': 'login-screen' }, 'Login'),
+ SetupScreen: () => React.createElement('div', null, 'Setup'),
+ useAuthSession: () =>
+ React.useSyncExternalStore(sessionStore.subscribe, sessionStore.getSnapshot, sessionStore.getSnapshot),
+ };
+});
+
+vi.mock('@workbench/components/WorkbenchSplashScreen', () => ({
+ WorkbenchSplashScreen: () => null,
+}));
+
+vi.mock('@workbench/launchpad/Launchpad', () => ({
+ Launchpad: () => null,
+}));
+
+vi.mock('@workbench/projects/session', () => ({
+ peekOpenProjectIds: () => Promise.resolve(null),
+}));
+
+vi.mock('@workbench/settings/store', () => ({
+ loadWorkbenchSettings: () => Promise.resolve(undefined),
+}));
+
+vi.mock('./SocketHubRuntime', async () => {
+ const React = await import('react');
+
+ return {
+ SocketHubRuntime: () =>
+ React.createElement('div', { 'data-testid': 'authenticated-runtime' }, 'Authenticated runtime'),
+ };
+});
+
+vi.mock('./WorkbenchApp', () => ({
+ WorkbenchApp: () => null,
+}));
+
+const AUTHENTICATED_PATHS = ['/', '/projects', '/models', '/nodes', '/users', '/app'] as const;
+
+const signedInSession = (accountEpoch: number): SessionSnapshot => ({
+ accountEpoch,
+ multiuserEnabled: true,
+ phase: 'ready',
+ sessionExpired: false,
+ setupRequired: false,
+ strictPasswordChecking: true,
+ user: { user_id: 'user-a' },
+});
+
+const signedOutSession = (accountEpoch: number): SessionSnapshot => ({
+ ...signedInSession(accountEpoch),
+ sessionExpired: true,
+ user: null,
+});
+
+const singleUserSession = (accountEpoch: number): SessionSnapshot => ({
+ ...signedInSession(accountEpoch),
+ multiuserEnabled: false,
+ user: null,
+});
+
+const unavailableSession = (accountEpoch: number): SessionSnapshot => ({
+ ...signedOutSession(accountEpoch),
+ multiuserEnabled: false,
+ phase: 'unavailable',
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ sessionStore.reset();
+ unavailableScreen.reset();
+});
+
+describe('authenticated route account lifecycle', () => {
+ it('never mounts authenticated runtime while auth mode is unavailable', async () => {
+ sessionStore.setSnapshot(unavailableSession(1));
+ const { router } = await import('./router');
+
+ await router.load();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(<RouterProvider router={router} />);
+ });
+
+ expect(host.querySelector('[data-testid="authenticated-runtime"]')).toBeNull();
+ expect(host.querySelector('[data-testid="login-screen"]')).toBeNull();
+ expect(host.querySelector('[data-testid="auth-unavailable-screen"]')).not.toBeNull();
+ const retry = unavailableScreen.getRetry();
+ expect(retry).not.toBeNull();
+
+ await act(async () => {
+ sessionStore.setSnapshot(signedInSession(2));
+ await retry?.();
+ });
+
+ await expect.poll(() => host?.querySelector('[data-testid="authenticated-runtime"]')).not.toBeNull();
+ expect(host.querySelector('[data-testid="auth-unavailable-screen"]')).toBeNull();
+ });
+
+ it('unmounts every authenticated route on multiuser sign-out and keeps every route mounted in single-user mode', async () => {
+ sessionStore.setSnapshot(signedInSession(1));
+ const { router } = await import('./router');
+
+ await router.load();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(<RouterProvider router={router} />);
+ });
+
+ const initialPath = router.state.location.pathname;
+ const initialRuntime = host.querySelector<HTMLElement>('[data-testid="authenticated-runtime"]');
+ expect(initialRuntime).not.toBeNull();
+
+ await act(() => {
+ sessionStore.setSnapshot(signedInSession(2));
+ });
+
+ const remountedRuntime = host.querySelector<HTMLElement>('[data-testid="authenticated-runtime"]');
+ expect(router.state.location.pathname).toBe(initialPath);
+ expect(initialRuntime?.isConnected).toBe(false);
+ expect(remountedRuntime).not.toBe(initialRuntime);
+ expect(remountedRuntime).not.toBeNull();
+
+ let accountEpoch = 2;
+
+ for (const path of AUTHENTICATED_PATHS) {
+ accountEpoch += 1;
+ await act(async () => {
+ sessionStore.setSnapshot(signedInSession(accountEpoch));
+ await router.navigate({ replace: true, to: path });
+ });
+ await expect.poll(() => router.state.location.pathname).toBe(path);
+ const authenticatedRuntime = host.querySelector<HTMLElement>('[data-testid="authenticated-runtime"]');
+ expect(authenticatedRuntime).not.toBeNull();
+
+ accountEpoch += 1;
+ await act(() => {
+ sessionStore.setSnapshot(signedOutSession(accountEpoch));
+ });
+
+ await expect.poll(() => router.state.location.pathname).toBe('/login');
+ expect(authenticatedRuntime?.isConnected).toBe(false);
+ expect(host.querySelector('[data-testid="authenticated-runtime"]')).toBeNull();
+ expect(host.querySelector('[data-testid="login-screen"]')).not.toBeNull();
+ }
+
+ for (const path of AUTHENTICATED_PATHS) {
+ accountEpoch += 1;
+ const snapshot = singleUserSession(accountEpoch);
+ await act(async () => {
+ sessionStore.setSnapshot(snapshot);
+ await router.navigate({ replace: true, to: path });
+ });
+ await expect.poll(() => router.state.location.pathname).toBe(path);
+ const authenticatedRuntime = host.querySelector<HTMLElement>('[data-testid="authenticated-runtime"]');
+ expect(authenticatedRuntime).not.toBeNull();
+
+ await act(() => {
+ sessionStore.setSnapshot({ ...snapshot });
+ });
+
+ expect(router.state.location.pathname).toBe(path);
+ expect(host.querySelector('[data-testid="authenticated-runtime"]')).toBe(authenticatedRuntime);
+ expect(host.querySelector('[data-testid="login-screen"]')).toBeNull();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
index 81d2082315..77e979786b 100644
--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
@@ -3,6 +3,7 @@ import { nodeExecutionStore } from '@features/nodes';
import { createProductionQueueRuntime } from '@features/queue';
import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';
/** App-owned production composition of Queue, Workbench, Gallery, Workflow, Nodes, and Models adapters. */
@@ -12,12 +13,16 @@ export const QueueRuntimeAdapter = () => {
const subscribe = useWorkbenchSubscription();
useMountEffect(() => {
+ const owner = captureAccountScope();
const runtime = createProductionQueueRuntime({
destinations: {
addImagesToGalleryBoard: async (boardId, imageNames) => {
+ assertAccountScopeCurrent(owner);
const { galleryOrganization } = await import('@features/gallery');
- await galleryOrganization.addToBoard(boardId, imageNames);
+ assertAccountScopeCurrent(owner);
+ await galleryOrganization.addToBoard(boardId, imageNames, owner.signal);
+ assertAccountScopeCurrent(owner);
},
},
ensureTemplatesLoaded: ensureInvocationTemplatesLoaded,
diff --git a/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx
index 6a1f402a85..5d883d71cb 100644
--- a/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx
+++ b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx
@@ -8,7 +8,7 @@ import { socketHub } from '@platform/transport/socketHub';
*
* It intentionally does NOT disconnect on unmount — that keeps it StrictMode
* safe and lets the socket persist across Launchpad↔editor navigation. The
- * socket is torn down explicitly on logout/expiry (see `features/identity/session.ts`).
+ * App-composed account lifecycle tears it down before an identity epoch changes.
*/
export const SocketHubRuntime = () => {
useMountEffect(() => {
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index 44cd4ea57f..0e67e504e0 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -1,6 +1,5 @@
import type { WorkbenchSearch } from '@workbench/projects/session';
-import { SessionExpiryGuard } from '@features/identity';
import { useSearch } from '@tanstack/react-router';
import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';
import { WorkbenchCommandPalette } from '@workbench/palette/WorkbenchCommandPalette';
@@ -37,7 +36,6 @@ export const WorkbenchApp = () => {
<WorkbenchProvider loadOptions={loadOptions}>
<WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>
<WorkbenchUiPorts>
- <SessionExpiryGuard />
<WorkbenchHotkeyRuntime />
<WorkbenchCommandPalette />
<QueueRuntimeAdapter />
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
index a6b0408c3e..16e427c57d 100644
--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
@@ -9,6 +9,11 @@ import { nodeExecutionStore } from '@features/nodes';
import { hasPendingWorkflowQueueItem } from '@features/queue';
import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';
import { shallowEqual } from '@platform/state/selectors';
import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';
@@ -71,15 +76,27 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNode
};
},
invoke: async (sourceId) => {
+ const owner = captureAccountScope();
flushGenerateDrafts();
- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
- return resolveAndSubmitGraphPreviewInvocation({
- commands,
- models: availabilityModels,
- prepareCanvasInvocation,
- project: queries.getSnapshot().activeProject,
- sourceId,
- });
+ try {
+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
+
+ assertAccountScopeCurrent(owner);
+ return resolveAndSubmitGraphPreviewInvocation({
+ commands,
+ models: availabilityModels,
+ owner,
+ prepareCanvasInvocation,
+ project: queries.getSnapshot().activeProject,
+ sourceId,
+ });
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
+ throw error;
+ }
},
}),
[availabilityModels, commands, queries, routeInput]
diff --git a/invokeai/frontend/webv2/src/app/accountLifecycle.test.ts b/invokeai/frontend/webv2/src/app/accountLifecycle.test.ts
new file mode 100644
index 0000000000..868716940e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/accountLifecycle.test.ts
@@ -0,0 +1,42 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const collaborators = vi.hoisted(() => ({
+ configureIdentityAccountLifecycle: vi.fn(),
+ disconnectSocket: vi.fn(),
+}));
+
+vi.mock('@features/identity', () => ({
+ configureIdentityAccountLifecycle: collaborators.configureIdentityAccountLifecycle,
+}));
+
+vi.mock('@platform/transport/socketHub', () => ({
+ socketHub: { disconnect: collaborators.disconnectSocket },
+}));
+
+beforeEach(() => {
+ vi.resetModules();
+ collaborators.configureIdentityAccountLifecycle.mockReset();
+ collaborators.disconnectSocket.mockReset();
+});
+
+describe('App account lifecycle composition', () => {
+ it('clears the shared QueryClient synchronously on account invalidation', async () => {
+ const [{ configureAppAccountLifecycle }, { queryClient }, { accountLifecycle }] = await Promise.all([
+ import('./accountLifecycle'),
+ import('@platform/query/client'),
+ import('@platform/state/accountLifecycle'),
+ ]);
+
+ configureAppAccountLifecycle();
+ accountLifecycle.activate('user-a', ':user:user-a');
+ collaborators.disconnectSocket.mockClear();
+ queryClient.setQueryData(['account-owned', 'probe'], { privateValue: 'user-a' });
+ expect(queryClient.getQueryData(['account-owned', 'probe'])).toEqual({ privateValue: 'user-a' });
+
+ accountLifecycle.invalidate();
+
+ expect(queryClient.getQueryData(['account-owned', 'probe'])).toBeUndefined();
+ expect(collaborators.disconnectSocket).toHaveBeenCalledOnce();
+ expect(collaborators.configureIdentityAccountLifecycle).toHaveBeenCalledWith(accountLifecycle);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/accountLifecycle.ts b/invokeai/frontend/webv2/src/app/accountLifecycle.ts
new file mode 100644
index 0000000000..533be526bb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/accountLifecycle.ts
@@ -0,0 +1,34 @@
+import { configureIdentityAccountLifecycle } from '@features/identity';
+import { queryClient } from '@platform/query/client';
+import { accountLifecycle, registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { socketHub } from '@platform/transport/socketHub';
+
+let isConfigured = false;
+
+/**
+ * App composition for resources whose implementations Identity must not know.
+ * Lazy feature modules register their own account-owned caches with the same
+ * lifecycle when they load.
+ */
+export const configureAppAccountLifecycle = (): void => {
+ if (isConfigured) {
+ return;
+ }
+ isConfigured = true;
+
+ registerAccountOwnedResource({
+ clear: () => {
+ // QueryClient.clear() synchronously destroys queries, which cancels their
+ // retryers before removing both query and mutation caches.
+ queryClient.clear();
+ },
+ name: 'query-client',
+ });
+ registerAccountOwnedResource({
+ clear: () => {
+ socketHub.disconnect();
+ },
+ name: 'socket-hub',
+ });
+ configureIdentityAccountLifecycle(accountLifecycle);
+};
diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsx
index 9d8900c5fa..42b0b2a644 100644
--- a/invokeai/frontend/webv2/src/app/main.tsx
+++ b/invokeai/frontend/webv2/src/app/main.tsx
@@ -5,9 +5,11 @@ import { configureHttpAuth } from '@platform/transport/http';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
+import { configureAppAccountLifecycle } from './accountLifecycle';
import { App } from './App';
-// HTTP auth must be configured before any React-owned transport consumer mounts.
+// Identity and HTTP ownership must be configured before any route starts work.
+configureAppAccountLifecycle();
configureHttpAuth(identityTransportAuthAdapter);
const rootElement = document.getElementById('root');
diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsx
index fe1937d8bc..e7eb3a7f5c 100644
--- a/invokeai/frontend/webv2/src/app/router.tsx
+++ b/invokeai/frontend/webv2/src/app/router.tsx
@@ -1,18 +1,31 @@
-import { ensureAuthSession, getCapabilities, LoginScreen, SetupScreen, type Capabilities } from '@features/identity';
+import {
+ AuthSessionUnavailableError,
+ AuthUnavailableScreen,
+ ensureReadyAuthSession,
+ getCapabilities,
+ LoginScreen,
+ SetupScreen,
+ useAuthSession,
+ type Capabilities,
+} from '@features/identity';
import {
createHashHistory,
createRootRoute,
createRoute,
createRouter,
+ ErrorComponent,
+ type ErrorComponentProps,
lazyRouteComponent,
Navigate,
Outlet,
redirect,
+ useRouter,
} from '@tanstack/react-router';
import { WorkbenchSplashScreen } from '@workbench/components/WorkbenchSplashScreen';
import { Launchpad } from '@workbench/launchpad/Launchpad';
import { peekOpenProjectIds, type WorkbenchSearch } from '@workbench/projects/session';
import { loadWorkbenchSettings } from '@workbench/settings/store';
+import { Fragment } from 'react';
import { SocketHubRuntime } from './SocketHubRuntime';
@@ -34,23 +47,48 @@ import { SocketHubRuntime } from './SocketHubRuntime';
* (`./`), so the app cannot rely on server-side fallback for deep paths.
*/
-const rootRoute = createRootRoute({ component: Outlet });
+const RouterError = ({ error }: ErrorComponentProps) => {
+ 'use no memo';
+ // Cold-path boundary: Compiler's memo cache costs more than this render.
+ // The browser retry test and production build budget guard its behavior.
+ const router = useRouter();
+
+ return error instanceof AuthSessionUnavailableError ? (
+ <AuthUnavailableScreen onRetry={router.invalidate} />
+ ) : (
+ <ErrorComponent error={error} />
+ );
+};
+
+const rootRoute = createRootRoute({ component: Outlet, errorComponent: RouterError });
/**
* Wraps every authenticated route with the shared backend socket transport.
* Feature runtimes attach their own listeners only where needed, keeping the
* light Launchpad bundle free of editor/model-manager code.
*/
-const AuthenticatedLayout = () => (
- <>
- <SocketHubRuntime />
- <Outlet />
- </>
-);
+const AuthenticatedLayout = () => {
+ const session = useAuthSession();
+
+ if (session.phase !== 'ready') {
+ return null;
+ }
+
+ if (session.multiuserEnabled && session.user === null) {
+ return <Navigate replace to="/login" />;
+ }
+
+ return (
+ <Fragment key={session.accountEpoch}>
+ <SocketHubRuntime />
+ <Outlet />
+ </Fragment>
+ );
+};
const authenticatedRoute = createRoute({
beforeLoad: async () => {
- const session = await ensureAuthSession();
+ const session = await ensureReadyAuthSession();
if (session.multiuserEnabled) {
if (session.setupRequired) {
@@ -70,7 +108,7 @@ const authenticatedRoute = createRoute({
});
const requireLaunchpadCapability = async (capability: keyof Capabilities): Promise<void> => {
- const session = await ensureAuthSession();
+ const session = await ensureReadyAuthSession();
if (!getCapabilities(session)[capability]) {
throw redirect({ to: '/projects' });
@@ -147,7 +185,7 @@ const workbenchRoute = createRoute({
const loginRoute = createRoute({
beforeLoad: async () => {
- const session = await ensureAuthSession();
+ const session = await ensureReadyAuthSession();
if (session.multiuserEnabled && session.setupRequired) {
throw redirect({ to: '/setup' });
@@ -164,7 +202,7 @@ const loginRoute = createRoute({
const setupRoute = createRoute({
beforeLoad: async () => {
- const session = await ensureAuthSession();
+ const session = await ensureReadyAuthSession();
if (!session.multiuserEnabled || !session.setupRequired) {
throw redirect({ to: '/' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 34f7c180f0..e9bdb9606d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -1,18 +1,22 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
apiFetchJson: vi.fn(),
+ apiFetchRaw: vi.fn(),
+ sleep: vi.fn(),
}));
vi.mock('@platform/transport/http', () => ({
absolutizeApiUrl: (url: string) => `https://api.test${url}`,
apiFetch: vi.fn(),
apiFetchJson: mocks.apiFetchJson,
- apiFetchRaw: vi.fn(),
- sleep: vi.fn(),
+ apiFetchRaw: mocks.apiFetchRaw,
+ sleep: mocks.sleep,
}));
import {
+ downloadGalleryArchive,
getGalleryImageByName,
imageMakeCanvasAssetChanges,
imageMakeDurableChanges,
@@ -20,6 +24,46 @@ import {
listGalleryImages,
} from './backend';
+describe('downloadGalleryArchive', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('user-a');
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchRaw.mockReset();
+ mocks.sleep.mockReset();
+ });
+
+ it('aborts polling before another account can request the prior account archive', async () => {
+ let resumeSleep: (() => void) | undefined;
+ mocks.apiFetchJson.mockResolvedValue({ bulk_download_item_name: 'user-a.zip' });
+ mocks.apiFetchRaw.mockResolvedValue(new Response(null, { status: 404 }));
+ mocks.sleep.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resumeSleep = resolve;
+ })
+ );
+
+ const download = downloadGalleryArchive({ imageNames: ['user-a.png'] });
+
+ await vi.waitFor(() => {
+ expect(mocks.sleep).toHaveBeenCalledOnce();
+ });
+ const postSignal = (mocks.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+ const pollSignal = (mocks.apiFetchRaw.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+ const sleepSignal = mocks.sleep.mock.calls[0]?.[1] as AbortSignal;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resumeSleep?.();
+
+ await expect(download).rejects.toThrow('no longer active');
+ expect(postSignal?.aborted).toBe(true);
+ expect(pollSignal?.aborted).toBe(true);
+ expect(sleepSignal.aborted).toBe(true);
+ expect(mocks.apiFetchRaw).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('getGalleryImageByName', () => {
beforeEach(() => {
mocks.apiFetchJson.mockReset();
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 31bd67f295..fbdbc0943a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -9,6 +9,7 @@ import type {
} from '@features/gallery/core/types';
import { isTimestampInRange } from '@platform/search/dateTokens';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { absolutizeApiUrl, apiFetch, apiFetchJson, apiFetchRaw, sleep } from '@platform/transport/http';
import { getGalleryImageThumbnailUrl } from './imageUrls';
@@ -182,8 +183,8 @@ interface VirtualDateBoardDTO {
cover_image_name?: string | null;
}
-export const listGalleryDateBoards = async (): Promise<GalleryBoard[]> => {
- const body = await apiFetchJson<VirtualDateBoardDTO[]>('/api/v1/virtual_boards/by_date');
+export const listGalleryDateBoards = async (signal?: AbortSignal): Promise<GalleryBoard[]> => {
+ const body = await apiFetchJson<VirtualDateBoardDTO[]>('/api/v1/virtual_boards/by_date', { signal });
return body.map((board) => ({
archived: false,
@@ -197,7 +198,7 @@ export const listGalleryDateBoards = async (): Promise<GalleryBoard[]> => {
}));
};
-export const getGalleryImagesByNames = async (imageNames: string[]): Promise<GalleryImage[]> => {
+export const getGalleryImagesByNames = async (imageNames: string[], signal?: AbortSignal): Promise<GalleryImage[]> => {
if (imageNames.length === 0) {
return [];
}
@@ -205,6 +206,7 @@ export const getGalleryImagesByNames = async (imageNames: string[]): Promise<Gal
const body = await apiFetchJson<BackendImageDTO[]>('/api/v1/images/images_by_names', {
body: JSON.stringify({ image_names: imageNames }),
method: 'POST',
+ signal,
});
return body.map(mapImage);
@@ -262,7 +264,7 @@ const listGalleryDateBoardImages = async ({
`/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`,
{ signal }
);
- const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit));
+ const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit), signal);
return { images, total: normalizeTotal(body.total_count, body.image_names.length) };
};
@@ -410,38 +412,51 @@ export const saveImageToGallery = async (imageName: string): Promise<GalleryImag
return mapImage(body);
};
-export const getGalleryImageMetadata = async (imageName: string): Promise<GalleryImageMetadata | null> => {
- const body = await apiFetchJson<unknown>(`/api/v1/images/i/${encodeURIComponent(imageName)}/metadata`);
+export const getGalleryImageMetadata = async (
+ imageName: string,
+ signal?: AbortSignal
+): Promise<GalleryImageMetadata | null> => {
+ const body = await apiFetchJson<unknown>(`/api/v1/images/i/${encodeURIComponent(imageName)}/metadata`, { signal });
return body && typeof body === 'object' && !Array.isArray(body) ? (body as GalleryImageMetadata) : null;
};
-export const createGalleryBoard = async (boardName: string): Promise<GalleryBoard> => {
+export const createGalleryBoard = async (boardName: string, signal?: AbortSignal): Promise<GalleryBoard> => {
const query = toSearchParams({ board_name: boardName });
- const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/?${query}`, { method: 'POST' });
+ const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/?${query}`, { method: 'POST', signal });
return mapBoard(body);
};
export const updateGalleryBoard = async (
boardId: string,
- changes: { name?: string; archived?: boolean }
+ changes: { name?: string; archived?: boolean },
+ signal?: AbortSignal
): Promise<GalleryBoard> => {
const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/${encodeURIComponent(boardId)}`, {
body: JSON.stringify({ archived: changes.archived, board_name: changes.name }),
method: 'PATCH',
+ signal,
});
return mapBoard(body);
};
-export const deleteGalleryBoard = async (boardId: string, includeImages: boolean): Promise<void> => {
+export const deleteGalleryBoard = async (
+ boardId: string,
+ includeImages: boolean,
+ signal?: AbortSignal
+): Promise<void> => {
const query = toSearchParams({ include_images: includeImages });
- await apiFetch(`/api/v1/boards/${encodeURIComponent(boardId)}?${query}`, { method: 'DELETE' });
+ await apiFetch(`/api/v1/boards/${encodeURIComponent(boardId)}?${query}`, { method: 'DELETE', signal });
};
-export const addImagesToGalleryBoard = async (boardId: string, imageNames: string[]): Promise<void> => {
+export const addImagesToGalleryBoard = async (
+ boardId: string,
+ imageNames: string[],
+ signal?: AbortSignal
+): Promise<void> => {
if (
boardId === 'none' ||
boardId === 'generated' ||
@@ -455,10 +470,11 @@ export const addImagesToGalleryBoard = async (boardId: string, imageNames: strin
await apiFetchJson('/api/v1/board_images/batch', {
body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
method: 'POST',
+ signal,
});
};
-export const removeImagesFromGalleryBoard = async (imageNames: string[]): Promise<void> => {
+export const removeImagesFromGalleryBoard = async (imageNames: string[], signal?: AbortSignal): Promise<void> => {
if (imageNames.length === 0) {
return;
}
@@ -466,10 +482,11 @@ export const removeImagesFromGalleryBoard = async (imageNames: string[]): Promis
await apiFetchJson('/api/v1/board_images/batch/delete', {
body: JSON.stringify({ image_names: imageNames }),
method: 'POST',
+ signal,
});
};
-const setGalleryImagesStarred = async (imageNames: string[], starred: boolean): Promise<void> => {
+const setGalleryImagesStarred = async (imageNames: string[], starred: boolean, signal?: AbortSignal): Promise<void> => {
if (imageNames.length === 0) {
return;
}
@@ -477,14 +494,17 @@ const setGalleryImagesStarred = async (imageNames: string[], starred: boolean):
await apiFetchJson(`/api/v1/images/${starred ? 'star' : 'unstar'}`, {
body: JSON.stringify({ image_names: imageNames }),
method: 'POST',
+ signal,
});
};
-export const starGalleryImages = (imageNames: string[]): Promise<void> => setGalleryImagesStarred(imageNames, true);
+export const starGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<void> =>
+ setGalleryImagesStarred(imageNames, true, signal);
-export const unstarGalleryImages = (imageNames: string[]): Promise<void> => setGalleryImagesStarred(imageNames, false);
+export const unstarGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<void> =>
+ setGalleryImagesStarred(imageNames, false, signal);
-export const deleteGalleryImages = async (imageNames: string[]): Promise<void> => {
+export const deleteGalleryImages = async (imageNames: string[], signal?: AbortSignal): Promise<void> => {
if (imageNames.length === 0) {
return;
}
@@ -492,6 +512,7 @@ export const deleteGalleryImages = async (imageNames: string[]): Promise<void> =
await apiFetchJson('/api/v1/images/delete', {
body: JSON.stringify({ image_names: imageNames }),
method: 'POST',
+ signal,
});
};
@@ -506,18 +527,25 @@ const BULK_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
export const downloadGalleryArchive = async ({
boardId,
imageNames,
+ signal,
}: {
boardId?: string;
imageNames?: string[];
+ signal?: AbortSignal;
}): Promise<{ blob: Blob; fileName: string }> => {
+ const owner = captureAccountScope();
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
const { bulk_download_item_name: fileName } = await apiFetchJson<{ bulk_download_item_name?: string | null }>(
'/api/v1/images/download',
{
body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
method: 'POST',
+ signal: requestSignal,
}
);
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
if (!fileName) {
throw new Error('The bulk download failed to start.');
}
@@ -525,17 +553,27 @@ export const downloadGalleryArchive = async ({
const startedAt = Date.now();
while (Date.now() - startedAt < BULK_DOWNLOAD_TIMEOUT_MS) {
- const response = await apiFetchRaw(`/api/v1/images/download/${encodeURIComponent(fileName)}`);
+ const response = await apiFetchRaw(`/api/v1/images/download/${encodeURIComponent(fileName)}`, {
+ signal: requestSignal,
+ });
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
if (response.ok) {
- return { blob: await response.blob(), fileName };
+ const blob = await response.blob();
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+ return { blob, fileName };
}
if (response.status !== 404) {
throw new Error(`${response.status} ${response.statusText}`);
}
- await sleep(BULK_DOWNLOAD_POLL_INTERVAL_MS);
+ await sleep(BULK_DOWNLOAD_POLL_INTERVAL_MS, requestSignal);
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
}
throw new Error('Timed out preparing the download archive.');
@@ -544,7 +582,7 @@ export const downloadGalleryArchive = async ({
export const uploadGalleryImage = async (
file: File,
boardId: string,
- options: { isIntermediate?: boolean } = {}
+ options: { isIntermediate?: boolean; signal?: AbortSignal } = {}
): Promise<GalleryImage> => {
const query = toSearchParams({
board_id: boardId === 'none' || isDateBoardId(boardId) ? undefined : boardId,
@@ -557,6 +595,7 @@ export const uploadGalleryImage = async (
const uploadedImage = await apiFetchJson<BackendImageDTO>(`/api/v1/images/upload?${query}`, {
body,
method: 'POST',
+ signal: options.signal,
});
return mapImage(uploadedImage);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
index 0cb74f363b..73a5ecf433 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -1,3 +1,4 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -66,4 +67,28 @@ describe('Gallery query read model', () => {
galleryImagesOptions({ ...ranged, createdTo: '2026-07-16' }).queryKey
);
});
+
+ it('cannot cache an image response from an expired account epoch', async () => {
+ accountLifecycle.activate('user-a');
+ let resolveImages: ((value: { images: never[]; total: number }) => void) | undefined;
+ backend.listGalleryImages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveImages = resolve;
+ })
+ );
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const options = galleryImagesOptions({
+ boardId: 'none',
+ galleryView: 'images',
+ searchTerm: '',
+ });
+ const oldRequest = queryClient.fetchQuery(options);
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resolveImages?.({ images: [], total: 0 });
+
+ await expect(oldRequest).rejects.toThrow('no longer active');
+ expect(queryClient.getQueryData(options.queryKey)).toBeUndefined();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index 53505be2f9..cfaf1bf7d8 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -1,5 +1,6 @@
import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { queryOptions } from '@tanstack/react-query';
import { listGalleryBoards, listGalleryDateBoards, listGalleryImages } from './backend';
@@ -33,23 +34,41 @@ export const galleryKeys = {
images: (query: GalleryImagesQuery) => [...galleryKeys.all, 'images', query] as const,
};
-export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) =>
- queryOptions({
+export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
queryFn: async ({ signal }) => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
const [boards, dateBoards] = await Promise.all([
- listGalleryBoards({ ...query, signal }),
- query.includeDateBoards ? listGalleryDateBoards() : Promise.resolve([]),
+ listGalleryBoards({ ...query, signal: requestSignal }),
+ query.includeDateBoards ? listGalleryDateBoards(requestSignal) : Promise.resolve([]),
]);
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+
return [...boards, ...dateBoards];
},
queryKey: galleryKeys.boards(query),
staleTime: 60_000,
});
+};
-export const galleryImagesOptions = (query: GalleryImagesQuery) =>
- queryOptions({
- queryFn: ({ signal }) => listGalleryImages({ ...query, signal }),
+export const galleryImagesOptions = (query: GalleryImagesQuery) => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: async ({ signal }) => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const result = await listGalleryImages({ ...query, signal: requestSignal });
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+
+ return result;
+ },
queryKey: galleryKeys.images(query),
staleTime: 60_000,
});
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.ts
index 44c1101f35..dd99256843 100644
--- a/invokeai/frontend/webv2/src/features/gallery/index.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts
@@ -53,8 +53,8 @@ export const galleryOrganization = {
addToBoard: addImagesToGalleryBoard,
deleteImages: deleteGalleryImages,
removeFromBoard: removeImagesFromGalleryBoard,
- setStarred: (imageNames: string[], starred: boolean): Promise<void> =>
- starred ? starGalleryImages(imageNames) : unstarGalleryImages(imageNames),
+ setStarred: (imageNames: string[], starred: boolean, signal?: AbortSignal): Promise<void> =>
+ starred ? starGalleryImages(imageNames, signal) : unstarGalleryImages(imageNames, signal),
} as const;
/** Destination choices for callers such as Workflow fields. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 057ffe7035..b1488e8b54 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -7,6 +7,11 @@ import {
updateGalleryBoard,
uploadGalleryImage,
} from '@features/gallery/data/backend';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { useMemo } from 'react';
import type { GalleryActions } from './GalleryWidgetContext';
@@ -51,8 +56,12 @@ export const useGalleryActions = ({
return {
archiveBoard: async (boardId, archived) => {
+ const owner = captureAccountScope();
+
try {
- await updateGalleryBoard(boardId, { archived });
+ await updateGalleryBoard(boardId, { archived }, owner.signal);
+
+ assertAccountScopeCurrent(owner);
recordSuccess(`${archived ? 'Archived' : 'Unarchived'} board "${getBoardName(boardId)}"`);
if (archived && boardId === selectedBoardId) {
@@ -61,25 +70,40 @@ export const useGalleryActions = ({
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
createBoard: async (boardName) => {
+ const owner = captureAccountScope();
+
try {
- const board = await createGalleryBoard(boardName);
+ const board = await createGalleryBoard(boardName, owner.signal);
+ assertAccountScopeCurrent(owner);
gallery.selectBoard(board.id);
recordSuccess(`Created board "${board.name}"`);
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
deleteBoard: async (boardId, includeImages) => {
+ const owner = captureAccountScope();
+
try {
const boardName = getBoardName(boardId);
- await deleteGalleryBoard(boardId, includeImages);
+ await deleteGalleryBoard(boardId, includeImages, owner.signal);
+
+ assertAccountScopeCurrent(owner);
recordSuccess(
`Deleted board "${boardName}"`,
includeImages ? 'Its images were permanently deleted.' : 'Its images were moved to Uncategorized.'
@@ -91,10 +115,16 @@ export const useGalleryActions = ({
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
downloadBoard: async (boardId) => {
+ const owner = captureAccountScope();
+
try {
notifications.add({
kind: 'info',
@@ -102,22 +132,35 @@ export const useGalleryActions = ({
title: 'Preparing download',
});
- const { blob, fileName } = await downloadGalleryArchive({ boardId });
+ const { blob, fileName } = await downloadGalleryArchive({ boardId, signal: owner.signal });
+ assertAccountScopeCurrent(owner);
saveBlobToDisk(blob, fileName);
recordSuccess('Download ready');
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
loadMore,
refresh,
renameBoard: async (boardId, boardName) => {
+ const owner = captureAccountScope();
+
try {
- await updateGalleryBoard(boardId, { name: boardName });
+ await updateGalleryBoard(boardId, { name: boardName }, owner.signal);
+
+ assertAccountScopeCurrent(owner);
recordSuccess(`Renamed board to "${boardName}"`);
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
@@ -125,6 +168,8 @@ export const useGalleryActions = ({
selectImage: gallery.selectImage,
selectImageRange: gallery.setMultiSelection,
selectProjectBoard: async () => {
+ const owner = captureAccountScope();
+
if (projectBoardId && boards.some((board) => board.id === projectBoardId)) {
gallery.selectBoard(projectBoardId);
return;
@@ -135,13 +180,18 @@ export const useGalleryActions = ({
}
try {
- const board = await createGalleryBoard(projectName);
+ const board = await createGalleryBoard(projectName, owner.signal);
+ assertAccountScopeCurrent(owner);
gallery.setProjectBoard(board.id);
gallery.selectBoard(board.id);
recordSuccess(`Created project board "${board.name}"`);
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
@@ -150,6 +200,7 @@ export const useGalleryActions = ({
toggleImageInSelection: gallery.toggleImageSelection,
updateSettings: gallery.updateSettings,
uploadFiles: async (files) => {
+ const owner = captureAccountScope();
const accepted = files.filter((file) => ACCEPTED_UPLOAD_TYPES.has(file.type));
if (accepted.length === 0) {
@@ -162,13 +213,21 @@ export const useGalleryActions = ({
}
try {
- await Promise.all(accepted.map((file) => uploadGalleryImage(file, selectedBoardId)));
+ await Promise.all(
+ accepted.map((file) => uploadGalleryImage(file, selectedBoardId, { signal: owner.signal }))
+ );
+
+ assertAccountScopeCurrent(owner);
recordSuccess(
`Uploaded ${accepted.length} ${accepted.length === 1 ? 'image' : 'images'}`,
`Added to ${getBoardName(selectedBoardId)} as assets.`
);
refresh();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.test.ts
new file mode 100644
index 0000000000..460fa5f1ce
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.test.ts
@@ -0,0 +1,59 @@
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+
+import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as navigationModule from './promptHistoryNavigation';
+
+vi.mock('./promptFocus', () => ({ isPositivePromptFocused: () => true }));
+
+let account: typeof accountLifecycleModule;
+let navigation: typeof navigationModule;
+
+const model = { base: 'sdxl', key: 'model', name: 'Model', type: 'main' } as const;
+
+beforeEach(async () => {
+ vi.resetModules();
+ navigation = await import('./promptHistoryNavigation');
+ account = await import('@platform/state/accountLifecycle');
+ account.accountLifecycle.activate('prompt-history-a');
+});
+
+afterEach(() => {
+ account.accountLifecycle.invalidate();
+});
+
+describe('prompt history account ownership', () => {
+ it('does not restore account A stashed prompts after account B becomes active', () => {
+ const patchValues = vi.fn();
+ const values = {
+ ...getDefaultGenerateSettings(model),
+ negativePrompt: 'account A negative',
+ negativePromptEnabled: true,
+ positivePrompt: 'account A draft',
+ };
+
+ navigation.promptHistoryNavigation.navigate({
+ direction: -1,
+ models: [model],
+ patchValues,
+ projectId: 'shared-project-id',
+ promptHistory: [{ negativePrompt: null, positivePrompt: 'account A history' }],
+ values,
+ });
+ expect(patchValues).toHaveBeenCalledOnce();
+
+ account.accountLifecycle.activate('prompt-history-b');
+ patchValues.mockClear();
+ navigation.promptHistoryNavigation.navigate({
+ direction: 1,
+ models: [model],
+ patchValues,
+ projectId: 'shared-project-id',
+ promptHistory: [{ negativePrompt: null, positivePrompt: 'account B history' }],
+ values: { ...values, positivePrompt: 'account B draft' },
+ });
+
+ expect(patchValues).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts
index 0d403cd316..7702f2906a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts
@@ -2,6 +2,7 @@ import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } fro
import { getPromptHistoryRecallPatch } from '@features/generation/core/baseGenerationPolicies';
import { normalizeGenerateSettings } from '@features/generation/core/settings';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { isPositivePromptFocused } from './promptFocus';
@@ -115,3 +116,8 @@ export const createPromptHistoryNavigation = (): PromptHistoryNavigation => {
/** One navigation cursor per window: the hotkey commands and both prompt fields must share it. */
export const promptHistoryNavigation: PromptHistoryNavigation = createPromptHistoryNavigation();
+
+registerAccountOwnedResource({
+ clear: promptHistoryNavigation.reset,
+ name: 'prompt-history-navigation',
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.ts
index 4a9d3e00e6..2b5027d4d0 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.ts
@@ -1,4 +1,5 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { type AccountScope, accountLifecycle } from '@platform/state/accountLifecycle';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const galleryApi = vi.hoisted(() => ({
galleryTransfers: { upload: vi.fn() },
@@ -25,8 +26,9 @@ const image = {
};
const cropBox = { height: 50, width: 50, x: 25, y: 10 };
-const stubCropBrowserApis = (onLoadUrl?: (url: string) => void) => {
+const stubCropBrowserApis = (onLoadUrl?: (url: string) => void, autoLoad = true) => {
const drawImage = vi.fn();
+ let completePendingLoad: (() => void) | null = null;
class TestImage {
crossOrigin = '';
@@ -37,7 +39,12 @@ const stubCropBrowserApis = (onLoadUrl?: (url: string) => void) => {
set src(value: string) {
onLoadUrl?.(value);
- this.onload?.();
+ if (autoLoad) {
+ this.onload?.();
+ } else {
+ const onload = this.onload;
+ completePendingLoad = () => onload?.();
+ }
}
}
@@ -51,11 +58,18 @@ const stubCropBrowserApis = (onLoadUrl?: (url: string) => void) => {
}),
});
- return { drawImage, TestImage };
+ return { completeLoad: () => completePendingLoad?.(), drawImage, TestImage };
};
+let owner: AccountScope;
+
+beforeEach(() => {
+ owner = accountLifecycle.activate('reference-crop-a', ':user:reference-crop-a');
+});
+
afterEach(() => {
galleryApi.galleryTransfers.upload.mockReset();
+ accountLifecycle.invalidate();
vi.unstubAllGlobals();
});
@@ -78,10 +92,11 @@ describe('ReferenceImageCropDialog', () => {
stubCropBrowserApis();
galleryApi.galleryTransfers.upload.mockResolvedValue({ height: 300, imageName: 'new-crop.png', width: 400 });
- const result = await applyReferenceImageCropSelection(image, cropBox);
+ const result = await applyReferenceImageCropSelection(image, cropBox, owner);
expect(galleryApi.galleryTransfers.upload).toHaveBeenCalledWith(expect.any(File), 'none', {
isIntermediate: true,
+ signal: owner.signal,
});
expect(result).toEqual({
crop: {
@@ -92,4 +107,34 @@ describe('ReferenceImageCropDialog', () => {
original: image.original,
});
});
+
+ it('does not upload when account A expires during local crop preprocessing', async () => {
+ const { completeLoad } = stubCropBrowserApis(undefined, false);
+ const pendingCrop = applyReferenceImageCropSelection(image, cropBox, owner);
+
+ accountLifecycle.activate('reference-crop-b', ':user:reference-crop-b');
+ completeLoad();
+
+ await expect(pendingCrop).rejects.toHaveProperty('name', 'AccountScopeExpiredError');
+ expect(owner.signal.aborted).toBe(true);
+ expect(galleryApi.galleryTransfers.upload).not.toHaveBeenCalled();
+ });
+
+ it('rejects an account A upload that resolves after account B activates', async () => {
+ stubCropBrowserApis();
+ let resolveUpload!: (value: { height: number; imageName: string; width: number }) => void;
+ const upload = new Promise<{ height: number; imageName: string; width: number }>((resolve) => {
+ resolveUpload = resolve;
+ });
+ galleryApi.galleryTransfers.upload.mockReturnValue(upload);
+
+ const pendingCrop = applyReferenceImageCropSelection(image, cropBox, owner);
+ await vi.waitFor(() => expect(galleryApi.galleryTransfers.upload).toHaveBeenCalledOnce());
+
+ accountLifecycle.activate('reference-crop-b', ':user:reference-crop-b');
+ resolveUpload({ height: 300, imageName: 'new-crop.png', width: 400 });
+
+ await expect(pendingCrop).rejects.toHaveProperty('name', 'AccountScopeExpiredError');
+ expect(owner.signal.aborted).toBe(true);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
index d6bb5f7361..d6ffe23435 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
@@ -13,6 +13,12 @@ import {
} from '@features/generation/core/referenceImage';
import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { Button } from '@platform/ui';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -99,8 +105,10 @@ const isDragMode = (value: unknown): value is DragMode =>
export const exportCroppedReferenceImage = async (
image: GenerateReferenceImageAsset,
- cropBox: ReferenceImageCropBoxPct
+ cropBox: ReferenceImageCropBoxPct,
+ owner: AccountScope = captureAccountScope()
): Promise<File> => {
+ assertAccountScopeCurrent(owner);
const original = image.original.image;
const img = new Image();
img.crossOrigin = 'anonymous';
@@ -111,6 +119,7 @@ export const exportCroppedReferenceImage = async (
img.src = getReferenceImageUrls({ original: image.original }).imageUrl;
});
+ assertAccountScopeCurrent(owner);
const sourceWidth = img.naturalWidth || original.width;
const sourceHeight = img.naturalHeight || original.height;
const sx = Math.round((cropBox.x / 100) * sourceWidth);
@@ -130,20 +139,29 @@ export const exportCroppedReferenceImage = async (
);
});
+ assertAccountScopeCurrent(owner);
return new File([blob], `${original.image_name.replace(/\.[^.]+$/, '')}-crop.png`, { type: 'image/png' });
};
export const applyReferenceImageCropSelection = async (
image: GenerateReferenceImageAsset,
- cropBox: ReferenceImageCropBoxPct
+ cropBox: ReferenceImageCropBoxPct,
+ owner: AccountScope = captureAccountScope()
): Promise<GenerateReferenceImageAsset> => {
+ assertAccountScopeCurrent(owner);
+
if (isFullReferenceImageCropBox(cropBox)) {
return resolveReferenceImageCrop(image, cropBox, null);
}
- const file = await exportCroppedReferenceImage(image, cropBox);
- const croppedImage = await galleryTransfers.upload(file, 'none', { isIntermediate: true });
+ const file = await exportCroppedReferenceImage(image, cropBox, owner);
+ assertAccountScopeCurrent(owner);
+ const croppedImage = await galleryTransfers.upload(file, 'none', {
+ isIntermediate: true,
+ signal: owner.signal,
+ });
+ assertAccountScopeCurrent(owner);
return resolveReferenceImageCrop(image, cropBox, generatedImageToReferenceImage(croppedImage).original.image);
};
@@ -240,26 +258,42 @@ export const ReferenceImageCropDialog = ({
const resetCrop = useCallback(() => setCropBox(FULL_REFERENCE_IMAGE_CROP_BOX), []);
const applyCrop = useCallback(async () => {
- if (isFullReferenceImageCropBox(cropBox)) {
- onApply(await applyReferenceImageCropSelection(image, cropBox));
- close();
- return;
+ const owner = captureAccountScope();
+ const isFullCrop = isFullReferenceImageCropBox(cropBox);
+
+ if (!isFullCrop) {
+ setIsApplying(true);
}
try {
- setIsApplying(true);
- const croppedImage = await applyReferenceImageCropSelection(image, cropBox);
- gallery.touchImages();
+ const croppedImage = await applyReferenceImageCropSelection(image, cropBox, owner);
+
+ assertAccountScopeCurrent(owner);
+ if (!isFullCrop) {
+ gallery.touchImages();
+ }
+
+ assertAccountScopeCurrent(owner);
onApply(croppedImage);
- onClose();
+ if (isFullCrop) {
+ close();
+ } else {
+ onClose();
+ }
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notifications.reportError({
area: 'reference-images',
message: error instanceof Error ? error.message : String(error),
namespace: 'generation',
});
} finally {
- setIsApplying(false);
+ if (!isFullCrop && isAccountScopeCurrent(owner)) {
+ setIsApplying(false);
+ }
}
}, [close, cropBox, gallery, image, notifications, onApply, onClose]);
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
index 6cfc0bf7ca..5241a9a4a1 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
@@ -5,6 +5,7 @@ import type { AuthSession } from './session';
import { getCapabilities } from './capabilities';
const session = (overrides: Partial<AuthSession>): AuthSession => ({
+ accountEpoch: 0,
multiuserEnabled: true,
phase: 'ready',
sessionExpired: false,
@@ -15,6 +16,14 @@ const session = (overrides: Partial<AuthSession>): AuthSession => ({
});
describe('Identity route capabilities', () => {
+ it.each(['unknown', 'unavailable'] as const)('grants nothing while auth mode is %s', (phase) => {
+ expect(getCapabilities(session({ multiuserEnabled: false, phase }))).toEqual({
+ canManageModels: false,
+ canManageNodes: false,
+ canManageUsers: false,
+ });
+ });
+
it('allows all local management in single-user mode', () => {
expect(getCapabilities(session({ multiuserEnabled: false }))).toEqual({
canManageModels: true,
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
index 92c61cfd25..497c929d02 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
@@ -7,6 +7,14 @@ export interface Capabilities {
}
export const getCapabilities = (session: AuthSession): Capabilities => {
+ if (session.phase !== 'ready') {
+ return {
+ canManageModels: false,
+ canManageNodes: false,
+ canManageUsers: false,
+ };
+ }
+
const isSingleUser = !session.multiuserEnabled;
const isAdmin = isSingleUser || session.user?.is_admin === true;
diff --git a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts
index a91723c9aa..53615e38c9 100644
--- a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts
@@ -3,9 +3,16 @@ import { describe, expect, it } from 'vitest';
import { shouldExpireUnauthorizedSession } from './sessionPolicy';
describe('unauthorized session policy', () => {
- it('expires only an authenticated multi-user session', () => {
- expect(shouldExpireUnauthorizedSession({ multiuserEnabled: true, user: { user_id: 'admin' } })).toBe(true);
- expect(shouldExpireUnauthorizedSession({ multiuserEnabled: true, user: null })).toBe(false);
- expect(shouldExpireUnauthorizedSession({ multiuserEnabled: false, user: null })).toBe(false);
+ it('expires an authenticated multi-user session but not login or single-user requests', () => {
+ expect(
+ shouldExpireUnauthorizedSession({ multiuserEnabled: true, phase: 'ready', user: { user_id: 'admin' } })
+ ).toBe(true);
+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: true, phase: 'ready', user: null })).toBe(false);
+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: false, phase: 'ready', user: null })).toBe(false);
+ });
+
+ it('rejects the current stored credential while auth mode is unresolved', () => {
+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: false, phase: 'unknown', user: null })).toBe(true);
+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: false, phase: 'unavailable', user: null })).toBe(true);
});
});
diff --git a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts
index f1c5ee5906..f2dc7faad0 100644
--- a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts
+++ b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts
@@ -1,8 +1,13 @@
export interface UnauthorizedSessionState {
+ phase: 'unknown' | 'unavailable' | 'ready';
multiuserEnabled: boolean;
user: unknown | null;
}
-/** Login failures and single-user requests must never expire the active shell session. */
+/**
+ * The transport only calls this policy for the current stored credential.
+ * Rejecting that credential while auth mode is unresolved must clear it;
+ * login requests have no stored bearer token and never reach this policy.
+ */
export const shouldExpireUnauthorizedSession = (session: UnauthorizedSessionState): boolean =>
- session.multiuserEnabled && session.user !== null;
+ session.phase !== 'ready' || (session.multiuserEnabled && session.user !== null);
diff --git a/invokeai/frontend/webv2/src/features/identity/data/api.ts b/invokeai/frontend/webv2/src/features/identity/data/api.ts
index 850373e11d..176739e3df 100644
--- a/invokeai/frontend/webv2/src/features/identity/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/identity/data/api.ts
@@ -66,8 +66,8 @@ export interface UserUpdateRequest {
export const getAuthStatus = (): Promise<AuthStatus> => apiFetchJson<AuthStatus>(`${AUTH_BASE}/status`);
-export const login = (request: LoginRequest): Promise<LoginResult> =>
- apiFetchJson<LoginResult>(`${AUTH_BASE}/login`, { body: JSON.stringify(request), method: 'POST' });
+export const login = (request: LoginRequest, signal?: AbortSignal): Promise<LoginResult> =>
+ apiFetchJson<LoginResult>(`${AUTH_BASE}/login`, { body: JSON.stringify(request), method: 'POST', signal });
export const logout = (): Promise<{ success: boolean }> =>
apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/logout`, { method: 'POST' });
diff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.ts
index f5ffe56faf..bdd46b0b3c 100644
--- a/invokeai/frontend/webv2/src/features/identity/index.ts
+++ b/invokeai/frontend/webv2/src/features/identity/index.ts
@@ -1,14 +1,21 @@
export * from './capabilities';
export {
+ AuthSessionUnavailableError,
completeAdminSetup,
+ configureIdentityAccountLifecycle,
ensureAuthSession,
+ ensureReadyAuthSession,
getAuthSession,
getUserStorageScope,
+ isLoginAttemptSupersededError,
+ LoginAttemptSupersededError,
loginWithCredentials,
logoutSession,
subscribeAuthSession,
useAuthSession,
type AuthSession,
+ type ReadyAuthSession,
+ type IdentityAccountLifecycle,
} from './session';
export type { IdentityTokenAdapter } from './core/tokenStorage';
export * from './transportAdapter';
@@ -25,7 +32,7 @@ export {
type UserUpdateRequest,
} from './data/api';
export { AccountMenu } from './ui/AccountMenu';
+export { AuthUnavailableScreen } from './ui/AuthUnavailableScreen';
export { LoginScreen } from './ui/LoginScreen';
-export { SessionExpiryGuard } from './ui/SessionExpiryGuard';
export { SetupScreen } from './ui/SetupScreen';
export { UsersPage } from './ui/UsersPage';
diff --git a/invokeai/frontend/webv2/src/features/identity/session.test.ts b/invokeai/frontend/webv2/src/features/identity/session.test.ts
new file mode 100644
index 0000000000..0d7a885100
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/identity/session.test.ts
@@ -0,0 +1,423 @@
+import { createAccountLifecycle, type AccountLifecycle } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LoginResult } from './data/api';
+import type * as sessionModule from './session';
+
+const testState = vi.hoisted(() => {
+ const events: string[] = [];
+ let token: string | null = null;
+
+ const tokenAdapter = {
+ clear: vi.fn(() => {
+ events.push('token.clear');
+ token = null;
+ }),
+ get: vi.fn(() => token),
+ set: vi.fn((nextToken: string) => {
+ events.push(`token.set:${nextToken}`);
+ token = nextToken;
+ }),
+ };
+
+ return {
+ events,
+ getToken: () => token,
+ reset: () => {
+ events.length = 0;
+ token = null;
+ tokenAdapter.clear.mockClear();
+ tokenAdapter.get.mockClear();
+ tokenAdapter.set.mockClear();
+ },
+ tokenAdapter,
+ };
+});
+
+const api = vi.hoisted(() => ({
+ getAuthStatus: vi.fn(),
+ getCurrentUser: vi.fn(),
+ login: vi.fn(),
+ logout: vi.fn(),
+ setupAdmin: vi.fn(),
+}));
+
+vi.mock('./core/tokenStorage', () => ({
+ browserIdentityTokenAdapter: testState.tokenAdapter,
+}));
+
+vi.mock('./data/api', () => api);
+
+const user = {
+ created_at: '2026-07-25T12:00:00Z',
+ display_name: 'Ada',
+ email: '[email protected]',
+ is_active: true,
+ is_admin: false,
+ last_login_at: '2026-07-25T12:00:00Z',
+ updated_at: '2026-07-25T12:00:00Z',
+ user_id: 'user-a',
+};
+
+const userB = {
+ ...user,
+ display_name: 'Grace',
+ email: '[email protected]',
+ user_id: 'user-b',
+};
+
+const createDeferred = <Value>(): {
+ promise: Promise<Value>;
+ reject: (reason?: unknown) => void;
+ resolve: (value: Value) => void;
+} => {
+ let reject!: (reason?: unknown) => void;
+ let resolve!: (value: Value) => void;
+ const promise = new Promise<Value>((resolvePromise, rejectPromise) => {
+ reject = rejectPromise;
+ resolve = resolvePromise;
+ });
+
+ return { promise, reject, resolve };
+};
+
+let session: typeof sessionModule;
+
+const createObservedLifecycle = (): {
+ lifecycle: AccountLifecycle;
+ port: sessionModule.IdentityAccountLifecycle;
+} => {
+ const lifecycle = createAccountLifecycle();
+
+ lifecycle.register({
+ clear: () => {
+ testState.events.push('cache.clear');
+ },
+ name: 'test-account-cache',
+ });
+
+ return {
+ lifecycle,
+ port: {
+ activate: (accountId, storageSuffix) => {
+ testState.events.push(`lifecycle.activate:${accountId}`);
+ return lifecycle.activate(accountId, storageSuffix);
+ },
+ invalidate: () => {
+ testState.events.push('lifecycle.invalidate');
+ return lifecycle.invalidate();
+ },
+ },
+ };
+};
+
+const resolveSignedOutMultiuserSession = async (): Promise<ReturnType<typeof createObservedLifecycle>> => {
+ const observed = createObservedLifecycle();
+
+ session.configureIdentityAccountLifecycle(observed.port);
+ await session.ensureAuthSession();
+ testState.events.length = 0;
+
+ return observed;
+};
+
+beforeEach(async () => {
+ vi.resetModules();
+ testState.reset();
+ api.getAuthStatus.mockReset();
+ api.getCurrentUser.mockReset();
+ api.login.mockReset();
+ api.logout.mockReset();
+ api.setupAdmin.mockReset();
+
+ api.getAuthStatus.mockResolvedValue({
+ admin_email: '[email protected]',
+ multiuser_enabled: true,
+ setup_required: false,
+ strict_password_checking: true,
+ });
+ api.login.mockImplementation(() => {
+ testState.events.push('api.login');
+ return Promise.resolve({ expires_in: 3600, token: 'token-a', user });
+ });
+ api.logout.mockResolvedValue({ success: true });
+
+ session = await import('./session');
+});
+
+describe('identity account transitions', () => {
+ it('invalidates old account state before installing a token and publishing a login', async () => {
+ await resolveSignedOutMultiuserSession();
+ const unsubscribe = session.subscribeAuthSession(() => {
+ const snapshot = session.getAuthSession();
+ testState.events.push(`publish:${snapshot.user?.user_id ?? 'signed-out'}:${snapshot.accountEpoch}`);
+ });
+
+ await session.loginWithCredentials(user.email, 'password', true);
+
+ const accountEpoch = session.getAuthSession().accountEpoch;
+ expect(testState.events).toEqual([
+ 'lifecycle.invalidate',
+ 'cache.clear',
+ 'token.clear',
+ expect.stringMatching(/^publish:signed-out:\d+$/),
+ 'api.login',
+ 'token.set:token-a',
+ 'lifecycle.activate:user-a',
+ 'cache.clear',
+ `publish:user-a:${accountEpoch}`,
+ ]);
+ expect(testState.getToken()).toBe('token-a');
+ unsubscribe();
+ });
+
+ it('clears account-owned state and the token before publishing transport expiry', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ testState.events.length = 0;
+ const unsubscribe = session.subscribeAuthSession(() => {
+ const snapshot = session.getAuthSession();
+ testState.events.push(`publish:${snapshot.user?.user_id ?? 'signed-out'}:${snapshot.accountEpoch}`);
+ });
+
+ session.handleUnauthorizedResponse();
+
+ const snapshot = session.getAuthSession();
+ expect(testState.events).toEqual([
+ 'lifecycle.invalidate',
+ 'cache.clear',
+ 'token.clear',
+ `publish:signed-out:${snapshot.accountEpoch}`,
+ ]);
+ expect(snapshot).toMatchObject({ sessionExpired: true, user: null });
+ expect(testState.getToken()).toBeNull();
+ unsubscribe();
+ });
+
+ it('completes local logout without waiting for the best-effort server request', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ testState.events.length = 0;
+ let resolveLogout: ((result: { success: boolean }) => void) | undefined;
+ api.logout.mockImplementation(() => {
+ testState.events.push('api.logout');
+ return new Promise((resolve) => {
+ resolveLogout = resolve;
+ });
+ });
+ const unsubscribe = session.subscribeAuthSession(() => {
+ const snapshot = session.getAuthSession();
+ testState.events.push(`publish:${snapshot.user?.user_id ?? 'signed-out'}:${snapshot.accountEpoch}`);
+ });
+
+ await session.logoutSession();
+
+ const snapshot = session.getAuthSession();
+ expect(testState.events).toEqual([
+ 'api.logout',
+ 'lifecycle.invalidate',
+ 'cache.clear',
+ 'token.clear',
+ `publish:signed-out:${snapshot.accountEpoch}`,
+ ]);
+ expect(snapshot).toMatchObject({ sessionExpired: false, user: null });
+ resolveLogout?.({ success: true });
+ unsubscribe();
+ });
+
+ it('rotates the epoch when the same user authenticates again', async () => {
+ const { lifecycle } = await resolveSignedOutMultiuserSession();
+
+ await session.loginWithCredentials(user.email, 'password', true);
+ const firstSession = session.getAuthSession();
+ const firstScope = lifecycle.capture();
+
+ api.login.mockResolvedValueOnce({ expires_in: 3600, token: 'token-a-refreshed', user });
+ await session.loginWithCredentials(user.email, 'new-password', false);
+
+ const secondSession = session.getAuthSession();
+ const secondScope = lifecycle.capture();
+ expect(secondSession.user?.user_id).toBe(firstSession.user?.user_id);
+ expect(secondSession.accountEpoch).toBeGreaterThan(firstSession.accountEpoch);
+ expect(secondScope.accountId).toBe(firstScope.accountId);
+ expect(secondScope).not.toBe(firstScope);
+ expect(firstScope.signal.aborted).toBe(true);
+ expect(lifecycle.isCurrent(firstScope)).toBe(false);
+ expect(lifecycle.isCurrent(secondScope)).toBe(true);
+ expect(testState.getToken()).toBe('token-a-refreshed');
+ });
+
+ it('rejects a profile completion owned by an expired account epoch', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ const oldEpoch = session.getAuthSession().accountEpoch;
+
+ await session.logoutSession();
+ session.setSessionUser({ ...user, display_name: 'Late User A' }, oldEpoch);
+
+ expect(session.getAuthSession().user).toBeNull();
+ });
+
+ it('fails closed when auth status is unavailable, even with a stored token', async () => {
+ testState.tokenAdapter.set('stored-token');
+ testState.events.length = 0;
+ api.getAuthStatus.mockRejectedValue(new Error('backend unavailable'));
+ const { lifecycle } = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle({
+ activate: (accountId, storageSuffix) => lifecycle.activate(accountId, storageSuffix),
+ invalidate: () => lifecycle.invalidate(),
+ });
+
+ const snapshot = await session.ensureAuthSession();
+
+ expect(snapshot).toMatchObject({
+ multiuserEnabled: false,
+ phase: 'unavailable',
+ user: null,
+ });
+ expect(lifecycle.capture()).toMatchObject({ accountId: null, storageSuffix: '' });
+ expect(testState.getToken()).toBe('stored-token');
+ expect(api.getCurrentUser).not.toHaveBeenCalled();
+ expect(() => session.getUserStorageScope()).toThrow(session.AuthSessionUnavailableError);
+ await expect(session.loginWithCredentials(user.email, 'password', true)).rejects.toBeInstanceOf(
+ session.AuthSessionUnavailableError
+ );
+ expect(api.login).not.toHaveBeenCalled();
+ expect(testState.getToken()).toBe('stored-token');
+ await expect(session.ensureReadyAuthSession()).rejects.toBeInstanceOf(session.AuthSessionUnavailableError);
+ });
+
+ it('recovers an unavailable stored-token session only after status and principal both resolve', async () => {
+ testState.tokenAdapter.set('stored-token');
+ api.getAuthStatus.mockRejectedValueOnce(new Error('backend unavailable'));
+ api.getCurrentUser.mockResolvedValue(user);
+ const { lifecycle, port } = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle(port);
+
+ expect((await session.ensureAuthSession()).phase).toBe('unavailable');
+
+ const recovered = await session.ensureReadyAuthSession();
+
+ expect(recovered).toMatchObject({
+ multiuserEnabled: true,
+ phase: 'ready',
+ sessionExpired: false,
+ user,
+ });
+ expect(lifecycle.capture()).toMatchObject({ accountId: user.user_id, storageSuffix: `:user:${user.user_id}` });
+ expect(session.getUserStorageScope()).toBe(`:user:${user.user_id}`);
+ expect(testState.getToken()).toBe('stored-token');
+ });
+
+ it('clears a stored token rejected after an auth-status outage and recovers to login', async () => {
+ const { ApiError } = await import('@platform/transport/http');
+ testState.tokenAdapter.set('stored-token');
+ api.getAuthStatus.mockRejectedValueOnce(new Error('backend unavailable'));
+ api.getCurrentUser.mockRejectedValueOnce(new ApiError('Unauthorized', 401));
+ const { lifecycle, port } = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle(port);
+
+ expect((await session.ensureAuthSession()).phase).toBe('unavailable');
+
+ const recovered = await session.ensureReadyAuthSession();
+
+ expect(recovered).toMatchObject({
+ multiuserEnabled: true,
+ phase: 'ready',
+ sessionExpired: true,
+ user: null,
+ });
+ expect(lifecycle.capture().accountId).toBeNull();
+ expect(testState.getToken()).toBeNull();
+ expect(() => session.getUserStorageScope()).toThrow(/without an authenticated user/);
+ });
+
+ it('treats a later 401 as rejection of the current stored credential while auth mode is unavailable', async () => {
+ testState.tokenAdapter.set('stored-token');
+ api.getAuthStatus.mockRejectedValue(new Error('backend unavailable'));
+ const { lifecycle, port } = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle(port);
+ await session.ensureAuthSession();
+
+ session.handleUnauthorizedResponse();
+
+ expect(session.getAuthSession()).toMatchObject({ phase: 'unavailable', sessionExpired: true, user: null });
+ expect(lifecycle.capture().accountId).toBeNull();
+ expect(testState.getToken()).toBeNull();
+
+ api.getAuthStatus.mockResolvedValue({
+ admin_email: '[email protected]',
+ multiuser_enabled: true,
+ setup_required: false,
+ strict_password_checking: true,
+ });
+ await expect(session.ensureReadyAuthSession()).resolves.toMatchObject({
+ phase: 'ready',
+ sessionExpired: true,
+ user: null,
+ });
+ });
+
+ it('lets the newest concurrent login win when an older response arrives last', async () => {
+ await resolveSignedOutMultiuserSession();
+ const first = createDeferred<LoginResult>();
+ const second = createDeferred<LoginResult>();
+ let firstSignal: AbortSignal | undefined;
+ api.login
+ .mockImplementationOnce((_request, signal: AbortSignal | undefined) => {
+ firstSignal = signal;
+ return first.promise;
+ })
+ .mockImplementationOnce(() => second.promise);
+
+ const firstOutcome = session.loginWithCredentials(user.email, 'password-a', true).catch((error) => error);
+ const secondLogin = session.loginWithCredentials(userB.email, 'password-b', false);
+
+ expect(firstSignal?.aborted).toBe(true);
+ second.resolve({ expires_in: 3600, token: 'token-b', user: userB });
+ await secondLogin;
+ first.resolve({ expires_in: 3600, token: 'token-a-late', user });
+
+ expect(await firstOutcome).toBeInstanceOf(session.LoginAttemptSupersededError);
+ expect(session.getAuthSession().user).toEqual(userB);
+ expect(testState.getToken()).toBe('token-b');
+ });
+
+ it('does not let a pending login undo logout', async () => {
+ await resolveSignedOutMultiuserSession();
+ const pending = createDeferred<LoginResult>();
+ let signal: AbortSignal | undefined;
+ api.login.mockImplementationOnce((_request, nextSignal: AbortSignal | undefined) => {
+ signal = nextSignal;
+ return pending.promise;
+ });
+ const loginOutcome = session.loginWithCredentials(user.email, 'password', true).catch((error) => error);
+
+ await session.logoutSession();
+ pending.resolve({ expires_in: 3600, token: 'late-token', user });
+
+ expect(signal?.aborted).toBe(true);
+ expect(await loginOutcome).toBeInstanceOf(session.LoginAttemptSupersededError);
+ expect(session.getAuthSession()).toMatchObject({ sessionExpired: false, user: null });
+ expect(testState.getToken()).toBeNull();
+ });
+
+ it('does not let a pending login undo transport expiry', async () => {
+ await resolveSignedOutMultiuserSession();
+ const pending = createDeferred<LoginResult>();
+ let signal: AbortSignal | undefined;
+ api.login.mockImplementationOnce((_request, nextSignal: AbortSignal | undefined) => {
+ signal = nextSignal;
+ return pending.promise;
+ });
+ const loginOutcome = session.loginWithCredentials(user.email, 'password', true).catch((error) => error);
+
+ session.handleUnauthorizedResponse();
+ pending.resolve({ expires_in: 3600, token: 'late-token', user });
+
+ expect(signal?.aborted).toBe(true);
+ expect(await loginOutcome).toBeInstanceOf(session.LoginAttemptSupersededError);
+ expect(session.getAuthSession()).toMatchObject({ sessionExpired: true, user: null });
+ expect(testState.getToken()).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/identity/session.ts b/invokeai/frontend/webv2/src/features/identity/session.ts
index 36b397cd9b..011d729ce6 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.ts
@@ -1,6 +1,5 @@
import { createExternalStore } from '@platform/state/externalStore';
import { ApiError } from '@platform/transport/http';
-import { socketHub } from '@platform/transport/socketHub';
import { shouldExpireUnauthorizedSession } from './core/sessionPolicy';
import { browserIdentityTokenAdapter } from './core/tokenStorage';
@@ -8,13 +7,16 @@ import { getAuthStatus, getCurrentUser, login, logout, setupAdmin, type AuthStat
/**
* Session-lived auth state shared by the router guards and shell chrome. When
- * multi-user is disabled on the backend the snapshot stays at its defaults
- * (`multiuserEnabled: false`, `user: null`) and the entire auth surface — login
- * screen, user menu, expiry handling — stays dormant.
+ * multi-user is disabled on the backend, the resolved snapshot keeps the
+ * entire auth surface — login screen, user menu, expiry handling — dormant.
+ * Until that mode is known, `phase` keeps the otherwise conservative boolean
+ * defaults from being interpreted as a single-user grant.
*/
export interface AuthSession {
- /** 'unknown' until the first `/auth/status` round-trip resolves. */
- phase: 'unknown' | 'ready';
+ /** Remount key for every authenticated lifetime, including same-user logins. */
+ accountEpoch: number;
+ /** Auth mode is never inferred when `/auth/status` cannot be resolved. */
+ phase: 'unknown' | 'unavailable' | 'ready';
multiuserEnabled: boolean;
setupRequired: boolean;
strictPasswordChecking: boolean;
@@ -24,6 +26,7 @@ export interface AuthSession {
}
const store = createExternalStore<AuthSession>({
+ accountEpoch: 0,
multiuserEnabled: false,
phase: 'unknown',
sessionExpired: false,
@@ -32,6 +35,26 @@ const store = createExternalStore<AuthSession>({
user: null,
});
+export interface IdentityAccountLifecycle {
+ activate(accountId: string, storageSuffix?: string): { readonly epoch: number };
+ invalidate(): { readonly epoch: number };
+}
+
+let accountLifecycle: IdentityAccountLifecycle | null = null;
+
+/** Selected once by the App composition root before session resolution. */
+export const configureIdentityAccountLifecycle = (lifecycle: IdentityAccountLifecycle): void => {
+ accountLifecycle = lifecycle;
+};
+
+const getAccountLifecycle = (): IdentityAccountLifecycle => {
+ if (!accountLifecycle) {
+ throw new Error('Identity account lifecycle has not been configured by the App composition root.');
+ }
+
+ return accountLifecycle;
+};
+
export const useAuthSession = (): AuthSession => store.useSnapshot();
/**
@@ -45,16 +68,24 @@ export const getAuthSession = (): AuthSession => store.getSnapshot();
export const subscribeAuthSession = (listener: () => void): (() => void) => store.subscribe(listener);
/**
- * Sticky across sign-out: a debounced autosave can still fire during the
- * logout transition, and it must land in the bucket of the user whose data
- * was loaded — never the shared single-user bucket.
+ * Compatibility scope for synchronous settings/storage callers. Long-lived
+ * async work must capture `AccountScope.storageSuffix` from the App-composed
+ * lifecycle instead of consulting this mutable value after an await.
*/
let activeUserScope = '';
const setActiveUserScope = (user: UserDTO | null): void => {
- if (user !== null) {
- activeUserScope = `:user:${user.user_id}`;
+ activeUserScope = user === null ? '' : `:user:${user.user_id}`;
+};
+
+const activateResolvedAccount = (multiuserEnabled: boolean, user: UserDTO | null): number => {
+ if (!multiuserEnabled) {
+ return getAccountLifecycle().activate('single-user').epoch;
}
+
+ return user
+ ? getAccountLifecycle().activate(user.user_id, `:user:${user.user_id}`).epoch
+ : getAccountLifecycle().invalidate().epoch;
};
/**
@@ -62,22 +93,101 @@ const setActiveUserScope = (user: UserDTO | null): void => {
* preferences, personal API keys — see the spec's State Ownership section).
* Empty in single-user mode, so existing keys keep working unchanged.
*/
-export const getUserStorageScope = (): string => (store.getSnapshot().multiuserEnabled ? activeUserScope : '');
+export const getUserStorageScope = (): string => {
+ const session = store.getSnapshot();
-const fetchAuthStatus = async (): Promise<AuthStatus> => {
- try {
- return await getAuthStatus();
- } catch {
- // Backend unreachable: let the shell mount in single-user shape. The
- // connection banner reports the outage, and a 401 once the backend returns
- // in multi-user mode routes through the session-expiry path to login.
- return { admin_email: null, multiuser_enabled: false, setup_required: false, strict_password_checking: false };
+ if (session.phase !== 'ready') {
+ throw new AuthSessionUnavailableError();
+ }
+
+ if (!session.multiuserEnabled) {
+ return '';
+ }
+
+ if (session.user === null || activeUserScope === '') {
+ throw new Error('Account-owned storage is unavailable without an authenticated user.');
}
+
+ return activeUserScope;
+};
+
+export class AuthSessionUnavailableError extends Error {
+ constructor() {
+ super('The backend authentication mode is currently unavailable.');
+ this.name = 'AuthSessionUnavailableError';
+ }
+}
+
+export class LoginAttemptSupersededError extends Error {
+ constructor() {
+ super('This sign-in attempt was superseded by a newer identity transition.');
+ this.name = 'LoginAttemptSupersededError';
+ }
+}
+
+export const isLoginAttemptSupersededError = (error: unknown): error is LoginAttemptSupersededError =>
+ error instanceof LoginAttemptSupersededError;
+
+interface LoginAttempt {
+ readonly controller: AbortController;
+}
+
+let activeLoginAttempt: LoginAttempt | null = null;
+
+const beginLoginAttempt = (): LoginAttempt => {
+ activeLoginAttempt?.controller.abort();
+
+ const attempt: LoginAttempt = { controller: new AbortController() };
+ activeLoginAttempt = attempt;
+
+ return attempt;
+};
+
+const cancelLoginAttempt = (): boolean => {
+ if (activeLoginAttempt === null) {
+ return false;
+ }
+
+ const attempt = activeLoginAttempt;
+ activeLoginAttempt = null;
+ attempt.controller.abort();
+
+ return true;
+};
+
+const isCurrentLoginAttempt = (attempt: LoginAttempt): boolean =>
+ activeLoginAttempt === attempt && !attempt.controller.signal.aborted;
+
+const publishUnavailableSession = (): AuthSession => {
+ cancelLoginAttempt();
+ setActiveUserScope(null);
+ const accountEpoch = getAccountLifecycle().invalidate().epoch;
+ store.patchSnapshot({
+ accountEpoch,
+ multiuserEnabled: false,
+ phase: 'unavailable',
+ setupRequired: false,
+ strictPasswordChecking: false,
+ user: null,
+ });
+
+ return store.getSnapshot();
};
const resolveSession = async (): Promise<AuthSession> => {
- const status = await fetchAuthStatus();
+ let status: AuthStatus;
+
+ try {
+ status = await getAuthStatus();
+ } catch {
+ // A network failure says nothing about the backend's auth mode. Publishing
+ // an unavailable state keeps every authenticated route and storage owner
+ // unmounted while allowing a later route retry to resolve the session.
+ return publishUnavailableSession();
+ }
+
let user: UserDTO | null = null;
+ let sessionExpired = false;
if (status.multiuser_enabled && !status.setup_required && browserIdentityTokenAdapter.get()) {
try {
@@ -85,15 +195,27 @@ const resolveSession = async (): Promise<AuthSession> => {
} catch (error) {
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
browserIdentityTokenAdapter.clear();
+ sessionExpired = true;
+ } else {
+ // The auth mode is known, but the principal is not. Treat this like a
+ // status outage instead of incorrectly presenting the user as signed
+ // out and making unscoped storage reachable.
+ return publishUnavailableSession();
}
- // Any other failure leaves `user` null; the route guard lands on login.
}
+ } else if (status.multiuser_enabled && !status.setup_required) {
+ // Preserve an expiry raised while auth status was unavailable so recovery
+ // can explain why the remembered session returned to the login screen.
+ sessionExpired = store.getSnapshot().sessionExpired;
}
setActiveUserScope(user);
+ const accountEpoch = activateResolvedAccount(status.multiuser_enabled, user);
store.patchSnapshot({
+ accountEpoch,
multiuserEnabled: status.multiuser_enabled,
phase: 'ready',
+ sessionExpired,
setupRequired: status.setup_required,
strictPasswordChecking: status.strict_password_checking,
user,
@@ -104,7 +226,7 @@ const resolveSession = async (): Promise<AuthSession> => {
let pendingResolve: Promise<AuthSession> | null = null;
-/** Resolve the session exactly once per app load; later calls reuse the snapshot. */
+/** Resolve once while pending; an unavailable snapshot is retryable. */
export const ensureAuthSession = (): Promise<AuthSession> => {
const current = store.getSnapshot();
@@ -119,29 +241,77 @@ export const ensureAuthSession = (): Promise<AuthSession> => {
return pendingResolve;
};
+export type ReadyAuthSession = AuthSession & { phase: 'ready' };
+
+/**
+ * Route-facing resolver. Unknown auth mode is an availability error, never an
+ * implicit single-user grant. Retrying the route retries session resolution.
+ */
+export const ensureReadyAuthSession = async (): Promise<ReadyAuthSession> => {
+ const session = await ensureAuthSession();
+
+ if (session.phase !== 'ready') {
+ throw new AuthSessionUnavailableError();
+ }
+
+ return session as ReadyAuthSession;
+};
+
export const loginWithCredentials = async (email: string, password: string, rememberMe: boolean): Promise<void> => {
- // A stale token must not ride along on the login request itself.
+ const session = store.getSnapshot();
+
+ if (session.phase !== 'ready' || !session.multiuserEnabled) {
+ throw new AuthSessionUnavailableError();
+ }
+
+ const attempt = beginLoginAttempt();
+
+ // Invalidate the old epoch before touching its token. This also protects a
+ // same-user reauthentication from completions started by the prior login.
+ const invalidatedEpoch = getAccountLifecycle().invalidate().epoch;
browserIdentityTokenAdapter.clear();
+ setActiveUserScope(null);
+ store.patchSnapshot({ accountEpoch: invalidatedEpoch, sessionExpired: false, user: null });
+
+ try {
+ const result = await login({ email, password, remember_me: rememberMe }, attempt.controller.signal);
+
+ if (!isCurrentLoginAttempt(attempt)) {
+ throw new LoginAttemptSupersededError();
+ }
- const result = await login({ email, password, remember_me: rememberMe });
+ browserIdentityTokenAdapter.set(result.token);
+ setActiveUserScope(result.user);
+ const accountEpoch = getAccountLifecycle().activate(result.user.user_id, `:user:${result.user.user_id}`).epoch;
+ store.patchSnapshot({ accountEpoch, sessionExpired: false, user: result.user });
+ } catch (error) {
+ if (!isCurrentLoginAttempt(attempt)) {
+ throw new LoginAttemptSupersededError();
+ }
- browserIdentityTokenAdapter.set(result.token);
- setActiveUserScope(result.user);
- store.patchSnapshot({ sessionExpired: false, user: result.user });
+ throw error;
+ } finally {
+ if (activeLoginAttempt === attempt) {
+ activeLoginAttempt = null;
+ }
+ }
};
-export const logoutSession = async (): Promise<void> => {
- try {
- await logout();
- } catch {
+export const logoutSession = (): Promise<void> => {
+ cancelLoginAttempt();
+
+ // apiFetch captures the current token synchronously. Let the best-effort
+ // request finish in the old account while local sign-out proceeds at once.
+ void logout().catch(() => {
// Tokens are stateless on the backend; local sign-out always wins.
- }
+ });
+ const accountEpoch = getAccountLifecycle().invalidate().epoch;
browserIdentityTokenAdapter.clear();
- // Tear down the shared socket so it does not linger authenticated as the
- // previous user; the next authenticated mount reconnects with a fresh token.
- socketHub.disconnect();
- store.patchSnapshot({ sessionExpired: false, user: null });
+ setActiveUserScope(null);
+ store.patchSnapshot({ accountEpoch, sessionExpired: false, user: null });
+
+ return Promise.resolve();
};
/** Create the initial admin account, then sign straight in with it. */
@@ -155,22 +325,29 @@ export const completeAdminSetup = async (
await loginWithCredentials(email, password, false);
};
-/** Reflect a profile edit (display name, password) into the session snapshot. */
-export const setSessionUser = (user: UserDTO): void => {
+/** Reflect a profile edit only into the authenticated lifetime that started it. */
+export const setSessionUser = (user: UserDTO, expectedAccountEpoch: number): void => {
+ const session = store.getSnapshot();
+
+ if (session.accountEpoch !== expectedAccountEpoch || session.user?.user_id !== user.user_id) {
+ return;
+ }
+
store.patchSnapshot({ user });
};
-// A 401 on any authenticated request means the stored token expired or was
-// revoked. Only react while an authenticated multi-user session is live, so
-// failed login attempts and single-user mode never trip it.
+// A 401 for the current stored credential invalidates its account lifetime.
+// Login requests carry no stored token, and known single-user mode stays inert.
export const handleUnauthorizedResponse = (): void => {
+ const canceledLogin = cancelLoginAttempt();
const session = store.getSnapshot();
- if (!shouldExpireUnauthorizedSession(session)) {
+ if (!canceledLogin && !shouldExpireUnauthorizedSession(session)) {
return;
}
+ const accountEpoch = getAccountLifecycle().invalidate().epoch;
browserIdentityTokenAdapter.clear();
- socketHub.disconnect();
- store.patchSnapshot({ sessionExpired: true, user: null });
+ setActiveUserScope(null);
+ store.patchSnapshot({ accountEpoch, sessionExpired: true, user: null });
};
diff --git a/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts b/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts
index 0184967fdf..1555bd3c61 100644
--- a/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts
@@ -1,3 +1,5 @@
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
import { describe, expect, it, vi } from 'vitest';
import type { IdentityTokenAdapter } from './core/tokenStorage';
@@ -17,12 +19,37 @@ describe('Identity transport auth adapter', () => {
},
};
const onUnauthorized = vi.fn();
- const adapter = createIdentityTransportAuthAdapter(testTokenAdapter, onUnauthorized);
+ let identity: AccountScope = {
+ accountId: 'a',
+ epoch: 1,
+ signal: new AbortController().signal,
+ storageSuffix: ':user:a',
+ };
+ const adapter = createIdentityTransportAuthAdapter(testTokenAdapter, onUnauthorized, {
+ capture: () => identity,
+ isCurrent: (candidate) => candidate === identity,
+ });
expect(adapter.getToken()).toBe('test-token');
+ expect(adapter.getIdentity()).toBe(identity);
testTokenAdapter.set('next-token');
expect(adapter.getToken()).toBe('next-token');
- adapter.onUnauthorized();
+ adapter.onUnauthorized('next-token', identity);
+ expect(onUnauthorized).toHaveBeenCalledOnce();
+
+ testTokenAdapter.set('newer-token');
+ adapter.onUnauthorized('next-token', identity);
+ expect(onUnauthorized).toHaveBeenCalledOnce();
+
+ testTokenAdapter.set('next-token');
+ const oldIdentity = identity;
+ identity = {
+ accountId: 'a',
+ epoch: 2,
+ signal: new AbortController().signal,
+ storageSuffix: ':user:a',
+ };
+ adapter.onUnauthorized('next-token', oldIdentity);
expect(onUnauthorized).toHaveBeenCalledOnce();
});
});
diff --git a/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts b/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts
index af5ed12a05..b9ad28186c 100644
--- a/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts
+++ b/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts
@@ -1,19 +1,41 @@
+import { captureAccountScope, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';
+
import type { IdentityTokenAdapter } from './core/tokenStorage';
import { browserIdentityTokenAdapter } from './core/tokenStorage';
import { handleUnauthorizedResponse } from './session';
export interface IdentityTransportAuthAdapter {
+ getIdentity(): unknown;
getToken(): string | null;
- onUnauthorized(): void;
+ onUnauthorized(rejectedToken: string, rejectedIdentity: unknown): void;
+}
+
+export interface IdentityAccountScopeAdapter {
+ capture(): AccountScope;
+ isCurrent(scope: AccountScope): boolean;
}
export const createIdentityTransportAuthAdapter = (
token: IdentityTokenAdapter,
- onUnauthorized: () => void
+ onUnauthorized: () => void,
+ account: IdentityAccountScopeAdapter = {
+ capture: captureAccountScope,
+ isCurrent: isAccountScopeCurrent,
+ }
): IdentityTransportAuthAdapter => ({
+ getIdentity: account.capture,
getToken: token.get,
- onUnauthorized,
+ onUnauthorized: (rejectedToken, rejectedIdentity) => {
+ if (
+ token.get() === rejectedToken &&
+ typeof rejectedIdentity === 'object' &&
+ rejectedIdentity !== null &&
+ account.isCurrent(rejectedIdentity as AccountScope)
+ ) {
+ onUnauthorized();
+ }
+ },
});
export const identityTransportAuthAdapter = createIdentityTransportAuthAdapter(
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx
index 71407e3a3a..87355c89d3 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx
@@ -29,10 +29,9 @@ export const AccountMenu = () => {
void navigate({ to: '/users' });
}, [navigate]);
- const signOut = useCallback(async () => {
- await logoutSession();
- await navigate({ to: '/login' });
- }, [navigate]);
+ const signOut = useCallback(() => {
+ void logoutSession();
+ }, []);
const openProfile = useCallback(() => setIsProfileOpen(true), []);
const closeProfile = useCallback(() => setIsProfileOpen(false), []);
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx
new file mode 100644
index 0000000000..355f1f24e2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx
@@ -0,0 +1,23 @@
+import { Button } from '@platform/ui/Button';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AuthScreen } from './AuthScreen';
+
+/**
+ * Fail-closed authentication availability boundary. This deliberately lives
+ * outside the workbench shell so no account-owned provider mounts before a
+ * retry has resolved the backend's auth mode and principal.
+ */
+export const AuthUnavailableScreen = ({ onRetry }: { onRetry: () => Promise<void> | void }) => {
+ const { t } = useTranslation();
+ const handleRetry = useCallback(() => {
+ void onRetry();
+ }, [onRetry]);
+
+ return (
+ <AuthScreen subtitle={t('widgets.serverStatus.disconnected')} title={t('common.somethingWentWrong')}>
+ <Button onClick={handleRetry}>{t('common.retry')}</Button>
+ </AuthScreen>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx
index db4ef3fff0..a69a869afc 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx
@@ -1,6 +1,6 @@
import { chakra, Checkbox, Input } from '@chakra-ui/react';
import { loginSchema } from '@features/identity/core/schemas';
-import { loginWithCredentials, useAuthSession } from '@features/identity/session';
+import { isLoginAttemptSupersededError, loginWithCredentials, useAuthSession } from '@features/identity/session';
import { useZodForm } from '@platform/react/useZodForm';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, Field } from '@platform/ui';
@@ -24,6 +24,13 @@ export const LoginScreen = () => {
try {
await loginWithCredentials(values.email, values.password, values.rememberMe);
} catch (error) {
+ // A second submit, logout, or expiry owns the newer identity
+ // transition. The stale submit should neither navigate nor flash an
+ // error over the winning transition.
+ if (isLoginAttemptSupersededError(error)) {
+ return;
+ }
+
throw new Error(getApiErrorMessage(error, t('auth.signInFailed')));
}
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsx b/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsx
index 822ddb441c..fe88f2e34b 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsx
@@ -116,7 +116,7 @@ const ProfileForm = ({ onClose, user }: { onClose: () => void; user: UserDTO })
try {
const updated = await updateCurrentUser(changes);
- setSessionUser(updated);
+ setSessionUser(updated, session.accountEpoch);
} catch (error) {
throw new Error(getApiErrorMessage(error, t('auth.couldNotUpdateAccount')));
}
@@ -124,7 +124,7 @@ const ProfileForm = ({ onClose, user }: { onClose: () => void; user: UserDTO })
notify.success(t('auth.accountUpdated'));
onClose();
}),
- [form, notify, onClose, t, user.display_name]
+ [form, notify, onClose, session.accountEpoch, t, user.display_name]
);
const handleDisplayNameChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => form.setValue('displayName', event.target.value),
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsx b/invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsx
deleted file mode 100644
index 0a21be6b7d..0000000000
--- a/invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useAuthSession } from '@features/identity/session';
-import { useNavigate } from '@tanstack/react-router';
-import { useEffect } from 'react';
-
-/**
- * Watches for mid-session token rejection (a 401 on any authenticated request)
- * and routes back to the login screen, which explains the expiry. Mounted once
- * inside the workbench route; renders nothing.
- */
-export const SessionExpiryGuard = () => {
- const session = useAuthSession();
- const navigate = useNavigate();
-
- useEffect(() => {
- if (session.multiuserEnabled && session.sessionExpired && session.user === null) {
- void navigate({ to: '/login' });
- }
- }, [navigate, session.multiuserEnabled, session.sessionExpired, session.user]);
-
- return null;
-};
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx
index 4efbc79a7c..66594a637f 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx
@@ -1,6 +1,6 @@
import { chakra, Input, Stack } from '@chakra-ui/react';
import { createSetupSchema, PASSWORD_RULES_HINT, type SetupFormValues } from '@features/identity/core/schemas';
-import { completeAdminSetup, useAuthSession } from '@features/identity/session';
+import { completeAdminSetup, isLoginAttemptSupersededError, useAuthSession } from '@features/identity/session';
import { useZodForm } from '@platform/react/useZodForm';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, Field } from '@platform/ui';
@@ -30,6 +30,10 @@ export const SetupScreen = () => {
try {
await completeAdminSetup(values.email, values.displayName.trim() || null, values.password);
} catch (error) {
+ if (isLoginAttemptSupersededError(error)) {
+ return;
+ }
+
throw new Error(getApiErrorMessage(error, t('auth.couldNotCreateAdmin')));
}
diff --git a/invokeai/frontend/webv2/src/features/models/data/api.test.ts b/invokeai/frontend/webv2/src/features/models/data/api.test.ts
index bf0cfcae40..2013fdb5c0 100644
--- a/invokeai/frontend/webv2/src/features/models/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/api.test.ts
@@ -27,12 +27,16 @@ describe('installModel', () => {
it('sends remote source credentials in a header instead of the URL', async () => {
const { installModel } = await import('./api');
+ const controller = new AbortController();
- await installModel({
- accessToken: 'secret-token',
- config: { name: 'Model' },
- source: 'https://example.test/model',
- });
+ await installModel(
+ {
+ accessToken: 'secret-token',
+ config: { name: 'Model' },
+ source: 'https://example.test/model',
+ },
+ controller.signal
+ );
const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
@@ -40,5 +44,63 @@ describe('installModel', () => {
expect(url).not.toContain('secret-token');
expect(init.headers).toEqual({ 'X-Model-Source-Access-Token': 'secret-token' });
expect(JSON.parse(init.body as string)).toEqual({ name: 'Model' });
+ expect(init.signal).toBe(controller.signal);
+ });
+});
+
+describe('account-owned model requests', () => {
+ beforeEach(() => {
+ mocks.request.mockReset().mockResolvedValue(new Response());
+ mocks.apiFetchJson.mockReset().mockResolvedValue([]);
+ });
+
+ it('forwards one account signal through lookup, credentials, relationships, maintenance, and image requests', async () => {
+ const {
+ addModelRelationship,
+ deleteOrphanedModels,
+ getExternalProviderConfigs,
+ getHuggingFaceModels,
+ pruneCompletedModelInstalls,
+ updateModelImage,
+ } = await import('./api');
+ const controller = new AbortController();
+ const image = new Blob(['image'], { type: 'image/png' });
+
+ await getHuggingFaceModels('owner/repo', controller.signal);
+ await getExternalProviderConfigs(controller.signal);
+ await deleteOrphanedModels(['/models/orphan'], controller.signal);
+ await addModelRelationship('model-a', 'model-b', controller.signal);
+ await pruneCompletedModelInstalls(controller.signal);
+ await updateModelImage('model-a', image, controller.signal);
+
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(
+ 1,
+ '/api/v2/models/hugging_face?hugging_face_repo=owner%2Frepo',
+ { signal: controller.signal }
+ );
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/app/external_providers/config', {
+ signal: controller.signal,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(3, '/api/v2/models/sync/orphaned', {
+ body: JSON.stringify({ paths: ['/models/orphan'] }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'DELETE',
+ signal: controller.signal,
+ });
+ expect(mocks.request).toHaveBeenNthCalledWith(1, '/api/v1/model_relationships/', {
+ body: JSON.stringify({ model_key_1: 'model-a', model_key_2: 'model-b' }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: controller.signal,
+ });
+ expect(mocks.request).toHaveBeenNthCalledWith(2, '/api/v2/models/install', {
+ method: 'DELETE',
+ signal: controller.signal,
+ });
+ expect(mocks.request).toHaveBeenNthCalledWith(
+ 3,
+ '/api/v2/models/i/model-a/image',
+ expect.objectContaining({ method: 'PATCH', signal: controller.signal })
+ );
});
});
diff --git a/invokeai/frontend/webv2/src/features/models/data/api.ts b/invokeai/frontend/webv2/src/features/models/data/api.ts
index b9a04121df..f3c1b27347 100644
--- a/invokeai/frontend/webv2/src/features/models/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/api.ts
@@ -18,62 +18,65 @@ import { browserModelsDataPort } from './transport';
const MODELS_BASE = '/api/v2/models';
const { buildUrl, request, requestJson } = browserModelsDataPort;
-export const listModels = async (): Promise<ModelConfig[]> => {
- const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/`);
+export const listModels = async (signal?: AbortSignal): Promise<ModelConfig[]> => {
+ const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/`, { signal });
return body.models ?? [];
};
/** Models whose database record points at a file that no longer exists. */
-export const listMissingModels = async (): Promise<ModelConfig[]> => {
- const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`);
+export const listMissingModels = async (signal?: AbortSignal): Promise<ModelConfig[]> => {
+ const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`, { signal });
return body.models ?? [];
};
/** Absolute server path of the models directory; relative model `path`s resolve against it. */
-export const getModelsDir = (): Promise<string> => requestJson<string>(`${MODELS_BASE}/models_dir`);
+export const getModelsDir = (signal?: AbortSignal): Promise<string> =>
+ requestJson<string>(`${MODELS_BASE}/models_dir`, { signal });
export const getModel = (key: string): Promise<ModelConfig> =>
requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`);
-export const updateModel = (key: string, changes: ModelRecordChanges): Promise<ModelConfig> =>
+export const updateModel = (key: string, changes: ModelRecordChanges, signal?: AbortSignal): Promise<ModelConfig> =>
requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, {
body: JSON.stringify(changes),
method: 'PATCH',
+ signal,
});
-export const deleteModel = async (key: string): Promise<void> => {
- await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, { method: 'DELETE' });
+export const deleteModel = async (key: string, signal?: AbortSignal): Promise<void> => {
+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, { method: 'DELETE', signal });
};
-export const bulkDeleteModels = (keys: string[]): Promise<BulkDeleteModelsResponse> =>
+export const bulkDeleteModels = (keys: string[], signal?: AbortSignal): Promise<BulkDeleteModelsResponse> =>
requestJson<BulkDeleteModelsResponse>(`${MODELS_BASE}/i/bulk_delete`, {
body: JSON.stringify({ keys }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
+ signal,
});
/** Re-probe the model files to refresh auto-detected base/type/format. */
-export const reidentifyModel = (key: string): Promise<ModelConfig> =>
- requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}/reidentify`, { method: 'POST' });
+export const reidentifyModel = (key: string, signal?: AbortSignal): Promise<ModelConfig> =>
+ requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}/reidentify`, { method: 'POST', signal });
-export const convertModelToDiffusers = (key: string): Promise<ModelConfig> =>
- requestJson<ModelConfig>(`${MODELS_BASE}/convert/${encodeURIComponent(key)}`, { method: 'PUT' });
+export const convertModelToDiffusers = (key: string, signal?: AbortSignal): Promise<ModelConfig> =>
+ requestJson<ModelConfig>(`${MODELS_BASE}/convert/${encodeURIComponent(key)}`, { method: 'PUT', signal });
/** Stable URL for a model's cover image; cache-busted via updated marker. */
export const getModelImageUrl = (key: string, cacheKey?: string): string =>
buildUrl(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image${cacheKey ? `?t=${encodeURIComponent(cacheKey)}` : ''}`);
-export const updateModelImage = async (key: string, image: Blob): Promise<void> => {
+export const updateModelImage = async (key: string, image: Blob, signal?: AbortSignal): Promise<void> => {
const formData = new FormData();
formData.append('image', image);
- await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { body: formData, method: 'PATCH' });
+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { body: formData, method: 'PATCH', signal });
};
-export const deleteModelImage = async (key: string): Promise<void> => {
- await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { method: 'DELETE' });
+export const deleteModelImage = async (key: string, signal?: AbortSignal): Promise<void> => {
+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { method: 'DELETE', signal });
};
export interface InstallModelRequest {
@@ -85,12 +88,10 @@ export interface InstallModelRequest {
config?: ModelRecordChanges;
}
-export const installModel = ({
- accessToken,
- config,
- inplace,
- source,
-}: InstallModelRequest): Promise<ModelInstallJob> => {
+export const installModel = (
+ { accessToken, config, inplace, source }: InstallModelRequest,
+ signal?: AbortSignal
+): Promise<ModelInstallJob> => {
const params = new URLSearchParams({ source });
const headers: HeadersInit = {};
@@ -106,87 +107,111 @@ export const installModel = ({
body: JSON.stringify(config ?? {}),
headers,
method: 'POST',
+ signal,
});
};
-export const listModelInstalls = (): Promise<ModelInstallJob[]> =>
- requestJson<ModelInstallJob[]>(`${MODELS_BASE}/install`);
+export const listModelInstalls = (signal?: AbortSignal): Promise<ModelInstallJob[]> =>
+ requestJson<ModelInstallJob[]>(`${MODELS_BASE}/install`, { signal });
-export const cancelModelInstall = async (id: number): Promise<void> => {
- await request(`${MODELS_BASE}/install/${id}`, { method: 'DELETE' });
+export const cancelModelInstall = async (id: number, signal?: AbortSignal): Promise<void> => {
+ await request(`${MODELS_BASE}/install/${id}`, { method: 'DELETE', signal });
};
-export const pauseModelInstall = (id: number): Promise<ModelInstallJob> =>
- requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/pause`, { method: 'POST' });
+export const pauseModelInstall = (id: number, signal?: AbortSignal): Promise<ModelInstallJob> =>
+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/pause`, { method: 'POST', signal });
-export const resumeModelInstall = (id: number): Promise<ModelInstallJob> =>
- requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/resume`, { method: 'POST' });
+export const resumeModelInstall = (id: number, signal?: AbortSignal): Promise<ModelInstallJob> =>
+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/resume`, { method: 'POST', signal });
-export const restartFailedModelInstall = (id: number): Promise<ModelInstallJob> =>
- requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_failed`, { method: 'POST' });
+export const restartFailedModelInstall = (id: number, signal?: AbortSignal): Promise<ModelInstallJob> =>
+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_failed`, { method: 'POST', signal });
/** Restart a single download part (by its file URL) of an install job. */
-export const restartModelInstallFile = (id: number, fileSource: string): Promise<ModelInstallJob> =>
+export const restartModelInstallFile = (
+ id: number,
+ fileSource: string,
+ signal?: AbortSignal
+): Promise<ModelInstallJob> =>
requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_file`, {
body: JSON.stringify(fileSource),
method: 'POST',
+ signal,
});
-export const pruneCompletedModelInstalls = async (): Promise<void> => {
- await request(`${MODELS_BASE}/install`, { method: 'DELETE' });
+export const pruneCompletedModelInstalls = async (signal?: AbortSignal): Promise<void> => {
+ await request(`${MODELS_BASE}/install`, { method: 'DELETE', signal });
};
-export const scanFolderForModels = (scanPath: string): Promise<FoundModel[]> =>
- requestJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`);
+export const scanFolderForModels = (scanPath: string, signal?: AbortSignal): Promise<FoundModel[]> =>
+ requestJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`, { signal });
-export const getHuggingFaceModels = (repo: string): Promise<HuggingFaceModels> =>
- requestJson<HuggingFaceModels>(`${MODELS_BASE}/hugging_face?hugging_face_repo=${encodeURIComponent(repo)}`);
+export const getHuggingFaceModels = (repo: string, signal?: AbortSignal): Promise<HuggingFaceModels> =>
+ requestJson<HuggingFaceModels>(`${MODELS_BASE}/hugging_face?hugging_face_repo=${encodeURIComponent(repo)}`, {
+ signal,
+ });
-export const getStarterModels = (): Promise<StarterModelResponse> =>
- requestJson<StarterModelResponse>(`${MODELS_BASE}/starter_models`);
+export const getStarterModels = (signal?: AbortSignal): Promise<StarterModelResponse> =>
+ requestJson<StarterModelResponse>(`${MODELS_BASE}/starter_models`, { signal });
-export const getHFTokenStatus = (): Promise<HFTokenStatus> => requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`);
+export const getHFTokenStatus = (signal?: AbortSignal): Promise<HFTokenStatus> =>
+ requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { signal });
-export const setHFToken = (token: string): Promise<HFTokenStatus> =>
- requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { body: JSON.stringify({ token }), method: 'POST' });
+export const setHFToken = (token: string, signal?: AbortSignal): Promise<HFTokenStatus> =>
+ requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, {
+ body: JSON.stringify({ token }),
+ method: 'POST',
+ signal,
+ });
-export const resetHFToken = (): Promise<HFTokenStatus> =>
- requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { method: 'DELETE' });
+export const resetHFToken = (signal?: AbortSignal): Promise<HFTokenStatus> =>
+ requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { method: 'DELETE', signal });
-export const getOrphanedModels = (): Promise<OrphanedModelInfo[]> =>
- requestJson<OrphanedModelInfo[]>(`${MODELS_BASE}/sync/orphaned`);
+export const getOrphanedModels = (signal?: AbortSignal): Promise<OrphanedModelInfo[]> =>
+ requestJson<OrphanedModelInfo[]>(`${MODELS_BASE}/sync/orphaned`, { signal });
-export const deleteOrphanedModels = (paths: string[]): Promise<DeleteOrphanedModelsResponse> =>
+export const deleteOrphanedModels = (paths: string[], signal?: AbortSignal): Promise<DeleteOrphanedModelsResponse> =>
requestJson<DeleteOrphanedModelsResponse>(`${MODELS_BASE}/sync/orphaned`, {
body: JSON.stringify({ paths }),
headers: { 'Content-Type': 'application/json' },
method: 'DELETE',
+ signal,
});
-export const emptyModelCache = async (): Promise<void> => {
- await request(`${MODELS_BASE}/empty_model_cache`, { method: 'POST' });
+export const emptyModelCache = async (signal?: AbortSignal): Promise<void> => {
+ await request(`${MODELS_BASE}/empty_model_cache`, { method: 'POST', signal });
};
/** Model relationships: bidirectional "related model" links between configs. */
const RELATIONSHIPS_BASE = '/api/v1/model_relationships';
-export const getRelatedModelKeys = (key: string): Promise<string[]> =>
- requestJson<string[]>(`${RELATIONSHIPS_BASE}/i/${encodeURIComponent(key)}`);
+export const getRelatedModelKeys = (key: string, signal?: AbortSignal): Promise<string[]> =>
+ requestJson<string[]>(`${RELATIONSHIPS_BASE}/i/${encodeURIComponent(key)}`, { signal });
-export const addModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {
+export const addModelRelationship = async (
+ modelKey1: string,
+ modelKey2: string,
+ signal?: AbortSignal
+): Promise<void> => {
await request(`${RELATIONSHIPS_BASE}/`, {
body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
+ signal,
});
};
-export const removeModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {
+export const removeModelRelationship = async (
+ modelKey1: string,
+ modelKey2: string,
+ signal?: AbortSignal
+): Promise<void> => {
await request(`${RELATIONSHIPS_BASE}/`, {
body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),
headers: { 'Content-Type': 'application/json' },
method: 'DELETE',
+ signal,
});
};
@@ -200,19 +225,25 @@ export interface ExternalProviderConfig {
base_url: string | null;
}
-export const getExternalProviderConfigs = (): Promise<ExternalProviderConfig[]> =>
- requestJson<ExternalProviderConfig[]>(`${EXTERNAL_PROVIDERS_BASE}/config`);
+export const getExternalProviderConfigs = (signal?: AbortSignal): Promise<ExternalProviderConfig[]> =>
+ requestJson<ExternalProviderConfig[]>(`${EXTERNAL_PROVIDERS_BASE}/config`, { signal });
export const setExternalProviderConfig = (
providerId: string,
- config: { api_key?: string; base_url?: string | null }
+ config: { api_key?: string; base_url?: string | null },
+ signal?: AbortSignal
): Promise<ExternalProviderConfig> =>
requestJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {
body: JSON.stringify(config),
method: 'POST',
+ signal,
});
-export const resetExternalProviderConfig = (providerId: string): Promise<ExternalProviderConfig> =>
+export const resetExternalProviderConfig = (
+ providerId: string,
+ signal?: AbortSignal
+): Promise<ExternalProviderConfig> =>
requestJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {
method: 'DELETE',
+ signal,
});
diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
index 5cc1b5ca96..f58138d2ce 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
@@ -1,5 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((settle) => {
+ resolve = settle;
+ });
+
+ return { promise, resolve };
+};
+
const dependencies = vi.hoisted(() => ({
listModelInstalls: vi.fn(),
refreshModels: vi.fn(),
@@ -61,4 +70,53 @@ describe('model install event interpretation', () => {
await vi.advanceTimersByTimeAsync(250);
expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
});
+
+ it('drops a stale refresh without releasing the replacement account refresh', async () => {
+ const first = deferred<Array<{ id: number; source: string; status: 'waiting' }>>();
+ const second = deferred<Array<{ id: number; source: string; status: 'waiting' }>>();
+
+ dependencies.listModelInstalls.mockReset().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+
+ const store = await import('./installsStore');
+ const { accountLifecycle } = await import('@platform/state/accountLifecycle');
+ const staleRefresh = store.refreshInstalls();
+
+ accountLifecycle.invalidate();
+
+ expect(store.getInstallsSnapshot()).toEqual({ error: null, jobs: [], status: 'idle' });
+
+ const currentRefresh = store.refreshInstalls();
+
+ first.resolve([{ id: 1, source: 'old/account', status: 'waiting' }]);
+ await staleRefresh;
+
+ expect(store.getInstallsSnapshot()).toEqual({ error: null, jobs: [], status: 'loading' });
+ expect(store.refreshInstalls()).toBe(currentRefresh);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+
+ second.resolve([{ id: 2, source: 'new/account', status: 'waiting' }]);
+ await currentRefresh;
+
+ expect(store.getInstallsSnapshot()).toEqual({
+ error: null,
+ jobs: [{ id: 2, source: 'new/account', status: 'waiting' }],
+ status: 'loaded',
+ });
+ });
+
+ it('ignores socket events owned by an expired account scope', async () => {
+ const store = await import('./installsStore');
+ const { accountLifecycle } = await import('@platform/state/accountLifecycle');
+ const owner = accountLifecycle.capture();
+
+ accountLifecycle.invalidate();
+ store.handleModelInstallSocketEvent(
+ 'model_install_download_progress',
+ { bytes: 25, id: 7, total_bytes: 100 },
+ owner
+ );
+
+ expect(store.getInstallProgress(7)).toBeNull();
+ expect(store.getInstallsSnapshot()).toEqual({ error: null, jobs: [], status: 'idle' });
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
index 7284f193fc..a6b430e996 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
@@ -1,5 +1,11 @@
import type { ModelInstallJob, ModelInstallStatus } from '@features/models/core/types';
+import {
+ type AccountScope,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';
import { listModelInstalls } from './api';
@@ -39,8 +45,11 @@ export interface InstallOutcome {
const REFRESH_COALESCE_MS = 250;
const OUTCOME_LIMIT = 16;
-const store = createExternalStore<InstallsSnapshot>({ error: null, jobs: [], status: 'idle' });
-const outcomesStore = createExternalStore<{ outcomes: InstallOutcome[] }>({ outcomes: [] });
+const EMPTY_INSTALLS_SNAPSHOT: InstallsSnapshot = { error: null, jobs: [], status: 'idle' };
+const EMPTY_INSTALL_OUTCOMES: { outcomes: InstallOutcome[] } = { outcomes: [] };
+
+const store = createExternalStore<InstallsSnapshot>(EMPTY_INSTALLS_SNAPSHOT);
+const outcomesStore = createExternalStore<{ outcomes: InstallOutcome[] }>(EMPTY_INSTALL_OUTCOMES);
let nextOutcomeId = 1;
const progressByJobId = createKeyedTransientStore<number, InstallDownloadProgress>();
@@ -48,15 +57,35 @@ const progressByJobId = createKeyedTransientStore<number, InstallDownloadProgres
let inflightRefresh: Promise<void> | null = null;
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
-export const refreshInstalls = (): Promise<void> => {
+registerAccountOwnedResource({
+ clear: () => {
+ if (refreshTimer !== null) {
+ clearTimeout(refreshTimer);
+ refreshTimer = null;
+ }
+
+ inflightRefresh = null;
+ nextOutcomeId = 1;
+ progressByJobId.clear();
+ outcomesStore.setSnapshot(EMPTY_INSTALL_OUTCOMES);
+ store.setSnapshot(EMPTY_INSTALLS_SNAPSHOT);
+ },
+ name: 'model-installs',
+});
+
+export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Promise<void> => {
if (inflightRefresh) {
return inflightRefresh;
}
store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
- inflightRefresh = listModelInstalls()
+ const refresh = listModelInstalls(owner.signal)
.then((jobs) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
const activeJobIds = new Set(jobs.map((job) => job.id));
for (const [jobId] of progressByJobId.entries()) {
@@ -68,15 +97,22 @@ export const refreshInstalls = (): Promise<void> => {
store.patchSnapshot({ error: null, jobs, status: 'loaded' });
})
.catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: error instanceof Error ? error.message : 'Failed to load install queue.',
status: store.getSnapshot().jobs.length > 0 ? 'loaded' : 'error',
});
})
.finally(() => {
- inflightRefresh = null;
+ if (inflightRefresh === refresh) {
+ inflightRefresh = null;
+ }
});
+ inflightRefresh = refresh;
return inflightRefresh;
};
@@ -162,7 +198,15 @@ export const MODEL_INSTALL_SOCKET_EVENTS = [
export type ModelInstallSocketEvent = (typeof MODEL_INSTALL_SOCKET_EVENTS)[number];
/** Socket sink — wired into the backend socket by the queue coordinator. */
-export const handleModelInstallSocketEvent = (event: ModelInstallSocketEvent, payload: unknown): void => {
+export const handleModelInstallSocketEvent = (
+ event: ModelInstallSocketEvent,
+ payload: unknown,
+ owner: AccountScope = captureAccountScope()
+): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
const data = payload as ModelInstallSocketPayload;
if (typeof data?.id !== 'number') {
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.ts
index fcd275fc60..9584a76dfa 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export interface ModelLoadInfo {
@@ -41,6 +42,11 @@ export const modelLoadActivitySink: ModelLoadActivitySink = {
},
};
+registerAccountOwnedResource({
+ clear: modelLoadActivitySink.reset,
+ name: 'model-load-activity',
+});
+
export const useModelLoads = (): ModelLoadInfo[] => store.useSelector((snapshot) => snapshot.activeLoads);
export const getModelLoads = (): ModelLoadInfo[] => store.getSnapshot().activeLoads;
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
index 7ee7e5a7b6..84d0882d7b 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
@@ -1,3 +1,5 @@
+import type { ModelConfig } from '@features/models/core/types';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
const api = vi.hoisted(() => ({
@@ -42,4 +44,51 @@ describe('models store loading', () => {
expect(getModelsSnapshot().models.map((model) => model.key)).toEqual(['model-key']);
expect(api.listModels).toHaveBeenCalledTimes(2);
});
+
+ it('keeps the new account request authoritative when the old request resolves last', async () => {
+ const account = await import('@platform/state/accountLifecycle');
+ account.accountLifecycle.activate('user-a');
+ const modelsStore = await import('./modelsStore');
+ let resolveA: ((value: ModelConfig[]) => void) | undefined;
+ let resolveB: ((value: ModelConfig[]) => void) | undefined;
+ api.listModels
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveA = resolve;
+ })
+ )
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveB = resolve;
+ })
+ );
+ const userARefresh = modelsStore.refreshModels();
+
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b');
+ const userBRefresh = modelsStore.refreshModels();
+
+ resolveA?.([]);
+ await userARefresh;
+ expect(modelsStore.refreshModels()).toBe(userBRefresh);
+
+ resolveB?.([
+ {
+ base: 'sdxl',
+ description: null,
+ file_size: 1,
+ format: 'checkpoint',
+ hash: 'hash-b',
+ key: 'model-b',
+ name: 'Model B',
+ path: 'model-b.safetensors',
+ source: 'model-b.safetensors',
+ source_type: 'path',
+ type: 'main',
+ },
+ ]);
+ await userBRefresh;
+
+ expect(modelsStore.getModelsSnapshot().models.map((model) => model.key)).toEqual(['model-b']);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
index 72b2fc9d66..0ad29d34e5 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
@@ -1,5 +1,11 @@
import type { ModelConfig } from '@features/models/core/types';
+import {
+ type AccountScope,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { getModelsDir, listMissingModels, listModels } from './api';
@@ -27,33 +33,46 @@ export interface ModelsSnapshot {
const EMPTY_MISSING_KEYS: ReadonlySet<string> = new Set<string>();
-const store = createExternalStore<ModelsSnapshot>({
+const EMPTY_MODELS_SNAPSHOT: ModelsSnapshot = {
coverImageVersions: {},
error: null,
missingModelKeys: EMPTY_MISSING_KEYS,
models: [],
modelsDir: null,
status: 'idle',
-});
+};
+const store = createExternalStore<ModelsSnapshot>(EMPTY_MODELS_SNAPSHOT);
let inflightRefresh: Promise<void> | null = null;
+registerAccountOwnedResource({
+ clear: () => {
+ inflightRefresh = null;
+ store.setSnapshot(EMPTY_MODELS_SNAPSHOT);
+ },
+ name: 'models-library',
+});
+
/** Re-fetch the library; concurrent calls share one request. */
-export const refreshModels = (): Promise<void> => {
+export const refreshModels = (owner: AccountScope = captureAccountScope()): Promise<void> => {
if (inflightRefresh) {
return inflightRefresh;
}
store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
- inflightRefresh = Promise.all([
- listModels(),
+ const refresh = Promise.all([
+ listModels(owner.signal),
// Missing-file detection is best-effort; never fail the whole library.
- listMissingModels().catch(() => [] as ModelConfig[]),
+ listMissingModels(owner.signal).catch(() => [] as ModelConfig[]),
// Static server config: fetched once, best-effort.
- store.getSnapshot().modelsDir ?? getModelsDir().catch(() => null),
+ store.getSnapshot().modelsDir ?? getModelsDir(owner.signal).catch(() => null),
])
.then(([models, missingModels, modelsDir]) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: null,
missingModelKeys:
@@ -64,15 +83,22 @@ export const refreshModels = (): Promise<void> => {
});
})
.catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: error instanceof Error ? error.message : 'Failed to load models.',
status: store.getSnapshot().models.length > 0 ? 'loaded' : 'error',
});
})
.finally(() => {
- inflightRefresh = null;
+ if (inflightRefresh === refresh) {
+ inflightRefresh = null;
+ }
});
+ inflightRefresh = refresh;
return inflightRefresh;
};
diff --git a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
index 9517cc097f..061ea702c4 100644
--- a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
@@ -1,5 +1,10 @@
import type { StarterModelResponse } from '@features/models/core/types';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { getStarterModels } from './api';
@@ -16,31 +21,52 @@ export interface StartersSnapshot {
error: string | null;
}
-const store = createExternalStore<StartersSnapshot>({ error: null, response: null, status: 'idle' });
+const EMPTY_STARTERS_SNAPSHOT: StartersSnapshot = { error: null, response: null, status: 'idle' };
+const store = createExternalStore<StartersSnapshot>(EMPTY_STARTERS_SNAPSHOT);
let inflightRefresh: Promise<void> | null = null;
+registerAccountOwnedResource({
+ clear: () => {
+ inflightRefresh = null;
+ store.setSnapshot(EMPTY_STARTERS_SNAPSHOT);
+ },
+ name: 'starter-models',
+});
+
export const refreshStarters = (): Promise<void> => {
if (inflightRefresh) {
return inflightRefresh;
}
+ const owner = captureAccountScope();
store.patchSnapshot({ status: store.getSnapshot().response ? 'loaded' : 'loading' });
- inflightRefresh = getStarterModels()
+ const refresh = getStarterModels(owner.signal)
.then((response) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({ error: null, response, status: 'loaded' });
})
.catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: error instanceof Error ? error.message : 'Failed to load starter models.',
status: store.getSnapshot().response ? 'loaded' : 'error',
});
})
.finally(() => {
- inflightRefresh = null;
+ if (inflightRefresh === refresh) {
+ inflightRefresh = null;
+ }
});
+ inflightRefresh = refresh;
return inflightRefresh;
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx
index 430925639f..24a7a79400 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx
@@ -4,17 +4,19 @@ import {
refreshInstalls,
} from '@features/models/data/installsStore';
import { refreshModels } from '@features/models/data/modelsStore';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getConnectionStatus, subscribeConnection } from '@platform/transport/connectionStore';
import { socketHub } from '@platform/transport/socketHub';
-import { useEffect } from 'react';
import { useInstallOutcomeToasts } from './useInstallOutcomeToasts';
/** Admin model-manager runtime: install socket events, reconnect refresh, and outcome toasts. */
export const ModelInstallRuntime = () => {
- useEffect(() => {
+ useMountEffect(() => {
+ const owner = captureAccountScope();
const detachers = MODEL_INSTALL_SOCKET_EVENTS.map((event) =>
- socketHub.on(event, (payload) => handleModelInstallSocketEvent(event, payload))
+ socketHub.on(event, (payload) => handleModelInstallSocketEvent(event, payload, owner))
);
return () => {
@@ -22,11 +24,12 @@ export const ModelInstallRuntime = () => {
detach();
}
};
- }, []);
+ });
- useEffect(() => {
+ useMountEffect(() => {
+ const owner = captureAccountScope();
const refreshOnConnect = () => {
- if (getConnectionStatus().status === 'connected') {
+ if (isAccountScopeCurrent(owner) && getConnectionStatus().status === 'connected') {
void refreshModels();
void refreshInstalls();
}
@@ -35,7 +38,7 @@ export const ModelInstallRuntime = () => {
refreshOnConnect();
return subscribeConnection(refreshOnConnect);
- }, []);
+ });
useInstallOutcomeToasts();
diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
index d3fdc60e63..73b63e3083 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
@@ -9,9 +9,16 @@ import { getExternalProviderConfigs, getHuggingFaceModels, scanFolderForModels }
import { ensureStartersLoaded, useStartersSelector } from '@features/models/data/startersStore';
import { updateModelsUi, useModelsUiSelector } from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { Button, Scrollable, Tooltip } from '@platform/ui';
import { DownloadIcon, FileIcon, FolderIcon, FolderSearchIcon, LinkIcon, SearchIcon } from 'lucide-react';
-import { useDeferredValue, useEffect, useMemo, useState } from 'react';
+import { useDeferredValue, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SiHuggingface } from 'react-icons/si';
@@ -76,16 +83,17 @@ export const AddModelsView = () => {
const [configuredExternalProviders, setConfiguredExternalProviders] = useState<ReadonlySet<string>>(() => new Set());
const [starterFilters, setStarterFilters] = useState<StarterModelFilters>(DEFAULT_STARTER_MODEL_FILTERS);
- useEffect(() => {
+ useMountEffect(() => {
ensureStartersLoaded();
- }, []);
+ });
- useEffect(() => {
- let isStale = false;
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+ let isMounted = true;
- getExternalProviderConfigs()
+ getExternalProviderConfigs(owner.signal)
.then((configs) => {
- if (isStale) {
+ if (!isMounted || !isAccountScopeCurrent(owner)) {
return;
}
@@ -94,7 +102,7 @@ export const AddModelsView = () => {
);
})
.catch((error) => {
- if (isStale) {
+ if (!isMounted || !isAccountScopeCurrent(owner)) {
return;
}
@@ -106,9 +114,9 @@ export const AddModelsView = () => {
});
return () => {
- isStale = true;
+ isMounted = false;
};
- }, [notify, t]);
+ });
const trimmed = query.trim();
const deferredTrimmed = useDeferredValue(trimmed);
@@ -167,10 +175,14 @@ export const AddModelsView = () => {
.map(({ model }) => model);
}, [deferredTrimmed, sourceModels, starterFilters]);
- const queueSources = async (entries: StarterInstallSource[]): Promise<number> => {
+ const queueSources = async (entries: StarterInstallSource[], owner: AccountScope): Promise<number> => {
let queued = 0;
for (const { config, source } of entries) {
+ if (!isAccountScopeCurrent(owner)) {
+ break;
+ }
+
if (await install({ config, source }, { silent: true })) {
queued += 1;
}
@@ -180,11 +192,13 @@ export const AddModelsView = () => {
};
const installStarter = async (model: StarterModel) => {
+ const owner = captureAccountScope();
const queued = await queueSources(
- getStarterModelInstallSources(model, { dependencySourcesToSkip: selectedBundleSources })
+ getStarterModelInstallSources(model, { dependencySourcesToSkip: selectedBundleSources }),
+ owner
);
- if (queued > 0) {
+ if (queued > 0 && isAccountScopeCurrent(owner)) {
notify.success(
t('models.modelInstallQueued'),
queued > 1 ? t('models.modelAndDependenciesQueued', { count: queued - 1, name: model.name }) : model.name
@@ -197,19 +211,24 @@ export const AddModelsView = () => {
return;
}
- setInstallingBundle(selectedBundle.name);
+ const owner = captureAccountScope();
+ const bundle = selectedBundle;
+
+ setInstallingBundle(bundle.name);
try {
- const queued = await queueSources(getStarterBundleInstallSources(selectedBundle));
+ const queued = await queueSources(getStarterBundleInstallSources(bundle), owner);
- if (queued > 0) {
+ if (queued > 0 && isAccountScopeCurrent(owner)) {
notify.success(
t('models.bundleInstallQueued'),
- t('models.bundleInstallQueuedDescription', { count: queued, name: selectedBundle.name })
+ t('models.bundleInstallQueuedDescription', { count: queued, name: bundle.name })
);
}
} finally {
- setInstallingBundle(null);
+ if (isAccountScopeCurrent(owner)) {
+ setInstallingBundle(null);
+ }
}
};
@@ -218,16 +237,19 @@ export const AddModelsView = () => {
return;
}
+ const owner = captureAccountScope();
+
setIsPulling(true);
try {
if (kind.looksRepo) {
- const lookup = await getHuggingFaceModels(trimmed);
+ const lookup = await getHuggingFaceModels(trimmed, owner.signal);
+ assertAccountScopeCurrent(owner);
if (lookup.is_diffusers) {
updateModelsUi({ hfLookup: null });
- if (await install({ accessToken: token, source: trimmed })) {
+ if ((await install({ accessToken: token, source: trimmed })) && isAccountScopeCurrent(owner)) {
setQuery('');
}
@@ -247,7 +269,7 @@ export const AddModelsView = () => {
if (lookup.urls.length === 1 && onlyUrl) {
updateModelsUi({ hfLookup: null });
- if (await install({ accessToken: token, source: onlyUrl })) {
+ if ((await install({ accessToken: token, source: onlyUrl })) && isAccountScopeCurrent(owner)) {
setQuery('');
}
@@ -259,25 +281,45 @@ export const AddModelsView = () => {
return;
}
- if (await install({ accessToken: token, inplace: kind.looksLocal ? inplace : undefined, source: trimmed })) {
+ if (
+ (await install({ accessToken: token, inplace: kind.looksLocal ? inplace : undefined, source: trimmed })) &&
+ isAccountScopeCurrent(owner)
+ ) {
setQuery('');
}
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.installFailed'), error instanceof Error ? error.message : String(error));
} finally {
- setIsPulling(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsPulling(false);
+ }
}
};
const handleScan = async () => {
+ const owner = captureAccountScope();
+
setIsScanning(true);
try {
- updateModelsUi({ scan: { path: trimmed, results: await scanFolderForModels(trimmed) } });
+ const results = await scanFolderForModels(trimmed, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ updateModelsUi({ scan: { path: trimmed, results } });
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.scanFailed'), error instanceof Error ? error.message : String(error));
} finally {
- setIsScanning(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsScanning(false);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts
index c3ce15cac5..9be030c808 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts
@@ -2,6 +2,11 @@ import { installModel, type InstallModelRequest } from '@features/models/data/ap
import { getAccessTokenForSource } from '@features/models/data/apiKeys';
import { addInstallJob } from '@features/models/data/installsStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { useCallback, useState } from 'react';
/**
@@ -17,14 +22,20 @@ export const useInstallActions = () => {
const install = useCallback(
async (request: InstallModelRequest, options?: { silent?: boolean }): Promise<boolean> => {
+ const owner = captureAccountScope();
+
setPendingSources((current) => new Set(current).add(request.source));
try {
- const job = await installModel({
- ...request,
- accessToken: request.accessToken ?? getAccessTokenForSource(request.source),
- });
+ const job = await installModel(
+ {
+ ...request,
+ accessToken: request.accessToken ?? getAccessTokenForSource(request.source),
+ },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
addInstallJob(job);
if (!options?.silent) {
@@ -33,17 +44,23 @@ export const useInstallActions = () => {
return true;
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
notify.error('Model install failed to start', error instanceof Error ? error.message : String(error));
return false;
} finally {
- setPendingSources((current) => {
- const next = new Set(current);
+ if (isAccountScopeCurrent(owner)) {
+ setPendingSources((current) => {
+ const next = new Set(current);
- next.delete(request.source);
+ next.delete(request.source);
- return next;
- });
+ return next;
+ });
+ }
}
},
[notify]
diff --git a/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx
index 23f49e8af5..afcb2c91ac 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx
@@ -15,9 +15,16 @@ import { clearCivitaiApiKey, getCivitaiApiKey, setCivitaiApiKey } from '@feature
import { refreshInstalls } from '@features/models/data/installsStore';
import { refreshStartersIfLoaded } from '@features/models/data/startersStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { Button } from '@platform/ui';
import { BotIcon, HexagonIcon } from 'lucide-react';
-import { useEffect, useState, type ElementType } from 'react';
+import { useState, type ElementType } from 'react';
import { useTranslation } from 'react-i18next';
import { SiAlibabacloud, SiBytedance, SiGooglegemini, SiHuggingface } from 'react-icons/si';
@@ -66,10 +73,10 @@ const ApiKeyCard = ({
icon: ElementType;
isLoading?: boolean;
/** Absent until a key exists; clears the stored key. */
- onClear?: () => Promise<void> | void;
+ onClear?: (owner: AccountScope) => Promise<void> | void;
/** Save/clear failures (network, backend rejection) land here. */
onError: (message: string) => void;
- onSave: (key: string) => Promise<void> | void;
+ onSave: (key: string, owner: AccountScope) => Promise<void> | void;
/** Hint at the expected shape, e.g. "hf_…" or "sk-…". */
placeholder: string;
status: KeyStatusBadge | null;
@@ -79,19 +86,29 @@ const ApiKeyCard = ({
const [draft, setDraft] = useState('');
const [isBusy, setIsBusy] = useState(false);
- const runAction = async (action: () => Promise<void> | void): Promise<boolean> => {
+ const runAction = async (
+ action: (owner: AccountScope) => Promise<void> | void,
+ owner: AccountScope = captureAccountScope()
+ ): Promise<boolean> => {
setIsBusy(true);
try {
- await action();
+ await action(owner);
+ assertAccountScopeCurrent(owner);
return true;
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
onError(error instanceof Error ? error.message : t('common.somethingWentWrong'));
return false;
} finally {
- setIsBusy(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
}
};
@@ -102,8 +119,10 @@ const ApiKeyCard = ({
return;
}
+ const owner = captureAccountScope();
+
// Keep the draft on failure so the key can be corrected and retried.
- if (await runAction(() => onSave(key))) {
+ if ((await runAction((actionOwner) => onSave(key, actionOwner), owner)) && isAccountScopeCurrent(owner)) {
setDraft('');
}
};
@@ -186,25 +205,26 @@ const HuggingFaceKeyCard = ({ onError }: { onError: (title: string, message: str
const [status, setStatus] = useState<HFTokenStatus | null>(null);
const statusBadge = status ? { label: t(`models.keyStatus.${status}`), palette: HF_STATUS_PALETTES[status] } : null;
- useEffect(() => {
- let isStale = false;
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+ let isMounted = true;
- getHFTokenStatus()
+ getHFTokenStatus(owner.signal)
.then((tokenStatus) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setStatus(tokenStatus);
}
})
.catch(() => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setStatus('unknown');
}
});
return () => {
- isStale = true;
+ isMounted = false;
};
- }, [t]);
+ });
return (
<ApiKeyCard
@@ -217,14 +237,18 @@ const HuggingFaceKeyCard = ({ onError }: { onError: (title: string, message: str
onError={(message) => onError(t('models.huggingFaceToken'), message)}
onClear={
status === 'valid' || status === 'invalid'
- ? async () => {
- setStatus(await resetHFToken());
+ ? async (owner) => {
+ const nextStatus = await resetHFToken(owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ setStatus(nextStatus);
}
: undefined
}
- onSave={async (key) => {
- const nextStatus = await setHFToken(key);
+ onSave={async (key, owner) => {
+ const nextStatus = await setHFToken(key, owner.signal);
+ assertAccountScopeCurrent(owner);
setStatus(nextStatus);
if (nextStatus === 'invalid') {
@@ -279,26 +303,27 @@ const ExternalProviderKeyCards = ({ onError }: { onError: (title: string, messag
const [configs, setConfigs] = useState<ExternalProviderConfig[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
- useEffect(() => {
- let isStale = false;
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+ let isMounted = true;
- getExternalProviderConfigs()
+ getExternalProviderConfigs(owner.signal)
.then((providerConfigs) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setConfigs(providerConfigs);
}
})
.catch((error: unknown) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setConfigs([]);
setLoadError(error instanceof Error ? error.message : t('models.failedToLoadExternalProviders'));
}
});
return () => {
- isStale = true;
+ isMounted = false;
};
- }, [t]);
+ });
const replaceConfig = (next: ExternalProviderConfig) => {
setConfigs((current) => (current ?? []).map((config) => (config.provider_id === next.provider_id ? next : config)));
@@ -367,33 +392,36 @@ const ExternalProviderKeyCard = ({
const [overrideBaseUrl, setOverrideBaseUrl] = useState(config.base_url !== null);
const [isBusy, setIsBusy] = useState(false);
- useEffect(() => {
- setApiKeyDraft('');
- setBaseUrlDraft(config.base_url ?? '');
- setOverrideBaseUrl(config.base_url !== null);
- }, [config.base_url, config.provider_id]);
-
const hasApiKeyDraft = apiKeyDraft.trim().length > 0;
const hasBaseUrlChange = overrideBaseUrl ? baseUrlDraft.trim() !== (config.base_url ?? '') : config.base_url !== null;
const runAction = async (
- action: () => Promise<ExternalProviderConfig>,
- onSuccess?: (next: ExternalProviderConfig) => void
+ action: (owner: AccountScope) => Promise<ExternalProviderConfig>,
+ onSuccess?: (next: ExternalProviderConfig, owner: AccountScope) => void
): Promise<void> => {
+ const owner = captureAccountScope();
+
setIsBusy(true);
try {
- const nextConfig = await action();
+ const nextConfig = await action(owner);
+ assertAccountScopeCurrent(owner);
onUpdated(nextConfig);
setApiKeyDraft('');
setBaseUrlDraft(nextConfig.base_url ?? '');
setOverrideBaseUrl(nextConfig.base_url !== null);
- onSuccess?.(nextConfig);
+ onSuccess?.(nextConfig, owner);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
onError(error instanceof Error ? error.message : t('common.somethingWentWrong'));
} finally {
- setIsBusy(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
}
};
@@ -419,13 +447,13 @@ const ExternalProviderKeyCard = ({
const apiKeyWasSet = nextConfig.api_key !== undefined;
await runAction(
- () => setExternalProviderConfig(config.provider_id, nextConfig),
- (next) => {
+ (owner) => setExternalProviderConfig(config.provider_id, nextConfig, owner.signal),
+ (next, owner) => {
if (apiKeyWasSet && next.api_key_configured) {
// The backend queues this provider's external starter models on
// key-set; pull the new jobs and refresh starters so its rows flip to
// Installed without an app restart.
- void refreshInstalls();
+ void refreshInstalls(owner);
refreshStartersIfLoaded();
}
}
@@ -544,7 +572,7 @@ const ExternalProviderKeyCard = ({
disabled={isBusy}
size="sm"
variant="ghost"
- onClick={() => void runAction(() => resetExternalProviderConfig(config.provider_id))}
+ onClick={() => void runAction((owner) => resetExternalProviderConfig(config.provider_id, owner.signal))}
>
{t('common.clear')}
</Button>
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 2183440d2d..48f16579cd 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx
@@ -6,6 +6,11 @@ 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 { Button, Combobox, FieldLabel, Panel, Select } from '@platform/ui';
import { MoveHorizontalIcon } from 'lucide-react';
import { useMemo, useState, type ReactNode } from 'react';
@@ -326,6 +331,7 @@ export const DefaultSettingsSection = ({
};
const handleSave = async () => {
+ const owner = captureAccountScope();
const validationError = validateDefaults(model, settings, t);
if (validationError) {
@@ -336,12 +342,21 @@ export const DefaultSettingsSection = ({
setIsSaving(true);
try {
- replaceModelInStore(await updateModel(model.key, { default_settings: settings }));
+ 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 {
- setIsSaving(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsSaving(false);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx
index 6c221264f1..e5c0172b4b 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx
@@ -8,6 +8,11 @@ import { getModelTypeLabel, MODEL_CATEGORIES } from '@features/models/core/taxon
import { updateModel } from '@features/models/data/api';
import { replaceModelInStore } from '@features/models/data/modelsStore';
import { useZodForm } from '@platform/react/useZodForm';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, Field, Select } from '@platform/ui';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -80,18 +85,33 @@ export const ModelEditForm = ({
const handleSave = () =>
form.handleSubmit(async (values) => {
- const updated = await updateModel(model.key, {
- base: values.base,
- description: values.description || null,
- name: values.name,
- prediction_type: values.predictionType === '' ? null : (values.predictionType as PredictionType),
- source_url: values.sourceUrl === '' ? null : values.sourceUrl,
- type: values.type,
- variant: values.variant === '' ? null : values.variant,
- });
+ const owner = captureAccountScope();
- replaceModelInStore(updated);
- onSaved();
+ try {
+ const updated = await updateModel(
+ model.key,
+ {
+ base: values.base,
+ description: values.description || null,
+ name: values.name,
+ prediction_type: values.predictionType === '' ? null : (values.predictionType as PredictionType),
+ source_url: values.sourceUrl === '' ? null : values.sourceUrl,
+ type: values.type,
+ variant: values.variant === '' ? null : values.variant,
+ },
+ owner.signal
+ );
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
+ onSaved();
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ throw error;
+ }
});
return (
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx
new file mode 100644
index 0000000000..1bbb05368d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.browser.test.tsx
@@ -0,0 +1,115 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { type AccountScope, accountLifecycle } from '@platform/state/accountLifecycle';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+
+import { ModelImageUpload } from './ModelImageUpload';
+
+const dependencies = vi.hoisted(() => ({
+ deleteModelImage: vi.fn(),
+ getModelImageUrl: vi.fn(() => '/model-image.png'),
+ markCoverImageChanged: vi.fn(),
+ updateModelImage: vi.fn(),
+}));
+
+vi.mock('@features/models/data/api', () => ({
+ deleteModelImage: dependencies.deleteModelImage,
+ getModelImageUrl: dependencies.getModelImageUrl,
+ updateModelImage: dependencies.updateModelImage,
+}));
+vi.mock('@features/models/data/modelsStore', () => ({
+ markCoverImageChanged: dependencies.markCoverImageChanged,
+ useModelsSelector: (selector: (snapshot: { coverImageVersions: Record<string, number> }) => unknown) =>
+ selector({ coverImageVersions: {} }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const deferred = <Value,>() => {
+ let reject!: (reason?: unknown) => void;
+ let resolve!: (value: Value) => void;
+ const promise = new Promise<Value>((resolvePromise, rejectPromise) => {
+ reject = rejectPromise;
+ resolve = resolvePromise;
+ });
+
+ return { promise, reject, resolve };
+};
+
+const model = { cover_image: null, key: 'model-a', name: 'Model A' };
+
+describe('ModelImageUpload account ownership', () => {
+ let host: HTMLDivElement;
+ let onError: Mock<(message: string) => void>;
+ let onUpdated: Mock<() => void>;
+ let owner: AccountScope;
+ let root: Root;
+
+ beforeEach(async () => {
+ dependencies.deleteModelImage.mockReset().mockResolvedValue(undefined);
+ dependencies.markCoverImageChanged.mockReset();
+ dependencies.updateModelImage.mockReset().mockResolvedValue(undefined);
+ onError = vi.fn();
+ onUpdated = vi.fn();
+ owner = accountLifecycle.activate('model-image-a', ':user:model-image-a');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <ModelImageUpload model={model} onError={onError} onUpdated={onUpdated} />
+ </ChakraProvider>
+ );
+ });
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ const upload = async (file: File): Promise<void> => {
+ const input = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+
+ Object.defineProperty(input, 'files', { configurable: true, value: [file] });
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ };
+
+ it('commits an upload only while its account lifetime is current', async () => {
+ const file = new File(['image'], 'cover.png', { type: 'image/png' });
+
+ await act(() => upload(file));
+ await vi.waitFor(() => expect(onUpdated).toHaveBeenCalledOnce());
+
+ expect(dependencies.updateModelImage).toHaveBeenCalledWith(model.key, file, owner.signal);
+ expect(dependencies.markCoverImageChanged).toHaveBeenCalledWith(model.key, true);
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('quietly drops an account A upload that resolves after account B activates', async () => {
+ const request = deferred<void>();
+ const file = new File(['image'], 'cover.png', { type: 'image/png' });
+ dependencies.updateModelImage.mockReturnValueOnce(request.promise);
+
+ await act(() => upload(file));
+ expect(dependencies.updateModelImage).toHaveBeenCalledWith(model.key, file, owner.signal);
+
+ await act(async () => {
+ accountLifecycle.activate('model-image-b', ':user:model-image-b');
+ request.resolve();
+ await request.promise;
+ });
+
+ expect(owner.signal.aborted).toBe(true);
+ expect(dependencies.markCoverImageChanged).not.toHaveBeenCalled();
+ expect(onUpdated).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
+});
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 8f5adef25c..76c950c112 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx
@@ -4,9 +4,14 @@ 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 { DropZone, IconButton, Tooltip } from '@platform/ui';
import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';
-import { useEffect, useRef, useState, type DragEvent } from 'react';
+import { useRef, useState, type DragEvent } from 'react';
import { useTranslation } from 'react-i18next';
const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
@@ -18,15 +23,17 @@ const dragContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTr
* or drop an image file onto it to upload. The remove button sits in the top
* corner and is hover/focus-revealed (and inert while hidden).
*/
-export const ModelImageUpload = ({
- model,
- onError,
- onUpdated,
-}: {
+interface ModelImageUploadProps {
model: Pick<ModelConfig, 'cover_image' | 'key' | 'name'>;
onError: (message: string) => void;
onUpdated: () => void;
-}) => {
+}
+
+export const ModelImageUpload = (props: ModelImageUploadProps) => (
+ <ModelImageUploadForModel key={`${props.model.key}:${props.model.cover_image ?? ''}`} {...props} />
+);
+
+const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploadProps) => {
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement | null>(null);
const dragDepthRef = useRef(0);
@@ -35,13 +42,6 @@ export const ModelImageUpload = ({
const [isBusy, setIsBusy] = useState(false);
const [isDropActive, setIsDropActive] = useState(false);
- useEffect(() => {
- dragDepthRef.current = 0;
- setHasImage(Boolean(model.cover_image));
- setIsBusy(false);
- setIsDropActive(false);
- }, [model.cover_image, model.key]);
-
const handleFile = async (file: File | undefined) => {
if (!file) {
return;
@@ -52,35 +52,55 @@ export const ModelImageUpload = ({
return;
}
- setIsBusy(true);
+ const owner = captureAccountScope();
const modelKey = model.key;
+ setIsBusy(true);
+
try {
- await updateModelImage(modelKey, file);
+ 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 {
- setIsBusy(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
}
};
const handleDelete = async () => {
- setIsBusy(true);
+ const owner = captureAccountScope();
const modelKey = model.key;
+ setIsBusy(true);
+
try {
- await deleteModelImage(modelKey);
+ 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 {
- setIsBusy(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx
index d2dcaf9f45..ed573e8d01 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx
@@ -8,9 +8,15 @@ import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } fr
import { useModelsSelector } from '@features/models/data/modelsStore';
import { ModelSelect } from '@features/models/ui/components';
import { SourceListItem } from '@features/models/ui/shared/SourceListItem';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { IconButton, FieldLabel, Tooltip } from '@platform/ui';
import { Link2OffIcon } from 'lucide-react';
-import { useEffect, useMemo, useState } from 'react';
+import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
/** Types offered when linking related models, grouped in one picker. */
@@ -30,38 +36,42 @@ const LINKABLE_TYPES: ModelTaxonomyType[] = [
* One grouped, compatibility-filtered picker searches every linkable type at
* once; linked models render as rows with an unlink action.
*/
-export const RelatedModelsSection = ({
- model,
- onError,
-}: {
+interface RelatedModelsSectionProps {
model: Pick<ModelConfig, 'base' | 'key'>;
onError: (message: string) => void;
-}) => {
+}
+
+export const RelatedModelsSection = (props: RelatedModelsSectionProps) => (
+ <RelatedModelsForModel key={props.model.key} {...props} />
+);
+
+const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) => {
const { t } = useTranslation();
const models = useModelsSelector((snapshot) => snapshot.models);
const [relatedKeys, setRelatedKeys] = useState<string[] | null>(null);
const [isMutating, setIsMutating] = useState(false);
- useEffect(() => {
- let isStale = false;
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+ let isMounted = true;
- getRelatedModelKeys(model.key)
+ getRelatedModelKeys(model.key, owner.signal)
.then((keys) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setRelatedKeys(keys);
}
})
.catch((error: unknown) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setRelatedKeys([]);
onError(error instanceof Error ? error.message : t('models.failedToLoadRelatedModels'));
}
});
return () => {
- isStale = true;
+ isMounted = false;
};
- }, [model.key, onError, t]);
+ });
const relatedModels = useMemo(() => {
const byKey = new Map(models.map((candidate) => [candidate.key, candidate]));
@@ -76,28 +86,48 @@ export const RelatedModelsSection = ({
return;
}
+ const owner = captureAccountScope();
+
setIsMutating(true);
try {
- await addModelRelationship(model.key, target.key);
+ await addModelRelationship(model.key, target.key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
setRelatedKeys((current) => [...(current ?? []), target.key]);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
onError(error instanceof Error ? error.message : t('models.failedToLinkModels'));
} finally {
- setIsMutating(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsMutating(false);
+ }
}
};
const handleRemove = async (key: string) => {
+ const owner = captureAccountScope();
+
setIsMutating(true);
try {
- await removeModelRelationship(model.key, key);
+ await removeModelRelationship(model.key, key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
setRelatedKeys((current) => (current ?? []).filter((existing) => existing !== key));
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
onError(error instanceof Error ? error.message : t('models.failedToUnlink'));
} finally {
- setIsMutating(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsMutating(false);
+ }
}
};
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 f9aa52afaf..68e24b13dd 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx
@@ -3,6 +3,12 @@ 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 { Button, Field } from '@platform/ui';
import { PlusIcon } from 'lucide-react';
import { memo, useState } from 'react';
@@ -40,7 +46,7 @@ export const TriggerPhrasesEditor = ({
const error = isEditorCurrent ? editor.error : null;
const isSaving = isEditorCurrent ? editor.isSaving : false;
- const persist = async (nextPhrases: string[]): Promise<boolean> => {
+ const persist = async (nextPhrases: string[], owner: AccountScope = captureAccountScope()): Promise<boolean> => {
setEditor((current) => ({
draft: current.modelKey === modelKey ? current.draft : '',
error: current.modelKey === modelKey ? current.error : null,
@@ -49,15 +55,23 @@ export const TriggerPhrasesEditor = ({
}));
try {
- replaceModelInStore(await updateModel(modelKey, { trigger_phrases: nextPhrases }));
+ const updated = await updateModel(modelKey, { trigger_phrases: nextPhrases }, owner.signal);
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
return true;
} catch (persistError) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
onError(persistError instanceof Error ? persistError.message : t('models.failedToUpdateTriggerPhrases'));
return false;
} finally {
- setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));
+ if (isAccountScopeCurrent(owner)) {
+ setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));
+ }
}
};
@@ -82,7 +96,9 @@ export const TriggerPhrasesEditor = ({
setEditor({ draft, error: null, isSaving, modelKey });
// Clear the draft only once it is saved, so a failure never eats the text.
- if (await persist([...phrases, parsed.data])) {
+ const owner = captureAccountScope();
+
+ if ((await persist([...phrases, parsed.data], owner)) && isAccountScopeCurrent(owner)) {
setEditor((current) => (current.modelKey === modelKey ? { ...current, draft: '' } : current));
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.browser.test.tsx
index 07510265f1..f4b97b8d1e 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.browser.test.tsx
@@ -2,6 +2,7 @@ import type { ModelConfig } from '@features/models/core/types';
import { ChakraProvider } from '@chakra-ui/react';
import { getModelsSnapshot, setModelsSnapshotForTests, useModelsSelector } from '@features/models/data/modelsStore';
+import { type AccountScope, accountLifecycle } from '@platform/state/accountLifecycle';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -63,11 +64,13 @@ describe('VaeCpuOnlySetting', () => {
let root: Root;
let onError: Mock<(message: string) => void>;
let onSaved: Mock<() => void>;
+ let owner: AccountScope;
beforeEach(async () => {
api.updateModel.mockReset();
onError = vi.fn();
onSaved = vi.fn();
+ owner = accountLifecycle.activate('vae-setting-test-a', ':user:vae-setting-test-a');
setModelsSnapshotForTests({ models: [vae], status: 'loaded' });
host = document.createElement('div');
document.body.append(host);
@@ -85,7 +88,7 @@ describe('VaeCpuOnlySetting', () => {
afterEach(async () => {
await act(() => root.unmount());
host.remove();
- setModelsSnapshotForTests({ models: [], status: 'idle' });
+ accountLifecycle.invalidate();
});
it('is available only for VAE model details', () => {
@@ -103,7 +106,7 @@ describe('VaeCpuOnlySetting', () => {
await Promise.resolve();
});
- expect(api.updateModel).toHaveBeenCalledWith(vae.key, { cpu_only: true });
+ expect(api.updateModel).toHaveBeenCalledWith(vae.key, { cpu_only: true }, owner.signal);
expect(input.checked).toBe(true);
expect(input.disabled).toBe(true);
expect(getModelsSnapshot().models[0]?.cpu_only).toBe(true);
@@ -141,4 +144,56 @@ describe('VaeCpuOnlySetting', () => {
expect(onError).toHaveBeenCalledWith('save exploded');
expect(onSaved).not.toHaveBeenCalled();
});
+
+ it('does not commit a late response from account A into account B', async () => {
+ const request = deferred<ModelConfig>();
+ api.updateModel.mockReturnValue(request.promise);
+ const input = host.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
+
+ await act(async () => {
+ input.click();
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ accountLifecycle.activate('vae-setting-test-b', ':user:vae-setting-test-b');
+ setModelsSnapshotForTests({ models: [{ ...vae, cpu_only: null }], status: 'loaded' });
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ request.resolve({ ...vae, cpu_only: true });
+ await request.promise;
+ });
+
+ expect(getModelsSnapshot().models[0]?.cpu_only).toBeNull();
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('does not roll back account B or report account A mutation failures', async () => {
+ const request = deferred<ModelConfig>();
+ api.updateModel.mockReturnValue(request.promise);
+ const input = host.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
+
+ await act(async () => {
+ input.click();
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ accountLifecycle.activate('vae-setting-test-b', ':user:vae-setting-test-b');
+ setModelsSnapshotForTests({ models: [{ ...vae, cpu_only: true }], status: 'loaded' });
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ request.reject(new Error('account A failed late'));
+ await request.promise.catch(() => undefined);
+ });
+
+ expect(getModelsSnapshot().models[0]?.cpu_only).toBe(true);
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
});
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 dfbd9299af..474bf230a6 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/VaeCpuOnlySetting.tsx
@@ -3,6 +3,11 @@ 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 { getApiErrorMessage } from '@platform/transport/http';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,6 +35,7 @@ export const VaeCpuOnlySetting = ({
return;
}
+ const owner = captureAccountScope();
const previousCpuOnly = model.cpu_only;
const cpuOnly = details.checked ? true : null;
@@ -37,13 +43,22 @@ export const VaeCpuOnlySetting = ({
patchModelInStore(model.key, { cpu_only: cpuOnly });
try {
- replaceModelInStore(await updateModel(model.key, { cpu_only: cpuOnly }));
+ const updated = await updateModel(model.key, { cpu_only: cpuOnly }, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
onSaved();
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
patchModelInStore(model.key, { cpu_only: previousCpuOnly });
onError(getApiErrorMessage(error, t('models.failedToSaveVaeCpuSetting')));
} finally {
- setIsPending(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsPending(false);
+ }
}
},
[isPending, model.cpu_only, model.key, onError, onSaved, t]
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 49892de5bf..f8a6a86fa1 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts
@@ -4,6 +4,11 @@ import { convertModelToDiffusers, deleteModel, reidentifyModel } from '@features
import { removeModelsFromStore, replaceModelInStore } from '@features/models/data/modelsStore';
import { pruneModelsUiKeys } from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { useCallback } from 'react';
/**
@@ -18,12 +23,20 @@ export const useModelActions = () => {
const remove = useCallback(
async (model: ModelActionTarget) => {
+ const owner = captureAccountScope();
+
try {
- await deleteModel(model.key);
+ await deleteModel(model.key, owner.signal);
+
+ assertAccountScopeCurrent(owner);
removeModelsFromStore([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));
}
},
@@ -32,10 +45,19 @@ export const useModelActions = () => {
const convert = useCallback(
async (model: ModelActionTarget) => {
+ const owner = captureAccountScope();
+
try {
- replaceModelInStore(await convertModelToDiffusers(model.key));
+ 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));
}
},
@@ -44,10 +66,19 @@ export const useModelActions = () => {
const reidentify = useCallback(
async (model: ModelActionTarget) => {
+ const owner = captureAccountScope();
+
try {
- replaceModelInStore(await reidentifyModel(model.key));
+ 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));
}
},
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 5c56f6f54c..0c1453bcb0 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,6 +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 { useConnectionStatusSelector } from '@platform/transport/connectionStore';
import { IconButton, Tooltip } from '@platform/ui';
import { PauseIcon, PlayIcon, RotateCcwIcon, TriangleAlertIcon, XIcon } from 'lucide-react';
@@ -42,21 +47,30 @@ export const InstallJobRow = ({
);
const showDisconnected = connectionStatus !== 'connected' && isActiveInstallStatus(job.status);
- const runAction = async (action: () => Promise<unknown>, failureTitle: string) => {
+ const runAction = async (action: (signal: AbortSignal) => Promise<unknown>, failureTitle: string) => {
+ const owner = captureAccountScope();
+
setIsActing(true);
try {
- const result = await action();
+ 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();
+ await refreshInstalls(owner);
}
} catch (actionError) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
onError(failureTitle, actionError instanceof Error ? actionError.message : String(actionError));
} finally {
- setIsActing(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsActing(false);
+ }
}
};
@@ -89,7 +103,7 @@ export const InstallJobRow = ({
disabled={isActing}
size="2xs"
variant="ghost"
- onClick={() => void runAction(() => pauseModelInstall(job.id), t('models.pauseFailed'))}
+ onClick={() => void runAction((signal) => pauseModelInstall(job.id, signal), t('models.pauseFailed'))}
>
<Icon as={PauseIcon} boxSize="3" />
</IconButton>
@@ -102,7 +116,7 @@ export const InstallJobRow = ({
disabled={isActing}
size="2xs"
variant="ghost"
- onClick={() => void runAction(() => resumeModelInstall(job.id), t('models.resumeFailed'))}
+ onClick={() => void runAction((signal) => resumeModelInstall(job.id, signal), t('models.resumeFailed'))}
>
<Icon as={PlayIcon} boxSize="3" />
</IconButton>
@@ -115,7 +129,9 @@ export const InstallJobRow = ({
disabled={isActing}
size="2xs"
variant="ghost"
- onClick={() => void runAction(() => restartFailedModelInstall(job.id), t('models.retryFailed'))}
+ onClick={() =>
+ void runAction((signal) => restartFailedModelInstall(job.id, signal), t('models.retryFailed'))
+ }
>
<Icon as={RotateCcwIcon} boxSize="3" />
</IconButton>
@@ -128,7 +144,7 @@ export const InstallJobRow = ({
disabled={isActing}
size="2xs"
variant="ghost"
- onClick={() => void runAction(() => cancelModelInstall(job.id), t('models.cancelFailed'))}
+ onClick={() => void runAction((signal) => cancelModelInstall(job.id, signal), t('models.cancelFailed'))}
>
<Icon as={XIcon} boxSize="3" />
</IconButton>
@@ -176,7 +192,10 @@ export const InstallJobRow = ({
size="2xs"
variant="ghost"
onClick={() =>
- void runAction(() => restartModelInstallFile(job.id, partUrl), t('models.restartFileFailed'))
+ void runAction(
+ (signal) => restartModelInstallFile(job.id, partUrl, signal),
+ t('models.restartFileFailed')
+ )
}
>
<Icon as={RotateCcwIcon} boxSize="3" />
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 6369ba7480..133fd06fdc 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
@@ -15,9 +15,15 @@ import {
} from '@features/models/data/installsStore';
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 { Button, IconButton, Tooltip } from '@platform/ui';
import { ChevronUpIcon, ListOrderedIcon, PauseIcon, PlayIcon, RefreshCcwIcon, Trash2Icon, XIcon } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { InstallQueueList } from './InstallQueueList';
@@ -35,9 +41,9 @@ export const InstallQueueBar = () => {
const status = useInstallsSelector((snapshot) => snapshot.status);
const queueExpanded = useModelsUiSelector((snapshot) => snapshot.queueExpanded);
- useEffect(() => {
+ useMountEffect(() => {
ensureInstallsLoaded();
- }, []);
+ });
const activeJobs = useMemo(() => jobs.filter((job) => isActiveInstallStatus(job.status)), [jobs]);
const pausedJobs = useMemo(() => jobs.filter((job) => job.status === 'paused'), [jobs]);
@@ -54,42 +60,65 @@ export const InstallQueueBar = () => {
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)));
- await refreshInstalls();
+ await Promise.all(targets.map((job) => call(job.id, owner.signal)));
+ assertAccountScopeCurrent(owner);
+ await refreshInstalls(owner);
+ assertAccountScopeCurrent(owner);
} catch (bulkError) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.queueActionFailed'), bulkError instanceof Error ? bulkError.message : String(bulkError));
- void refreshInstalls();
+ void refreshInstalls(owner);
} finally {
- setBusyAction(null);
+ if (isAccountScopeCurrent(owner)) {
+ setBusyAction(null);
+ }
}
},
[notify, t]
);
const handlePrune = useCallback(async () => {
+ const owner = captureAccountScope();
+
setBusyAction('prune');
try {
- await pruneCompletedModelInstalls();
- await refreshInstalls();
+ 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 {
- setBusyAction(null);
+ if (isAccountScopeCurrent(owner)) {
+ setBusyAction(null);
+ }
}
}, [notify, t]);
const handleRefresh = useCallback(async () => {
+ const owner = captureAccountScope();
+
setBusyAction('refresh');
try {
- await refreshInstalls();
+ await refreshInstalls(owner);
} finally {
- setBusyAction(null);
+ if (isAccountScopeCurrent(owner)) {
+ setBusyAction(null);
+ }
}
}, []);
const handleOpenChange = useCallback((event: { open: boolean }) => setQueueExpanded(event.open), []);
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 fd5fdde5a9..33112b07b7 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx
@@ -6,9 +6,15 @@ import { formatBytes } from '@features/models/core/taxonomy';
import { deleteOrphanedModels, emptyModelCache, getOrphanedModels } from '@features/models/data/api';
import { refreshModels } from '@features/models/data/modelsStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, CloseButton, IconButton, MenuContent, Panel } from '@platform/ui';
import { BrushCleaningIcon, FolderSearchIcon, MoreHorizontalIcon, RefreshCcwIcon } from 'lucide-react';
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
/**
@@ -21,14 +27,28 @@ export const MaintenanceMenu = () => {
const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false);
const handleEmptyCache = async () => {
+ const owner = captureAccountScope();
+
try {
- await emptyModelCache();
+ await emptyModelCache(owner.signal);
+
+ assertAccountScopeCurrent(owner);
notify.success(t('models.cacheEmptied'));
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.failedToEmptyCache'), error instanceof Error ? error.message : String(error));
}
};
+ const handleRefresh = () => {
+ const owner = captureAccountScope();
+
+ void refreshModels(owner);
+ };
+
return (
<>
<Menu.Root positioning={{ placement: 'bottom-end' }}>
@@ -40,7 +60,7 @@ export const MaintenanceMenu = () => {
<Portal>
<Menu.Positioner>
<MenuContent minW="14rem">
- <Menu.Item value="refresh" onClick={() => void refreshModels()}>
+ <Menu.Item value="refresh" onClick={handleRefresh}>
<Icon as={RefreshCcwIcon} boxSize="3.5" />
<Menu.ItemText fontSize="xs">{t('models.refreshList')}</Menu.ItemText>
</Menu.Item>
@@ -70,25 +90,26 @@ const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string>>(new Set());
const [isDeleting, setIsDeleting] = useState(false);
- useEffect(() => {
- let isStale = false;
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+ let isMounted = true;
- getOrphanedModels()
+ getOrphanedModels(owner.signal)
.then((result) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setOrphans(result);
}
})
.catch((error: unknown) => {
- if (!isStale) {
+ if (isMounted && isAccountScopeCurrent(owner)) {
setLoadError(error instanceof Error ? error.message : t('models.failedToScanOrphaned'));
}
});
return () => {
- isStale = true;
+ isMounted = false;
};
- }, [t]);
+ });
const togglePath = (path: string) => {
setSelectedPaths((current) => {
@@ -105,10 +126,14 @@ const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
};
const handleDelete = async () => {
+ const owner = captureAccountScope();
+
setIsDeleting(true);
try {
- const result = await deleteOrphanedModels([...selectedPaths]);
+ const result = await deleteOrphanedModels([...selectedPaths], owner.signal);
+
+ assertAccountScopeCurrent(owner);
const errorCount = Object.keys(result.errors).length;
if (errorCount > 0) {
@@ -127,12 +152,18 @@ const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
);
}
- void refreshModels();
+ void refreshModels(owner);
onClose();
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.orphanedCleanupFailed'), error instanceof Error ? error.message : String(error));
} finally {
- setIsDeleting(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsDeleting(false);
+ }
}
};
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 1466937818..48cfc494bf 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
@@ -14,6 +14,11 @@ import {
useModelsUiSelector,
} from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, IconButton, ConfirmDialog } from '@platform/ui';
import { Trash2Icon, XIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
@@ -46,11 +51,13 @@ 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);
+ const result = await bulkDeleteModels(keys, owner.signal);
+ assertAccountScopeCurrent(owner);
removeModelsFromStore(result.deleted);
pruneModelsUiKeys(result.deleted);
updateModelsUi({ selectedKeys: new Set(result.failed.map((failure) => failure.key)) });
@@ -68,8 +75,12 @@ export const LibraryColumn = () => {
notify.success(t('models.deleted'), t('models.deletedDescription', { count: result.deleted.length }));
}
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('models.bulkDeleteFailed'), error instanceof Error ? error.message : String(error));
- void refreshModels();
+ void refreshModels(owner);
}
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
index 366c4281e1..ba130f29c6 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts
@@ -1,6 +1,7 @@
import type { FoundModel } from '@features/models/core/types';
import { DEFAULT_LIBRARY_FILTERS, type ModelLibraryFilters } from '@features/models/core/library';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -41,10 +42,10 @@ export interface ModelsUiSnapshot {
libraryScrollOffsets: Record<string, number>;
}
-const store = createExternalStore<ModelsUiSnapshot>({
+const createInitialModelsUiSnapshot = (): ModelsUiSnapshot => ({
activeModelKey: null,
activeTab: 'add',
- filters: DEFAULT_LIBRARY_FILTERS,
+ filters: { ...DEFAULT_LIBRARY_FILTERS },
hfLookup: null,
libraryScrollOffsets: {},
queueExpanded: false,
@@ -52,6 +53,13 @@ const store = createExternalStore<ModelsUiSnapshot>({
selectedKeys: new Set(),
});
+const store = createExternalStore<ModelsUiSnapshot>(createInitialModelsUiSnapshot());
+
+registerAccountOwnedResource({
+ clear: () => store.setSnapshot(createInitialModelsUiSnapshot()),
+ name: 'models-ui',
+});
+
export const updateModelsUi = (next: Partial<ModelsUiSnapshot>): void => {
store.patchSnapshot(next);
};
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts
index c25996de8e..7915ad69bc 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts
@@ -29,22 +29,37 @@ describe('custom node data adapter', () => {
customNodesPath: '/nodes',
nodePacks: [{ name: 'pack', nodeCount: 2, nodeTypes: ['one', 'two'], path: '/nodes/pack' }],
});
- expect(adapter.requestJson).toHaveBeenCalledWith('/api/v2/custom_nodes/');
+ expect(adapter.requestJson).toHaveBeenCalledWith('/api/v2/custom_nodes/', { signal: undefined });
});
it('encodes pack identifiers and sends install intent in the body', async () => {
adapter.requestJson.mockResolvedValue({ success: true });
const { installCustomNodePack, uninstallCustomNodePack } = await import('./api');
+ const controller = new AbortController();
- await installCustomNodePack('https://example.test/nodes.git');
- await uninstallCustomNodePack('pack/with spaces');
+ await installCustomNodePack('https://example.test/nodes.git', controller.signal);
+ await uninstallCustomNodePack('pack/with spaces', controller.signal);
expect(adapter.requestJson).toHaveBeenNthCalledWith(1, '/api/v2/custom_nodes/install', {
body: JSON.stringify({ source: 'https://example.test/nodes.git' }),
method: 'POST',
+ signal: controller.signal,
});
expect(adapter.requestJson).toHaveBeenNthCalledWith(2, '/api/v2/custom_nodes/pack%2Fwith%20spaces', {
method: 'DELETE',
+ signal: controller.signal,
+ });
+ });
+
+ it('forwards account cancellation to node reloads', async () => {
+ const { reloadCustomNodes } = await import('./api');
+ const controller = new AbortController();
+
+ await reloadCustomNodes(controller.signal);
+
+ expect(adapter.request).toHaveBeenCalledWith('/api/v2/custom_nodes/reload', {
+ method: 'POST',
+ signal: controller.signal,
});
});
});
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/api.ts b/invokeai/frontend/webv2/src/features/nodes/data/api.ts
index b2f5f78c9b..798b1c3973 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/api.ts
@@ -22,18 +22,22 @@ export interface UninstallNodePackResponse {
message: string;
}
-export const listCustomNodePacks = async (): Promise<NodePackCatalog> =>
- normalizeNodePackCatalog(await requestJson<unknown>(`${CUSTOM_NODES_BASE}/`));
+export const listCustomNodePacks = async (signal?: AbortSignal): Promise<NodePackCatalog> =>
+ normalizeNodePackCatalog(await requestJson<unknown>(`${CUSTOM_NODES_BASE}/`, { signal }));
-export const installCustomNodePack = (source: string): Promise<InstallNodePackResponse> =>
+export const installCustomNodePack = (source: string, signal?: AbortSignal): Promise<InstallNodePackResponse> =>
requestJson<InstallNodePackResponse>(`${CUSTOM_NODES_BASE}/install`, {
body: JSON.stringify({ source }),
method: 'POST',
+ signal,
});
-export const uninstallCustomNodePack = (packName: string): Promise<UninstallNodePackResponse> =>
- requestJson<UninstallNodePackResponse>(`${CUSTOM_NODES_BASE}/${encodeURIComponent(packName)}`, { method: 'DELETE' });
+export const uninstallCustomNodePack = (packName: string, signal?: AbortSignal): Promise<UninstallNodePackResponse> =>
+ requestJson<UninstallNodePackResponse>(`${CUSTOM_NODES_BASE}/${encodeURIComponent(packName)}`, {
+ method: 'DELETE',
+ signal,
+ });
-export const reloadCustomNodes = async (): Promise<void> => {
- await request(`${CUSTOM_NODES_BASE}/reload`, { method: 'POST' });
+export const reloadCustomNodes = async (signal?: AbortSignal): Promise<void> => {
+ await request(`${CUSTOM_NODES_BASE}/reload`, { method: 'POST', signal });
};
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.ts
index 71257e26b1..f8282f44b1 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export interface CustomNodeInstallLogEntry {
@@ -33,4 +34,12 @@ export const clearCustomNodeInstallLog = (): void => {
store.patchSnapshot({ log: [] });
};
+registerAccountOwnedResource({
+ clear: () => {
+ nextId = 1;
+ clearCustomNodeInstallLog();
+ },
+ name: 'custom-node-install-log',
+});
+
export const useCustomNodeInstallLog = (): CustomNodeInstallLogEntry[] => store.useSelector((snapshot) => snapshot.log);
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
index 2da9b29db7..513279a79f 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
@@ -4,6 +4,7 @@ import type {
NodeInvocationStartedEvent,
} from '@features/nodes/core/executionContracts';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createKeyedTransientStore } from '@platform/state/externalStore';
import { browserNodesDataPort } from './transport';
@@ -115,5 +116,10 @@ export interface NodeExecutionSink {
subscribe(nodeId: string, listener: () => void): () => void;
}
+registerAccountOwnedResource({
+ clear: nodeExecutionStore.clearAll,
+ name: 'node-execution',
+});
+
export const useNodeExecutionState = (nodeId: string): NodeExecutionState | null =>
stateByNodeId.useValue(nodeId) ?? null;
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
index 7ac56f63f4..fee9b33ffa 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
@@ -1,5 +1,11 @@
import type { NodePackInfo } from '@features/nodes/core/catalog';
+import {
+ type AccountScope,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { getApiErrorMessage } from '@platform/transport/http';
@@ -12,24 +18,37 @@ export interface CustomNodesSnapshot {
error: string | null;
}
-const store = createExternalStore<CustomNodesSnapshot>({
+const EMPTY_CUSTOM_NODES_SNAPSHOT: CustomNodesSnapshot = {
customNodesPath: null,
error: null,
nodePacks: [],
status: 'idle',
-});
+};
+const store = createExternalStore<CustomNodesSnapshot>(EMPTY_CUSTOM_NODES_SNAPSHOT);
let inflightRefresh: Promise<void> | null = null;
-export const refreshCustomNodePacks = (): Promise<void> => {
+registerAccountOwnedResource({
+ clear: () => {
+ inflightRefresh = null;
+ store.setSnapshot(EMPTY_CUSTOM_NODES_SNAPSHOT);
+ },
+ name: 'custom-node-packs',
+});
+
+export const refreshCustomNodePacks = (owner: AccountScope = captureAccountScope()): Promise<void> => {
if (inflightRefresh) {
return inflightRefresh;
}
store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
- inflightRefresh = listCustomNodePacks()
+ const refresh = listCustomNodePacks(owner.signal)
.then((response) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
customNodesPath: response.customNodesPath,
error: null,
@@ -38,15 +57,22 @@ export const refreshCustomNodePacks = (): Promise<void> => {
});
})
.catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: getApiErrorMessage(error, 'Failed to load custom node packs.'),
status: store.getSnapshot().nodePacks.length > 0 ? 'loaded' : 'error',
});
})
.finally(() => {
- inflightRefresh = null;
+ if (inflightRefresh === refresh) {
+ inflightRefresh = null;
+ }
});
+ inflightRefresh = refresh;
return inflightRefresh;
};
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx
index d43bf25119..a3edcba007 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx
@@ -3,6 +3,11 @@ import { installCustomNodePack } from '@features/nodes/data/api';
import { addCustomNodeInstallLogEntry } from '@features/nodes/data/installLogStore';
import { refreshCustomNodePacks, useCustomNodesSelector } from '@features/nodes/data/nodesStore';
import { updateNodesUi, useNodesUiSelector, type AddNodesTab } from '@features/nodes/ui/nodesUiStore';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, Field, Scrollable, Tabs, toaster } from '@platform/ui';
import { FolderOpenIcon, GitBranchIcon } from 'lucide-react';
@@ -55,16 +60,20 @@ const InstallFromGitForm = () => {
return;
}
+ const owner = captureAccountScope();
+
setIsInstalling(true);
addCustomNodeInstallLogEntry({ name: trimmedSource, status: 'installing' });
try {
- const result = await installCustomNodePack(trimmedSource);
+ const result = await installCustomNodePack(trimmedSource, owner.signal);
+ assertAccountScopeCurrent(owner);
if (result.success) {
addCustomNodeInstallLogEntry({ message: result.message, name: result.name, status: 'completed' });
setSource('');
- await refreshCustomNodePacks();
+ await refreshCustomNodePacks(owner);
+ assertAccountScopeCurrent(owner);
if (result.requires_dependencies) {
toaster.create({
@@ -80,13 +89,19 @@ const InstallFromGitForm = () => {
addCustomNodeInstallLogEntry({ message: result.message, name: result.name, status: 'error' });
}
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
addCustomNodeInstallLogEntry({
message: getApiErrorMessage(error, t('nodes.installFailed')),
name: trimmedSource,
status: 'error',
});
} finally {
- setIsInstalling(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsInstalling(false);
+ }
}
}, [t, trimmedSource]);
const handleSourceChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.browser.test.tsx
new file mode 100644
index 0000000000..69400d09e8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.browser.test.tsx
@@ -0,0 +1,101 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { type AccountScope, accountLifecycle } from '@platform/state/accountLifecycle';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ReloadNodesButton } from './ReloadNodesButton';
+
+const dependencies = vi.hoisted(() => ({
+ error: vi.fn(),
+ refreshCustomNodePacks: vi.fn(),
+ reloadCustomNodes: vi.fn(),
+ success: vi.fn(),
+}));
+
+vi.mock('@features/nodes/data/api', () => ({ reloadCustomNodes: dependencies.reloadCustomNodes }));
+vi.mock('@features/nodes/data/nodesStore', () => ({
+ refreshCustomNodePacks: dependencies.refreshCustomNodePacks,
+}));
+vi.mock('@features/nodes/ui/useNodesNotify', () => ({
+ useNotify: () => ({ error: dependencies.error, success: dependencies.success }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const deferred = <Value,>() => {
+ let reject!: (reason?: unknown) => void;
+ let resolve!: (value: Value) => void;
+ const promise = new Promise<Value>((resolvePromise, rejectPromise) => {
+ reject = rejectPromise;
+ resolve = resolvePromise;
+ });
+
+ return { promise, reject, resolve };
+};
+
+describe('ReloadNodesButton account ownership', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let owner: AccountScope;
+
+ beforeEach(async () => {
+ dependencies.error.mockReset();
+ dependencies.refreshCustomNodePacks.mockReset().mockResolvedValue(undefined);
+ dependencies.reloadCustomNodes.mockReset().mockResolvedValue(undefined);
+ dependencies.success.mockReset();
+ owner = accountLifecycle.activate('reload-nodes-a', ':user:reload-nodes-a');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <ReloadNodesButton />
+ </ChakraProvider>
+ );
+ });
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('completes reload and refresh within one account lifetime', async () => {
+ await act(async () => {
+ host.querySelector<HTMLButtonElement>('button')?.click();
+ await vi.waitFor(() => expect(dependencies.success).toHaveBeenCalledOnce());
+ });
+
+ expect(dependencies.reloadCustomNodes).toHaveBeenCalledWith(owner.signal);
+ expect(dependencies.refreshCustomNodePacks).toHaveBeenCalledWith(owner);
+ expect(dependencies.error).not.toHaveBeenCalled();
+ });
+
+ it('keeps an account A abort quiet after account B activates', async () => {
+ const request = deferred<void>();
+ dependencies.reloadCustomNodes.mockReturnValueOnce(request.promise);
+
+ await act(async () => {
+ host.querySelector<HTMLButtonElement>('button')?.click();
+ await Promise.resolve();
+ });
+ expect(dependencies.reloadCustomNodes).toHaveBeenCalledWith(owner.signal);
+
+ await act(async () => {
+ accountLifecycle.activate('reload-nodes-b', ':user:reload-nodes-b');
+ request.reject(new DOMException('The operation was aborted.', 'AbortError'));
+ await request.promise.catch(() => undefined);
+ });
+
+ expect(owner.signal.aborted).toBe(true);
+ expect(dependencies.refreshCustomNodePacks).not.toHaveBeenCalled();
+ expect(dependencies.success).not.toHaveBeenCalled();
+ expect(dependencies.error).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx
index 2a92ef0ea7..ad0484affc 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx
@@ -3,6 +3,11 @@ import { Icon } from '@chakra-ui/react';
import { reloadCustomNodes } from '@features/nodes/data/api';
import { refreshCustomNodePacks } from '@features/nodes/data/nodesStore';
import { useNotify } from '@features/nodes/ui/useNodesNotify';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button } from '@platform/ui';
import { RefreshCwIcon } from 'lucide-react';
@@ -15,16 +20,26 @@ export const ReloadNodesButton = () => {
const [isReloading, setIsReloading] = useState(false);
const handleReload = async () => {
+ const owner = captureAccountScope();
+
setIsReloading(true);
try {
- await reloadCustomNodes();
- await refreshCustomNodePacks();
+ await reloadCustomNodes(owner.signal);
+ assertAccountScopeCurrent(owner);
+ await refreshCustomNodePacks(owner);
+ assertAccountScopeCurrent(owner);
notify.success(t('nodes.customNodesReloaded'));
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('nodes.reloadFailed'), getApiErrorMessage(error, t('nodes.couldNotReloadCustomNodes')));
} finally {
- setIsReloading(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsReloading(false);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts
index bdd4c004a9..397a2d3037 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -18,12 +19,19 @@ export interface NodesUiSnapshot {
searchTerm: string;
}
-const store = createExternalStore<NodesUiSnapshot>({
+const INITIAL_NODES_UI_SNAPSHOT: NodesUiSnapshot = {
activeTab: 'details',
activePackName: null,
activityExpanded: false,
addTab: 'git',
searchTerm: '',
+};
+
+const store = createExternalStore<NodesUiSnapshot>(INITIAL_NODES_UI_SNAPSHOT);
+
+registerAccountOwnedResource({
+ clear: () => store.setSnapshot(INITIAL_NODES_UI_SNAPSHOT),
+ name: 'nodes-ui',
});
export const updateNodesUi = (next: Partial<NodesUiSnapshot>): void => store.patchSnapshot(next);
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.ts b/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.ts
index acbd1b0662..b17fd4c536 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.ts
@@ -4,22 +4,34 @@ import { uninstallCustomNodePack } from '@features/nodes/data/api';
import { addCustomNodeInstallLogEntry } from '@features/nodes/data/installLogStore';
import { refreshCustomNodePacks, removeCustomNodePackFromStore } from '@features/nodes/data/nodesStore';
import { useNotify } from '@features/nodes/ui/useNodesNotify';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
export const useNodePackActions = () => {
const notify = useNotify();
const uninstall = async (pack: NodePackInfo, onUninstalled?: (packName: string) => void) => {
+ const owner = captureAccountScope();
+
try {
- const result = await uninstallCustomNodePack(pack.name);
+ const result = await uninstallCustomNodePack(pack.name, owner.signal);
+ assertAccountScopeCurrent(owner);
removeCustomNodePackFromStore(pack.name);
addCustomNodeInstallLogEntry({ message: result.message, name: result.name, status: 'uninstalled' });
notify.success('Node pack uninstalled', 'Restart InvokeAI for node removal to take full effect.');
onUninstalled?.(pack.name);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error('Uninstall failed', getApiErrorMessage(error, 'Could not uninstall the node pack.'));
- await refreshCustomNodePacks();
+ await refreshCustomNodePacks(owner);
}
};
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 91f74bc658..5b92b86c9e 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -236,11 +236,11 @@ export interface QueueBackendPort extends QueueFeatureCommands {
options?: QueueResultImageOptions
): Promise<QueueResultImage[]>;
listItems(): Promise<QueueBackendItem[]>;
- readCurrent(scope?: QueueQueryScope): Promise<QueueItemReadModel | null>;
- readItemIds(order: 'asc' | 'desc', scope?: QueueQueryScope): Promise<QueueItemIdsReadModel>;
- readItemsById(itemIds: number[]): Promise<QueueItemReadModel[]>;
- readNext(scope?: QueueQueryScope): Promise<QueueItemReadModel | null>;
- readStatus(scope?: QueueQueryScope): Promise<QueueStatusReadModel>;
+ readCurrent(scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueItemReadModel | null>;
+ readItemIds(order: 'asc' | 'desc', scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueItemIdsReadModel>;
+ readItemsById(itemIds: number[], signal?: AbortSignal): Promise<QueueItemReadModel[]>;
+ readNext(scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueItemReadModel | null>;
+ readStatus(scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueStatusReadModel>;
retryItems(itemIds: number[]): Promise<unknown>;
emit(event: string, payload: unknown): void;
on(event: string, handler: (payload: never) => void): () => void;
diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts
index 2bdc201d7d..c09182266c 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts
@@ -1,5 +1,6 @@
import type { QueueItemProgressTarget } from '@features/queue/core/types';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export interface ActiveProgressTargetSink {
@@ -27,5 +28,10 @@ export const activeProgressTargetStore: ActiveProgressTargetSink = {
},
};
+registerAccountOwnedResource({
+ clear: () => activeProgressTargetStore.clear(),
+ name: 'queue-active-progress-target',
+});
+
export const useActiveProgressTarget = (): QueueItemProgressTarget | null =>
store.useSelector((snapshot) => snapshot.target);
diff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts
index d5cd4a9fe6..2a53660a35 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts
@@ -48,19 +48,19 @@ export const queueBackend: QueueBackendPort = {
pauseProcessor: async () => {
await pauseQueueProcessor();
},
- readCurrent: async (scope) => {
- const item = await getCurrentQueueItem(scope);
+ readCurrent: async (scope, signal) => {
+ const item = await getCurrentQueueItem(scope, signal);
return item ? mapQueueItemDTO(item) : null;
},
- readItemIds: async (order, scope) => mapQueueItemIdsDTO(await getQueueItemIds(order, scope)),
- readItemsById: async (itemIds) => (await getQueueItemsByIds(itemIds)).map(mapQueueItemDTO),
- readNext: async (scope) => {
- const item = await getNextQueueItem(scope);
+ readItemIds: async (order, scope, signal) => mapQueueItemIdsDTO(await getQueueItemIds(order, scope, signal)),
+ readItemsById: async (itemIds, signal) => (await getQueueItemsByIds(itemIds, signal)).map(mapQueueItemDTO),
+ readNext: async (scope, signal) => {
+ const item = await getNextQueueItem(scope, signal);
return item ? mapQueueItemDTO(item) : null;
},
- readStatus: async (scope) => mapQueueStatusDTO(await getQueueStatus(scope)),
+ readStatus: async (scope, signal) => mapQueueStatusDTO(await getQueueStatus(scope, signal)),
retryItems: retryItemsById,
resumeProcessor: async () => {
await resumeQueueProcessor();
diff --git a/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts
index ff2bbd49cf..04936854b5 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts
@@ -1,4 +1,5 @@
import { mergeQueueProgressImage, type QueueProgressImage } from '@features/queue/core/progressImage';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createKeyedTransientStore } from '@platform/state/externalStore';
/**
@@ -37,5 +38,10 @@ export const itemProgressStore = {
},
};
+registerAccountOwnedResource({
+ clear: itemProgressStore.clearAll,
+ name: 'queue-backend-item-progress',
+});
+
export const useItemProgress = (itemId: number | null | undefined): ItemProgress | null =>
progressByItemId.useValue(itemId ?? -1) ?? null;
diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
index c4d2d2a4f6..d606eee834 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
@@ -1,6 +1,7 @@
import type { QueueProgressImage } from '@features/queue/core/progressImage';
import type { QueueItemProgressTarget } from '@features/queue/core/types';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';
/**
@@ -53,6 +54,11 @@ export const progressImageStore = {
},
};
+registerAccountOwnedResource({
+ clear: () => progressImageStore.clear(),
+ name: 'queue-progress-images',
+});
+
export type ProgressImageSink = typeof progressImageStore;
export const useProgressImage = (): LatestProgressImageSnapshot | null =>
diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts
index 4223d46804..091313dfc5 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts
@@ -1,5 +1,6 @@
import type { QueueItemProgress } from '@features/queue/core/types';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createKeyedTransientStore } from '@platform/state/externalStore';
/**
@@ -31,5 +32,10 @@ export const queueItemProgressStore: QueueItemProgressSink = {
},
};
+registerAccountOwnedResource({
+ clear: () => queueItemProgressStore.clearAll?.(),
+ name: 'queue-local-item-progress',
+});
+
export const useQueueItemProgress = (queueItemId: string): QueueItemProgress | null =>
progressByQueueItemId.useValue(queueItemId) ?? null;
diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts
index 82fa55fb49..1f008aa561 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts
@@ -1,5 +1,6 @@
import type { QueueBackendPort } from '@features/queue/core/types';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient } from '@tanstack/react-query';
import { describe, expect, it, vi } from 'vitest';
@@ -57,7 +58,7 @@ describe('queue queries', () => {
expect(first).toBe(second);
expect(cached).toBe(first);
expect(backend.readStatus).toHaveBeenCalledTimes(1);
- expect(backend.readItemsById).toHaveBeenCalledWith([2, 1]);
+ expect(backend.readItemsById).toHaveBeenCalledWith([2, 1], expect.any(AbortSignal));
});
it('keeps project-scoped queue reads in distinct cache entries', async () => {
@@ -82,4 +83,39 @@ describe('queue queries', () => {
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
});
+
+ it('does not continue or publish a read after its account epoch expires', async () => {
+ accountLifecycle.activate('user-a');
+ const backend = createBackend();
+ const onRead = vi.fn();
+ let resolveStatus: ((value: Awaited<ReturnType<QueueBackendPort['readStatus']>>) => void) | undefined;
+
+ vi.mocked(backend.readStatus).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveStatus = resolve;
+ })
+ );
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const oldRead = client.fetchQuery(queueReadModelOptions(backend, {}, onRead));
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resolveStatus?.({
+ processor: { isProcessing: false, isStarted: true },
+ queue: {
+ canceled: 0,
+ completed: 0,
+ failed: 0,
+ inProgress: 0,
+ pending: 0,
+ queueId: 'default',
+ total: 0,
+ waiting: 0,
+ },
+ });
+
+ await expect(oldRead).rejects.toThrow('no longer active');
+ expect(backend.readItemsById).not.toHaveBeenCalled();
+ expect(onRead).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.ts
index 0e24a281d6..50382a6ead 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.ts
@@ -1,5 +1,6 @@
import type { QueueBackendPort, QueueQueryScope, QueueReadModel } from '@features/queue/core/types';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { queryOptions, type QueryClient } from '@tanstack/react-query';
export const QUEUE_RECENT_WINDOW = 50;
@@ -14,25 +15,35 @@ export const queueReadModelOptions = (
scope: QueueQueryScope,
onRead?: (model: QueueReadModel) => void
) =>
- queryOptions({
- queryFn: async (): Promise<QueueReadModel> => {
- const [status, current, next, idsResult] = await Promise.all([
- backend.readStatus(scope),
- backend.readCurrent(scope),
- backend.readNext(scope),
- backend.readItemIds('desc', scope),
- ]);
- const items = await backend.readItemsById(idsResult.itemIds.slice(0, QUEUE_RECENT_WINDOW));
-
- const model = { current, items, next, scope, status };
-
- onRead?.(model);
-
- return model;
- },
- queryKey: queueKeys.readModel(scope),
- staleTime: 5_000,
- });
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: async ({ signal }): Promise<QueueReadModel> => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const [status, current, next, idsResult] = await Promise.all([
+ backend.readStatus(scope, requestSignal),
+ backend.readCurrent(scope, requestSignal),
+ backend.readNext(scope, requestSignal),
+ backend.readItemIds('desc', scope, requestSignal),
+ ]);
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+ const items = await backend.readItemsById(idsResult.itemIds.slice(0, QUEUE_RECENT_WINDOW), requestSignal);
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+ const model = { current, items, next, scope, status };
+
+ onRead?.(model);
+
+ return model;
+ },
+ queryKey: queueKeys.readModel(scope),
+ staleTime: 5_000,
+ });
+ })();
/** Coalesced by QueryClient; only active queue observers refetch. */
export const invalidateQueueReadModels = async (queryClient: QueryClient): Promise<void> => {
diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts
index a4eaa6b6fa..d6f541150f 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts
@@ -1,3 +1,4 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createQueueRealtimeRuntime } from './realtimeRuntime';
@@ -55,8 +56,10 @@ describe('queue realtime runtime', () => {
vi.advanceTimersByTime(50);
expect(invalidate).toHaveBeenCalledTimes(1);
+ progress.clearAll.mockClear();
runtime.dispose();
expect(detachers.every((detach) => detach.mock.calls.length === 1)).toBe(true);
+ expect(progress.clearAll).toHaveBeenCalledOnce();
});
it('updates transient progress without invalidating the queue list', () => {
@@ -93,4 +96,23 @@ describe('queue realtime runtime', () => {
expect(progress.clear).toHaveBeenCalledWith(43);
runtime.dispose();
});
+
+ it('ignores timers and socket callbacks after its account scope expires', () => {
+ const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });
+
+ runtime.start();
+ progress.set.mockClear();
+ accountLifecycle.invalidate();
+
+ handlers.get('invocation_progress')?.({
+ item_id: 42,
+ message: 'Old account',
+ percentage: 0.5,
+ } as never);
+ vi.advanceTimersByTime(50);
+
+ expect(progress.set).not.toHaveBeenCalled();
+ expect(invalidate).not.toHaveBeenCalled();
+ runtime.dispose();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts
index 9df7742221..55de021ca6 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts
@@ -6,6 +6,7 @@ import type {
} from '@features/queue/data/events';
import { isTerminalBackendStatus } from '@features/queue/data/events';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
export interface QueueItemProgressPort {
clear(itemId: number): void;
@@ -43,23 +44,28 @@ export const createQueueRealtimeRuntime = ({
progress: QueueItemProgressPort;
refreshModelCache: () => void | Promise<void>;
}): QueueRealtimeRuntime => {
+ const owner = captureAccountScope();
const detachers: Array<() => void> = [];
let invalidationTimer: ReturnType<typeof setTimeout> | null = null;
let isStarted = false;
+ const isActive = (): boolean => isStarted && isAccountScopeCurrent(owner);
const scheduleInvalidation = (): void => {
- if (invalidationTimer !== null) {
+ if (!isActive() || invalidationTimer !== null) {
return;
}
invalidationTimer = setTimeout(() => {
invalidationTimer = null;
- void invalidate();
+
+ if (isActive()) {
+ void invalidate();
+ }
}, coalesceMs);
};
const start = (): void => {
- if (isStarted) {
+ if (isStarted || !isAccountScopeCurrent(owner)) {
return;
}
@@ -69,6 +75,10 @@ export const createQueueRealtimeRuntime = ({
detachers.push(
backend.on('queue_item_status_changed', (payload: never) => {
+ if (!isActive()) {
+ return;
+ }
+
const event = payload as unknown as QueueItemStatusChangedEvent;
if (isTerminalBackendStatus(event.status) && event.status !== 'completed') {
@@ -82,11 +92,19 @@ export const createQueueRealtimeRuntime = ({
backend.on('queue_items_retried', scheduleInvalidation),
backend.on('queue_items_canceled', scheduleInvalidation),
backend.on('invocation_started', (payload: never) => {
+ if (!isActive()) {
+ return;
+ }
+
const event = payload as unknown as InvocationStartedEvent;
progress.set(event.item_id, { message: '', percentage: null });
}),
backend.on('invocation_progress', (payload: never) => {
+ if (!isActive()) {
+ return;
+ }
+
const event = payload as unknown as InvocationProgressEvent;
progress.set(event.item_id, {
@@ -98,9 +116,15 @@ export const createQueueRealtimeRuntime = ({
});
}),
backend.on('model_load_complete', () => {
- void refreshModelCache();
+ if (isActive()) {
+ void refreshModelCache();
+ }
}),
backend.onConnectionChange((status) => {
+ if (!isActive()) {
+ return;
+ }
+
if (status === 'connected') {
progress.clearAll();
scheduleInvalidation();
@@ -111,6 +135,8 @@ export const createQueueRealtimeRuntime = ({
};
const dispose = (): void => {
+ isStarted = false;
+
for (const detach of detachers.splice(0)) {
detach();
}
@@ -120,7 +146,7 @@ export const createQueueRealtimeRuntime = ({
invalidationTimer = null;
}
- isStarted = false;
+ progress.clearAll();
};
return { dispose, start };
diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts
new file mode 100644
index 0000000000..8aec76ab08
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts
@@ -0,0 +1,59 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const transport = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', () => transport);
+
+import { cancelCurrentQueueItem, cancelScopedQueueItems, clearFailedQueueItems, clearScopedQueue } from './serverApi';
+
+describe('queue command account ownership', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('user-a');
+ transport.apiFetchJson.mockReset();
+ });
+
+ it.each([
+ {
+ name: 'clear failed',
+ resolveFirst: { item_ids: [11], limit: 1, offset: 0 },
+ run: () => clearFailedQueueItems({ originPrefix: 'webv2:p:a:' }),
+ },
+ {
+ name: 'clear scoped',
+ resolveFirst: { item_ids: [11], limit: 1, offset: 0 },
+ run: () => clearScopedQueue({ originPrefix: 'webv2:p:a:' }),
+ },
+ {
+ name: 'cancel current',
+ resolveFirst: { item_id: 11, status: 'in_progress' },
+ run: () => cancelCurrentQueueItem(),
+ },
+ {
+ name: 'cancel scoped',
+ resolveFirst: { item_ids: [11], limit: 1, offset: 0 },
+ run: () => cancelScopedQueueItems({ originPrefix: 'webv2:p:a:' }),
+ },
+ ])('does not start the second $name request after an account switch', async ({ resolveFirst, run }) => {
+ let resolveRequest: ((value: unknown) => void) | undefined;
+ transport.apiFetchJson.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveRequest = resolve;
+ })
+ );
+
+ const oldCommand = run();
+ const signal = (transport.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resolveRequest?.(resolveFirst);
+
+ await expect(oldCommand).rejects.toThrow('no longer active');
+ expect(signal?.aborted).toBe(true);
+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
index 261affd1fa..a5e21be0fe 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts
@@ -5,6 +5,7 @@ import type {
QueueServerItemDTO,
} from '@features/queue/data/serverTypes';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { apiFetchJson } from '@platform/transport/http';
const QUEUE_ID = 'default';
@@ -24,38 +25,52 @@ const buildQueryString = (params: Record<string, string | undefined>): string =>
return queryString ? `?${queryString}` : '';
};
-export const getQueueStatus = (scope: QueueQueryScope = {}): Promise<QueueAndProcessorStatusDTO> =>
+export const getQueueStatus = (
+ scope: QueueQueryScope = {},
+ signal?: AbortSignal
+): Promise<QueueAndProcessorStatusDTO> =>
apiFetchJson<QueueAndProcessorStatusDTO>(
- buildQueueUrl(`status${buildQueryString({ origin_prefix: scope.originPrefix })}`)
+ buildQueueUrl(`status${buildQueryString({ origin_prefix: scope.originPrefix })}`),
+ { signal }
);
-export const getCurrentQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItemDTO | null> =>
+export const getCurrentQueueItem = (
+ scope: QueueQueryScope = {},
+ signal?: AbortSignal
+): Promise<QueueServerItemDTO | null> =>
apiFetchJson<QueueServerItemDTO | null>(
- buildQueueUrl(`current${buildQueryString({ origin_prefix: scope.originPrefix })}`)
+ buildQueueUrl(`current${buildQueryString({ origin_prefix: scope.originPrefix })}`),
+ { signal }
);
-export const getNextQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItemDTO | null> =>
+export const getNextQueueItem = (
+ scope: QueueQueryScope = {},
+ signal?: AbortSignal
+): Promise<QueueServerItemDTO | null> =>
apiFetchJson<QueueServerItemDTO | null>(
- buildQueueUrl(`next${buildQueryString({ origin_prefix: scope.originPrefix })}`)
+ buildQueueUrl(`next${buildQueryString({ origin_prefix: scope.originPrefix })}`),
+ { signal }
);
-export const getQueueItem = (itemId: number): Promise<QueueServerItemDTO> =>
- apiFetchJson<QueueServerItemDTO>(buildQueueUrl(`i/${itemId}`));
+export const getQueueItem = (itemId: number, signal?: AbortSignal): Promise<QueueServerItemDTO> =>
+ apiFetchJson<QueueServerItemDTO>(buildQueueUrl(`i/${itemId}`), { signal });
-export const listAllQueueItems = (): Promise<QueueServerItemDTO[]> =>
- apiFetchJson<QueueServerItemDTO[]>(buildQueueUrl('list_all'));
+export const listAllQueueItems = (signal?: AbortSignal): Promise<QueueServerItemDTO[]> =>
+ apiFetchJson<QueueServerItemDTO[]>(buildQueueUrl('list_all'), { signal });
export const getQueueItemIds = (
orderDir: 'asc' | 'desc' = 'desc',
- scope: QueueQueryScope = {}
+ scope: QueueQueryScope = {},
+ signal?: AbortSignal
): Promise<QueueItemIdsResultDTO> =>
apiFetchJson<QueueItemIdsResultDTO>(
buildQueueUrl(
`item_ids${buildQueryString({ order_dir: orderDir.toUpperCase(), origin_prefix: scope.originPrefix })}`
- )
+ ),
+ { signal }
);
-export const getQueueItemsByIds = (itemIds: number[]): Promise<QueueServerItemDTO[]> => {
+export const getQueueItemsByIds = (itemIds: number[], signal?: AbortSignal): Promise<QueueServerItemDTO[]> => {
if (itemIds.length === 0) {
return Promise.resolve([]);
}
@@ -63,53 +78,71 @@ export const getQueueItemsByIds = (itemIds: number[]): Promise<QueueServerItemDT
return apiFetchJson<QueueServerItemDTO[]>(buildQueueUrl('items_by_ids'), {
body: JSON.stringify({ item_ids: itemIds }),
method: 'POST',
+ signal,
});
};
-export const clearQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('clear'), { method: 'PUT' });
+export const clearQueue = (signal?: AbortSignal): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('clear'), { method: 'PUT', signal });
-export const pruneQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('prune'), { method: 'PUT' });
+export const pruneQueue = (signal?: AbortSignal): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('prune'), { method: 'PUT', signal });
-export const deleteQueueItem = (itemId: number): Promise<unknown> =>
- apiFetchJson(buildQueueUrl(`i/${itemId}`), { method: 'DELETE' });
+export const deleteQueueItem = (itemId: number, signal?: AbortSignal): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl(`i/${itemId}`), { method: 'DELETE', signal });
-export const deleteQueueItems = async (itemIds: number[]): Promise<void> => {
- await Promise.all(itemIds.map(deleteQueueItem));
+export const deleteQueueItems = async (itemIds: number[], signal?: AbortSignal): Promise<void> => {
+ await Promise.all(itemIds.map((itemId) => deleteQueueItem(itemId, signal)));
};
-export const cancelQueueItems = async (itemIds: number[]): Promise<void> => {
- await Promise.all(itemIds.map(cancelQueueItem));
+export const cancelQueueItems = async (itemIds: number[], signal?: AbortSignal): Promise<void> => {
+ await Promise.all(itemIds.map((itemId) => cancelQueueItem(itemId, signal)));
};
export const clearFailedQueueItems = async (scope: QueueQueryScope = {}): Promise<void> => {
- const idsResult = await getQueueItemIds('desc', scope);
- const items = await getQueueItemsByIds(idsResult.item_ids);
+ const owner = captureAccountScope();
+ const idsResult = await getQueueItemIds('desc', scope, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ const items = await getQueueItemsByIds(idsResult.item_ids, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const failedItemIds = items.filter((item) => item.status === 'failed').map((item) => item.item_id);
- await deleteQueueItems(failedItemIds);
+ await deleteQueueItems(failedItemIds, owner.signal);
+ assertAccountScopeCurrent(owner);
};
export const clearScopedQueue = async (scope: QueueQueryScope = {}): Promise<void> => {
+ const owner = captureAccountScope();
+
if (!scope.originPrefix) {
- await clearQueue();
+ await clearQueue(owner.signal);
+ assertAccountScopeCurrent(owner);
return;
}
- const idsResult = await getQueueItemIds('desc', scope);
- await deleteQueueItems(idsResult.item_ids);
+ const idsResult = await getQueueItemIds('desc', scope, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ await deleteQueueItems(idsResult.item_ids, owner.signal);
+ assertAccountScopeCurrent(owner);
};
-export const cancelAllExceptCurrent = (): Promise<unknown> =>
- apiFetchJson(buildQueueUrl('cancel_all_except_current'), { method: 'PUT' });
+export const cancelAllExceptCurrent = (signal?: AbortSignal): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('cancel_all_except_current'), { method: 'PUT', signal });
-export const cancelQueueItem = (itemId: number): Promise<unknown> =>
- apiFetchJson(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT' });
+export const cancelQueueItem = (itemId: number, signal?: AbortSignal): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT', signal });
export const cancelCurrentQueueItem = async (): Promise<void> => {
- const current = await getCurrentQueueItem();
+ const owner = captureAccountScope();
+ const current = await getCurrentQueueItem({}, owner.signal);
+ assertAccountScopeCurrent(owner);
if (current) {
- await cancelQueueItem(current.item_id);
+ await cancelQueueItem(current.item_id, owner.signal);
+ assertAccountScopeCurrent(owner);
}
};
@@ -117,8 +150,13 @@ export const cancelScopedQueueItems = async (
scope: QueueQueryScope = {},
currentItemId?: number | null
): Promise<void> => {
- const idsResult = await getQueueItemIds('desc', scope);
- const items = await getQueueItemsByIds(idsResult.item_ids);
+ const owner = captureAccountScope();
+ const idsResult = await getQueueItemIds('desc', scope, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ const items = await getQueueItemsByIds(idsResult.item_ids, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const cancellableItemIds = items
.filter(
(item) =>
@@ -128,7 +166,8 @@ export const cancelScopedQueueItems = async (
)
.map((item) => item.item_id);
- await cancelQueueItems(cancellableItemIds);
+ await cancelQueueItems(cancellableItemIds, owner.signal);
+ assertAccountScopeCurrent(owner);
};
export const cancelByBatchIds = (batchIds: string[]): Promise<unknown> =>
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
index ee736a1902..3bc9b55363 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -1,5 +1,6 @@
import type { QueueEnqueueGenerateRequest, QueueEnqueueWorkflowRequest } from '@features/queue/core/types';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
@@ -142,6 +143,7 @@ describe('enqueueWorkflow', () => {
describe('getResultImages', () => {
beforeEach(() => {
+ accountLifecycle.activate('test-account');
mocks.apiFetchJson.mockReset();
});
@@ -221,4 +223,31 @@ describe('getResultImages', () => {
expect(images.map((image) => image.imageName)).toEqual(['external-a.png', 'external-b.png']);
});
+
+ it('does not issue image requests from queue data resolved after an account switch', async () => {
+ accountLifecycle.activate('user-a');
+ let resolveItem: ((item: unknown) => void) | undefined;
+ mocks.apiFetchJson.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveItem = resolve;
+ })
+ );
+ const { getResultImages } = await import('./submissionApi');
+
+ const oldResult = getResultImages(1, 'source-a', '2026-06-15T00:00:00.000Z');
+ const signal = (mocks.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resolveItem?.({
+ item_id: 1,
+ session: { results: { output: { image: { image_name: 'user-a.png' } } } },
+ status: 'completed',
+ });
+
+ await expect(oldResult).rejects.toThrow('no longer active');
+ expect(signal?.aborted).toBe(true);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index 98f11453ed..6d3f817222 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -6,6 +6,7 @@ import type {
QueueResultImageOptions,
} from '@features/queue/core/types';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { absolutizeApiUrl, ApiError, apiFetchJson } from '@platform/transport/http';
import type { QueueImageDTO, QueueServerItemDTO } from './serverTypes';
@@ -140,10 +141,11 @@ const getResultImageNames = (queueItem: QueueServerItemDTO, options?: QueueResul
const getResultImage = async (
imageName: string,
queuedAt: string,
- sourceQueueItemId: string
+ sourceQueueItemId: string,
+ signal: AbortSignal
): Promise<QueueResultImage | null> => {
try {
- const image = await apiFetchJson<QueueImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);
+ const image = await apiFetchJson<QueueImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`, { signal });
return {
height: image.height,
@@ -169,10 +171,16 @@ export const getResultImages = async (
queuedAt: string,
options?: QueueResultImageOptions
): Promise<QueueResultImage[]> => {
- const item = await getQueueItem(itemId);
+ const owner = captureAccountScope();
+ const item = await getQueueItem(itemId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const images = await Promise.all(
- getResultImageNames(item, options).map((imageName) => getResultImage(imageName, queuedAt, sourceQueueItemId))
+ getResultImageNames(item, options).map((imageName) =>
+ getResultImage(imageName, queuedAt, sourceQueueItemId, owner.signal)
+ )
);
+ assertAccountScopeCurrent(owner);
return images.filter((image): image is QueueResultImage => image !== null);
};
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index b8ab55e4db..601b2bb23e 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -17,6 +17,7 @@ import {
type QueueNodeExecutionPort,
type ReconcileInput,
} from '@features/queue/runtime/coordinator';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
export interface QueueResultDestinationPort {
@@ -175,6 +176,7 @@ export const createQueueRuntime = ({
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
}): QueueRuntime => {
+ const owner = captureAccountScope();
const commands = history.commands;
const startedQueueItemIds = new Set<string>();
const cancelledQueueItemIds = new Set<string>();
@@ -182,9 +184,10 @@ export const createQueueRuntime = ({
let reconcileState: 'idle' | 'running' | 'done' = 'idle';
let isDisposed = false;
let isStarted = false;
+ const isActive = (): boolean => !isDisposed && isAccountScopeCurrent(owner);
const addImagesToDestination = async (queueItem: QueueItem, imageNames: string[]): Promise<void> => {
- if (queueItem.snapshot.destination !== 'gallery') {
+ if (!isActive() || queueItem.snapshot.destination !== 'gallery') {
return;
}
@@ -223,9 +226,14 @@ export const createQueueRuntime = ({
queueItem.snapshot.submittedAt,
getQueueItemResultImageOptions(queueItem)
);
+
+ if (!isActive()) {
+ return;
+ }
+
const images = await deliverVisibleImages(queueItem, allImages);
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -234,7 +242,7 @@ export const createQueueRuntime = ({
commands.refreshBackendData();
}
} catch (error) {
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -264,9 +272,14 @@ export const createQueueRuntime = ({
queueItem.snapshot.submittedAt,
getQueueItemResultImageOptions(queueItem)
);
+
+ if (!isActive()) {
+ return;
+ }
+
const visibleImages = await deliverVisibleImages(queueItem, images);
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -280,7 +293,7 @@ export const createQueueRuntime = ({
commands.refreshBackendData();
}
} catch (error) {
- if (!isDisposed) {
+ if (isActive()) {
commands.recordError({
area: 'queue-results',
message: toErrorMessage(error),
@@ -294,6 +307,10 @@ export const createQueueRuntime = ({
const coordinator = createQueueCoordinator(
{
onBackendItemCancelled: (localQueueItemId, backendItemId) => {
+ if (!isActive()) {
+ return;
+ }
+
const target = getRouteTarget(history, localQueueItemId);
if (!target?.queueItem || target.queueItem.cancelledBackendItemIds?.includes(backendItemId)) {
@@ -307,6 +324,10 @@ export const createQueueRuntime = ({
});
},
onBackendItemComplete: (localQueueItemId, backendItemId) => {
+ if (!isActive()) {
+ return;
+ }
+
const target = getRouteTarget(history, localQueueItemId);
if (!target?.queueItem || target.queueItem.completedBackendItemIds?.includes(backendItemId)) {
@@ -315,7 +336,11 @@ export const createQueueRuntime = ({
return routeBackendItemResults(target.project.id, target.queueItem, backendItemId);
},
- onGalleryRefresh: commands.refreshBackendData,
+ onGalleryRefresh: () => {
+ if (isActive()) {
+ commands.refreshBackendData();
+ }
+ },
},
{ backend, modelLoads, nodeExecution }
);
@@ -340,7 +365,7 @@ export const createQueueRuntime = ({
request
.then(({ batchId, itemIds }) => {
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -355,7 +380,7 @@ export const createQueueRuntime = ({
return routeRunResults(coordinator, project.id, queueItem);
})
.catch((error: unknown) => {
- if (!isDisposed) {
+ if (isActive()) {
commands.setStatus({
error: toErrorMessage(error),
projectId: project.id,
@@ -367,7 +392,7 @@ export const createQueueRuntime = ({
};
const processQueueItems = (): void => {
- if (isDisposed || reconcileState !== 'done') {
+ if (!isActive() || reconcileState !== 'done') {
return;
}
@@ -387,7 +412,7 @@ export const createQueueRuntime = ({
coordinator
.cancelRun({ backendBatchId: queueItem.backendBatchId, backendItemIds: queueItem.backendItemIds })
.catch((error: unknown) => {
- if (!isDisposed) {
+ if (isActive()) {
commands.recordError({
area: 'queue-cancel',
message: toErrorMessage(error),
@@ -402,7 +427,7 @@ export const createQueueRuntime = ({
const reconcile = (): void => {
if (
- isDisposed ||
+ !isActive() ||
reconcileState !== 'idle' ||
!history.getSnapshot().isHydrated ||
history.getSnapshot().connectionStatus !== 'connected'
@@ -433,7 +458,7 @@ export const createQueueRuntime = ({
coordinator
.reconcile(inputs)
.then((outcomes) => {
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -469,7 +494,7 @@ export const createQueueRuntime = ({
}
})
.catch((error: unknown) => {
- if (isDisposed) {
+ if (!isActive()) {
return;
}
@@ -493,7 +518,7 @@ export const createQueueRuntime = ({
}
})
.finally(() => {
- if (!isDisposed) {
+ if (isActive()) {
reconcileState = 'done';
processQueueItems();
}
@@ -506,7 +531,7 @@ export const createQueueRuntime = ({
};
const start = (): void => {
- if (isStarted || isDisposed) {
+ if (isStarted || !isActive()) {
return;
}
@@ -516,6 +541,10 @@ export const createQueueRuntime = ({
detachers.push(
history.subscribe(synchronize),
backend.onConnectionChange((status, error) => {
+ if (!isActive()) {
+ return;
+ }
+
commands.setConnectionStatus({ error, status });
synchronize();
})
@@ -530,6 +559,8 @@ export const createQueueRuntime = ({
detach();
}
+ startedQueueItemIds.clear();
+ cancelledQueueItemIds.clear();
coordinator.dispose();
};
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index abed97a06f..7be105bd1a 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -12,6 +12,7 @@ import {
buildUtilityQueueItemOrigin,
type QueueItemStatusChangedEvent,
} from '@features/queue/data/events';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { createSocketHub, type BackendSocket } from '@platform/transport/socketHub';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -26,6 +27,15 @@ import {
type QueueNodeExecutionPort,
} from './coordinator';
+const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((settle) => {
+ resolve = settle;
+ });
+
+ return { promise, resolve };
+};
+
class FakeSocket implements BackendSocket {
readonly emitted: { event: string; payload: unknown }[] = [];
private readonly handlers = new Map<string, ((payload: never) => void)[]>();
@@ -163,6 +173,9 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har
clear: (queueItemId) => {
progressEntries.delete(queueItemId);
},
+ clearAll: () => {
+ progressEntries.clear();
+ },
set: (queueItemId, value) => {
progressEntries.set(queueItemId, value);
},
@@ -567,6 +580,28 @@ describe('queueCoordinator', () => {
expect(harness.progressImage.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });
});
+ it('does not let an old routing finalizer clear replacement-account progress', async () => {
+ const routing = deferred<void>();
+
+ harness.callbacks.onBackendItemComplete = vi.fn(() => routing.promise);
+ harness.coordinator.connect();
+ await harness.coordinator.submitGenerate('local-1', generateRequest);
+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');
+
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));
+ await resultsPromise;
+ harness.coordinator.dispose();
+ const clearsAfterDispose = harness.progressImage.clear.mock.calls.length;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('replacement-account');
+ routing.resolve();
+ await routing.promise;
+ await Promise.resolve();
+
+ expect(harness.progressImage.clear).toHaveBeenCalledTimes(clearsAfterDispose);
+ });
+
it('notifies when one backend item in a batch completes', async () => {
harness.callbacks.onBackendItemComplete = vi.fn();
harness.api.enqueueGenerate.mockResolvedValue({
@@ -896,10 +931,26 @@ describe('queueCoordinator', () => {
harness.coordinator.connect();
await harness.coordinator.submitGenerate('local-1', generateRequest);
+ expect(harness.progressEntries.size).toBe(1);
+
harness.coordinator.dispose();
harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));
expect(harness.nodeExecution.settleRunning).not.toHaveBeenCalled();
+ expect(harness.progressEntries.size).toBe(0);
+ });
+
+ it('does not adopt an enqueue response that completes after its account scope expires', async () => {
+ const acceptance = deferred<{ batchId: string; enqueued: number; itemIds: number[]; requested: number }>();
+
+ harness.api.enqueueGenerate.mockReturnValue(acceptance.promise);
+ const submission = harness.coordinator.submitGenerate('local-1', generateRequest);
+
+ accountLifecycle.invalidate();
+ acceptance.resolve({ batchId: 'old-account-batch', enqueued: 1, itemIds: [42], requested: 1 });
+
+ await expect(submission).rejects.toBeInstanceOf(QueueItemCancelledError);
+ expect(harness.progressEntries.size).toBe(0);
});
});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index 1b8a51b3bc..07182c09a3 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -30,6 +30,7 @@ import {
type ProgressImageTarget,
} from '@features/queue/data/progressImageStore';
import { queueItemProgressStore, type QueueItemProgressSink } from '@features/queue/data/progressStore';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
const GALLERY_REFRESH_COALESCE_MS = 400;
@@ -188,6 +189,7 @@ export const createQueueCoordinator = (
sweepIntervalMs?: number;
}
): QueueCoordinator => {
+ const owner = captureAccountScope();
const backend = options.backend;
const activeProgressTarget = options.activeProgressTarget ?? activeProgressTargetStore;
const progress = options.progress ?? queueItemProgressStore;
@@ -214,19 +216,27 @@ export const createQueueCoordinator = (
let galleryRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let sweepTimer: ReturnType<typeof setInterval> | null = null;
let isSweeping = false;
+ const isActive = (): boolean => !isDisposed && isAccountScopeCurrent(owner);
const scheduleGalleryRefresh = (): void => {
- if (isDisposed || galleryRefreshTimer !== null) {
+ if (!isActive() || galleryRefreshTimer !== null) {
return;
}
galleryRefreshTimer = setTimeout(() => {
galleryRefreshTimer = null;
- callbacks.onGalleryRefresh();
+
+ if (isActive()) {
+ callbacks.onGalleryRefresh();
+ }
}, galleryRefreshCoalesceMs);
};
const bufferTerminalOutcome = (backendItemId: number, outcome: TerminalOutcome): void => {
+ if (!isActive()) {
+ return;
+ }
+
recentTerminalOutcomes.delete(backendItemId);
recentTerminalOutcomes.set(backendItemId, outcome);
@@ -242,6 +252,10 @@ export const createQueueCoordinator = (
};
const publishRunProgress = (localQueueItemId: string): void => {
+ if (!isActive()) {
+ return;
+ }
+
const state = runProgress.get(localQueueItemId);
if (!state) {
@@ -286,7 +300,11 @@ export const createQueueCoordinator = (
waits.delete(backendItemId);
const progressTarget = getProgressImageTarget(wait.localQueueItemId, backendItemId);
- const clearProgressImage = (): void => progressImage.clear(progressTarget);
+ const clearProgressImage = (): void => {
+ if (isActive()) {
+ progressImage.clear(progressTarget);
+ }
+ };
activeProgressTarget.clear(progressTarget);
const state = runProgress.get(wait.localQueueItemId);
@@ -352,6 +370,10 @@ export const createQueueCoordinator = (
};
const beginRun = (localQueueItemId: string, backendItemIds: number[], backendBatchId?: string): void => {
+ if (!isActive()) {
+ throw new QueueItemCancelledError(localQueueItemId);
+ }
+
runs.set(localQueueItemId, {
backendBatchId,
backendItemIds,
@@ -370,7 +392,7 @@ export const createQueueCoordinator = (
/** Slow safety net for events lost to disconnects; runs on reconnect and on a long interval. */
const sweep = async (): Promise<void> => {
- if (isSweeping || waits.size === 0) {
+ if (!isActive() || isSweeping || waits.size === 0) {
return;
}
@@ -380,9 +402,13 @@ export const createQueueCoordinator = (
await Promise.all(
[...waits.keys()].map(async (backendItemId) => {
try {
- settleFromQueueItem(await backend.getItem(backendItemId));
+ const queueItem = await backend.getItem(backendItemId);
+
+ if (isActive()) {
+ settleFromQueueItem(queueItem);
+ }
} catch (error) {
- if (error instanceof ApiError && error.status === 404) {
+ if (isActive() && error instanceof ApiError && error.status === 404) {
settleWait(backendItemId, {
error: `Queue item ${backendItemId} is no longer on the backend queue.`,
status: 'failed',
@@ -397,6 +423,10 @@ export const createQueueCoordinator = (
};
const handleStatusChanged = (event: QueueItemStatusChangedEvent): void => {
+ if (!isActive()) {
+ return;
+ }
+
const sequence = event.status_sequence;
const previousSequence = latestStatusSequences.get(event.item_id);
if (sequence !== null && previousSequence !== undefined && sequence < previousSequence) {
@@ -424,6 +454,10 @@ export const createQueueCoordinator = (
};
const handleItemsCanceled = (event: QueueItemsCanceledEvent): void => {
+ if (!isActive()) {
+ return;
+ }
+
for (const itemId of event.canceled_item_ids) {
if (waits.has(itemId)) {
settleWait(itemId, { status: 'canceled' });
@@ -432,6 +466,10 @@ export const createQueueCoordinator = (
};
const handleProgress = (event: InvocationProgressEvent): void => {
+ if (!isActive()) {
+ return;
+ }
+
const wait = waits.get(event.item_id);
if (!wait) {
@@ -465,6 +503,10 @@ export const createQueueCoordinator = (
* and, on (re)connect, schedules a gallery refresh and missed-event sweep.
*/
const handleConnectionChange = (status: BackendConnectionStatus): void => {
+ if (!isActive()) {
+ return;
+ }
+
if (status !== 'connected') {
activeProgressTarget.clear();
progressImage.clear();
@@ -481,7 +523,7 @@ export const createQueueCoordinator = (
/** Attach generation listeners to the shared socket hub. */
const connect = (): void => {
- if (isDisposed || isAttached) {
+ if (!isActive() || isAttached) {
return;
}
@@ -492,31 +534,35 @@ export const createQueueCoordinator = (
backend.on('queue_items_canceled', handleItemsCanceled),
backend.on('invocation_progress', handleProgress),
backend.on('invocation_started', (event: InvocationStartedEvent) => {
- if (!isTrackedEvent(event)) {
+ if (!isActive() || !isTrackedEvent(event)) {
return;
}
nodeExecution.started(event);
}),
backend.on('invocation_complete', (event: InvocationCompleteEvent) => {
- if (!isTrackedEvent(event)) {
+ if (!isActive() || !isTrackedEvent(event)) {
return;
}
nodeExecution.completed(event);
}),
backend.on('invocation_error', (event: InvocationErrorEvent) => {
- if (!isTrackedEvent(event)) {
+ if (!isActive() || !isTrackedEvent(event)) {
return;
}
nodeExecution.failed(event);
}),
backend.on('model_load_started', (payload: never) => {
- modelLoads.started(payload);
+ if (isActive()) {
+ modelLoads.started(payload);
+ }
}),
backend.on('model_load_complete', (payload: never) => {
- modelLoads.completed(payload);
+ if (isActive()) {
+ modelLoads.completed(payload);
+ }
})
);
@@ -534,6 +580,9 @@ export const createQueueCoordinator = (
isDisposed = true;
activeProgressTarget.clear();
progressImage.clear();
+ progress.clearAll?.();
+ nodeExecution.clearAll();
+ modelLoads.reset();
for (const detach of detachers) {
detach();
@@ -560,12 +609,16 @@ export const createQueueCoordinator = (
}
waits.clear();
+ runs.clear();
+ runProgress.clear();
+ recentTerminalOutcomes.clear();
+ latestStatusSequences.clear();
};
const reconcile = async (items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>> => {
const outcomes = new Map<string, ReconcileOutcome>();
- if (items.length === 0) {
+ if (!isActive() || items.length === 0) {
return outcomes;
}
@@ -588,6 +641,11 @@ export const createQueueCoordinator = (
)
).filter((item) => item !== undefined)
: await backend.listItems();
+
+ if (!isActive()) {
+ return outcomes;
+ }
+
const backendItemsById = new Map(backendItems.map((item) => [item.id, item]));
const backendItemsByLocalId = new Map<string, QueueBackendItem[]>();
@@ -656,20 +714,34 @@ export const createQueueCoordinator = (
const submitGenerate = async (
localQueueItemId: string,
request: QueueEnqueueGenerateRequest
- ): Promise<QueueEnqueueResult> =>
- adoptEnqueueResult(localQueueItemId, await backend.enqueueGenerate(request), 'generation');
+ ): Promise<QueueEnqueueResult> => {
+ if (!isActive()) {
+ throw new QueueItemCancelledError(localQueueItemId);
+ }
+
+ return adoptEnqueueResult(localQueueItemId, await backend.enqueueGenerate(request), 'generation');
+ };
const submitWorkflow = async (
localQueueItemId: string,
request: QueueEnqueueWorkflowRequest
- ): Promise<QueueEnqueueResult> =>
- adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow');
+ ): Promise<QueueEnqueueResult> => {
+ if (!isActive()) {
+ throw new QueueItemCancelledError(localQueueItemId);
+ }
+
+ return adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow');
+ };
const waitForResults = async (
localQueueItemId: string,
queuedAt: string,
options?: QueueResultImageOptions
): Promise<QueueResultImage[]> => {
+ if (!isActive()) {
+ throw new QueueItemCancelledError(localQueueItemId);
+ }
+
const run = runs.get(localQueueItemId);
if (!run) {
@@ -704,7 +776,9 @@ export const createQueueCoordinator = (
} finally {
runs.delete(localQueueItemId);
runProgress.delete(localQueueItemId);
- progress.clear(localQueueItemId);
+ if (isActive()) {
+ progress.clear(localQueueItemId);
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
index 71ca812016..4b10cd0f8a 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts
@@ -1,6 +1,31 @@
-import { describe, expect, it } from 'vitest';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { getModelCacheClearToast, getModelCacheUsage, normalizeModelCacheClearResult } from './modelCacheStore';
+import {
+ getModelCacheClearToast,
+ getModelCacheSnapshot,
+ getModelCacheUsage,
+ normalizeModelCacheClearResult,
+ refreshModelCacheStats,
+} from './modelCacheStore';
+
+const dependencies = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', () => ({
+ apiFetchJson: dependencies.apiFetchJson,
+ getApiErrorMessage: (error: unknown, fallback: string) => (error instanceof Error ? error.message : fallback),
+}));
+
+const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((settle) => {
+ resolve = settle;
+ });
+
+ return { promise, resolve };
+};
const t = ((key: string, values?: Record<string, unknown>) => {
const translations: Record<string, string> = {
@@ -14,6 +39,11 @@ const t = ((key: string, values?: Record<string, unknown>) => {
return translations[key] ?? key;
}) as never;
+beforeEach(() => {
+ accountLifecycle.invalidate();
+ dependencies.apiFetchJson.mockReset();
+});
+
describe('model cache stats helpers', () => {
it('uses current cache usage instead of the historical high watermark', () => {
expect(
@@ -47,4 +77,49 @@ describe('model cache stats helpers', () => {
it('normalizes legacy null clear-cache responses', () => {
expect(normalizeModelCacheClearResult(null)).toEqual({ bytes_freed: 0, models_cleared: 0 });
});
+
+ it('drops a stale stats response without releasing the replacement account refresh', async () => {
+ const first = deferred<null>();
+ const second = deferred<{
+ cache_size: number;
+ cleared: number;
+ high_watermark: number;
+ hits: number;
+ in_cache: number;
+ misses: number;
+ }>();
+
+ dependencies.apiFetchJson.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+
+ const staleRefresh = refreshModelCacheStats();
+
+ accountLifecycle.invalidate();
+
+ expect(getModelCacheSnapshot()).toEqual({ error: null, loadState: 'idle', stats: null });
+
+ const currentRefresh = refreshModelCacheStats();
+
+ first.resolve(null);
+ await staleRefresh;
+
+ expect(getModelCacheSnapshot()).toEqual({ error: null, loadState: 'loading', stats: null });
+ expect(refreshModelCacheStats()).toBe(currentRefresh);
+ expect(dependencies.apiFetchJson).toHaveBeenCalledTimes(2);
+
+ second.resolve({
+ cache_size: 100,
+ cleared: 0,
+ high_watermark: 20,
+ hits: 1,
+ in_cache: 1,
+ misses: 2,
+ });
+ await currentRefresh;
+
+ expect(getModelCacheSnapshot()).toMatchObject({
+ error: null,
+ loadState: 'loaded',
+ stats: { cache_size: 100, high_watermark: 20, in_cache: 1 },
+ });
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
index d852eab738..d71ae36d55 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts
@@ -1,5 +1,11 @@
import type { TFunction } from 'i18next';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';
@@ -79,45 +85,75 @@ export const getModelCacheClearToast = (
};
};
-interface ModelCacheSnapshot {
+export interface ModelCacheSnapshot {
stats: ModelCacheStats | null;
loadState: 'idle' | 'loading' | 'loaded' | 'error';
error: string | null;
}
-const store = createExternalStore<ModelCacheSnapshot>({ error: null, loadState: 'idle', stats: null });
+const EMPTY_MODEL_CACHE_SNAPSHOT: ModelCacheSnapshot = { error: null, loadState: 'idle', stats: null };
+const store = createExternalStore<ModelCacheSnapshot>(EMPTY_MODEL_CACHE_SNAPSHOT);
let inflight: Promise<void> | null = null;
+registerAccountOwnedResource({
+ clear: () => {
+ inflight = null;
+ store.setSnapshot(EMPTY_MODEL_CACHE_SNAPSHOT);
+ },
+ name: 'model-cache-stats',
+});
+
export const refreshModelCacheStats = (): Promise<void> => {
if (inflight) {
return inflight;
}
+ const owner = captureAccountScope();
+
if (store.getSnapshot().loadState === 'idle') {
store.patchSnapshot({ loadState: 'loading' });
}
- inflight = apiFetchJson<ModelCacheStats | null>('/api/v2/models/stats')
+ const refresh = apiFetchJson<ModelCacheStats | null>('/api/v2/models/stats', { signal: owner.signal })
.then((stats) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({ error: null, loadState: 'loaded', stats });
})
.catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load model cache stats'), loadState: 'error' });
})
.finally(() => {
- inflight = null;
+ if (inflight === refresh) {
+ inflight = null;
+ }
});
+ inflight = refresh;
return inflight;
};
export const clearModelCache = async (): Promise<ModelCacheClearResult> => {
+ const owner = captureAccountScope();
const result = await apiFetchJson<ModelCacheClearResult | null>('/api/v2/models/empty_model_cache', {
method: 'POST',
+ signal: owner.signal,
});
+
+ assertAccountScopeCurrent(owner);
await refreshModelCacheStats();
+ assertAccountScopeCurrent(owner);
+
return normalizeModelCacheClearResult(result);
};
+export const getModelCacheSnapshot = (): ModelCacheSnapshot => store.getSnapshot();
+
export const useModelCacheStats = (): ModelCacheSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.ts
index 5ca7fed451..52dd53b920 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.ts
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export interface QueueConfirmation {
@@ -19,6 +20,11 @@ export const clearQueueConfirmation = (): void => {
queueConfirmationStore.setSnapshot({ confirmation: null });
};
+registerAccountOwnedResource({
+ clear: clearQueueConfirmation,
+ name: 'queue-confirmation',
+});
+
export const getQueueConfirmation = (): QueueConfirmation | null => queueConfirmationStore.getSnapshot().confirmation;
export const useQueueConfirmation = (): QueueConfirmation | null =>
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueUiStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueUiStore.ts
index f95a23f7c9..5c4f3e4553 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/queueUiStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueUiStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export interface QueueItemRevealRequest {
@@ -20,6 +21,16 @@ export const clearPendingQueueItemReveal = (requestId: number): void => {
}
};
+const resetQueueUi = (): void => {
+ nextRevealRequestId = 0;
+ queueRevealStore.setSnapshot({ pendingReveal: null });
+};
+
+registerAccountOwnedResource({
+ clear: resetQueueUi,
+ name: 'queue-ui',
+});
+
export const getPendingQueueItemReveal = (): QueueItemRevealRequest | null =>
queueRevealStore.getSnapshot().pendingReveal;
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
index 0752e0ce18..12a2c7dd98 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
@@ -65,33 +65,47 @@ interface WorkflowRecordDTO {
}
/** Returns the stored workflow JSON, with the record id stamped in. */
-export const getLibraryWorkflow = async (workflowId: string): Promise<Record<string, unknown>> => {
- const record = await apiFetchJson<WorkflowRecordDTO>(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`);
+export const getLibraryWorkflow = async (
+ workflowId: string,
+ signal?: AbortSignal
+): Promise<Record<string, unknown>> => {
+ const record = await apiFetchJson<WorkflowRecordDTO>(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, {
+ signal,
+ });
return { ...record.workflow, id: record.workflow_id };
};
-export const createLibraryWorkflow = async (workflow: Record<string, unknown>): Promise<string> => {
+export const createLibraryWorkflow = async (
+ workflow: Record<string, unknown>,
+ signal?: AbortSignal
+): Promise<string> => {
const { id: _id, ...workflowWithoutId } = workflow;
const record = await apiFetchJson<WorkflowRecordDTO>('/api/v1/workflows/', {
body: JSON.stringify({ workflow: workflowWithoutId }),
method: 'POST',
+ signal,
});
return record.workflow_id;
};
-export const updateLibraryWorkflow = async (workflowId: string, workflow: Record<string, unknown>): Promise<void> => {
+export const updateLibraryWorkflow = async (
+ workflowId: string,
+ workflow: Record<string, unknown>,
+ signal?: AbortSignal
+): Promise<void> => {
await apiFetchJson(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, {
body: JSON.stringify({ workflow: { ...workflow, id: workflowId } }),
method: 'PATCH',
+ signal,
});
};
-export const deleteLibraryWorkflow = async (workflowId: string): Promise<void> => {
- await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, { method: 'DELETE' });
+export const deleteLibraryWorkflow = async (workflowId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, { method: 'DELETE', signal });
};
-export const touchLibraryWorkflowOpenedAt = async (workflowId: string): Promise<void> => {
- await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT' });
+export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT', signal });
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts
new file mode 100644
index 0000000000..c3acb313d1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts
@@ -0,0 +1,82 @@
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as libraryCacheModule from './libraryCache';
+
+const api = vi.hoisted(() => ({
+ getLibraryWorkflow: vi.fn(),
+ listLibraryWorkflows: vi.fn(),
+}));
+
+vi.mock('./api', () => api);
+
+let account: typeof accountLifecycleModule;
+let cache: typeof libraryCacheModule;
+
+const params = { category: 'user' as const, page: 1, perPage: 20 };
+
+beforeEach(async () => {
+ vi.resetModules();
+ api.getLibraryWorkflow.mockReset();
+ api.listLibraryWorkflows.mockReset();
+ cache = await import('./libraryCache');
+ account = await import('@platform/state/accountLifecycle');
+});
+
+describe('workflow library account ownership', () => {
+ it('clears pages and payloads synchronously on account invalidation', async () => {
+ account.accountLifecycle.activate('user-a');
+ api.listLibraryWorkflows.mockResolvedValue({ items: [], page: 1, pages: 1, per_page: 20, total: 0 });
+ api.getLibraryWorkflow.mockResolvedValue({ id: 'workflow-a' });
+
+ await cache.listLibraryWorkflowsCached(params);
+ await cache.getLibraryWorkflowCached('workflow-a');
+ expect(cache.getCachedWorkflowPage(params)).not.toBeNull();
+
+ account.accountLifecycle.invalidate();
+
+ expect(cache.getCachedWorkflowPage(params)).toBeNull();
+ api.getLibraryWorkflow.mockResolvedValue({ id: 'after-clear' });
+ await cache.getLibraryWorkflowCached('workflow-a');
+ expect(api.getLibraryWorkflow).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects delayed page and payload completions from the prior epoch', async () => {
+ account.accountLifecycle.activate('user-a');
+ let resolvePage: ((value: unknown) => void) | undefined;
+ let resolveWorkflow: ((value: Record<string, unknown>) => void) | undefined;
+ api.listLibraryWorkflows.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePage = resolve;
+ })
+ );
+ api.getLibraryWorkflow.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveWorkflow = resolve;
+ })
+ );
+
+ const oldPage = cache.listLibraryWorkflowsCached(params);
+ const oldWorkflow = cache.getLibraryWorkflowCached('shared-id');
+ const pageSignal = api.listLibraryWorkflows.mock.calls[0]?.[0]?.signal as AbortSignal;
+ const workflowSignal = api.getLibraryWorkflow.mock.calls[0]?.[1] as AbortSignal;
+
+ expect(pageSignal.aborted).toBe(false);
+ expect(workflowSignal.aborted).toBe(false);
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b');
+
+ expect(pageSignal.aborted).toBe(true);
+ expect(workflowSignal.aborted).toBe(true);
+ resolvePage?.({ items: [{ workflow_id: 'a' }], page: 1, pages: 1, per_page: 20, total: 1 });
+ resolveWorkflow?.({ owner: 'a' });
+
+ await expect(oldPage).rejects.toThrow('no longer active');
+ await expect(oldWorkflow).rejects.toThrow('no longer active');
+ expect(cache.getCachedWorkflowPage(params)).toBeNull();
+
+ api.getLibraryWorkflow.mockResolvedValueOnce({ owner: 'b' });
+ await expect(cache.getLibraryWorkflowCached('shared-id')).resolves.toEqual({ owner: 'b' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
index ce69eaec0d..8c977bd9ae 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
@@ -1,3 +1,9 @@
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
+
import { getLibraryWorkflow, listLibraryWorkflows, type ListWorkflowsParams, type WorkflowLibraryPage } from './api';
/**
@@ -18,23 +24,37 @@ export const getCachedWorkflowPage = (params: ListWorkflowsParams): WorkflowLibr
/** Fetches a page and stores it; callers show `getCachedWorkflowPage` while this resolves. */
export const listLibraryWorkflowsCached = async (params: ListWorkflowsParams): Promise<WorkflowLibraryPage> => {
- const result = await listLibraryWorkflows(params);
+ const owner = captureAccountScope();
+ const signal = params.signal ? AbortSignal.any([params.signal, owner.signal]) : owner.signal;
+ const result = await listLibraryWorkflows({ ...params, signal });
+ assertAccountScopeCurrent(owner);
+ signal.throwIfAborted();
pageCache.set(getPageKey(params), result);
return result;
};
/** Workflow payloads are immutable per save; cache hits skip the fetch entirely. */
-export const getLibraryWorkflowCached = async (workflowId: string): Promise<Record<string, unknown>> => {
+export const getLibraryWorkflowCached = async (
+ workflowId: string,
+ externalSignal?: AbortSignal
+): Promise<Record<string, unknown>> => {
+ const owner = captureAccountScope();
+ const signal = externalSignal ? AbortSignal.any([externalSignal, owner.signal]) : owner.signal;
+
+ signal.throwIfAborted();
const cached = workflowCache.get(workflowId);
if (cached) {
+ assertAccountScopeCurrent(owner);
return cached;
}
- const result = await getLibraryWorkflow(workflowId);
+ const result = await getLibraryWorkflow(workflowId, signal);
+ assertAccountScopeCurrent(owner);
+ signal.throwIfAborted();
workflowCache.set(workflowId, result);
return result;
@@ -44,3 +64,8 @@ export const invalidateWorkflowLibraryCache = (): void => {
pageCache.clear();
workflowCache.clear();
};
+
+registerAccountOwnedResource({
+ clear: invalidateWorkflowLibraryCache,
+ name: 'workflow-library',
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
index 9a5dafb552..87f1425f9b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
@@ -7,6 +7,11 @@ import type {
InvocationTemplatesSnapshot,
} from '@features/workflow/core/types';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';
@@ -19,7 +24,15 @@ export type { InvocationTemplatesSnapshot } from '@features/workflow/core/types'
* than in project state.
*/
-const store = createExternalStore<InvocationTemplatesSnapshot>({ error: null, status: 'idle', templates: {} });
+const EMPTY_INVOCATION_TEMPLATES: InvocationTemplatesSnapshot = { error: null, status: 'idle', templates: {} };
+const store = createExternalStore<InvocationTemplatesSnapshot>(EMPTY_INVOCATION_TEMPLATES);
+
+registerAccountOwnedResource({
+ clear: () => {
+ store.setSnapshot(EMPTY_INVOCATION_TEMPLATES);
+ },
+ name: 'invocation-templates',
+});
type JsonObject = Record<string, unknown>;
@@ -352,14 +365,24 @@ export const parseOpenApiToTemplates = (openApiDocument: unknown): InvocationTem
};
export const refreshInvocationTemplates = async (): Promise<void> => {
+ const owner = captureAccountScope();
+
store.patchSnapshot({ error: null, status: 'loading' });
try {
// FastAPI serves the schema at the app root (proxied in dev), not under /api.
- const openApiDocument = await apiFetchJson<unknown>('/openapi.json');
+ const openApiDocument = await apiFetchJson<unknown>('/openapi.json', { signal: owner.signal });
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
store.setSnapshot({ error: null, status: 'loaded', templates: parseOpenApiToTemplates(openApiDocument) });
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.patchSnapshot({
error: getApiErrorMessage(error, 'Failed to load node definitions from the backend.'),
status: 'error',
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
index d4774ea98b..4193617674 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
@@ -3,6 +3,11 @@ import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCo
import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
import { parseWorkflowJson } from '@features/workflow/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { useTranslation } from 'react-i18next';
@@ -18,10 +23,15 @@ export const PendingLibraryWorkflowLoader = () => {
const { t } = useTranslation();
const { replace } = useProjectGraphCommands();
const notify = useWorkflowNotifications();
- useMountEffect(() =>
- startWorkflowUiPendingLoadRuntime(async (workflowId) => {
+ useMountEffect(() => {
+ const owner = captureAccountScope();
+
+ return startWorkflowUiPendingLoadRuntime(async (workflowId) => {
try {
- const raw = await getLibraryWorkflow(workflowId);
+ assertAccountScopeCurrent(owner);
+ const raw = await getLibraryWorkflow(workflowId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const { document, warnings } = parseWorkflowJson(raw);
const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';
@@ -31,17 +41,21 @@ export const PendingLibraryWorkflowLoader = () => {
notify.info(t('commandPalette.workflowLoad.warning'), warning);
}
- void touchLibraryWorkflowOpenedAt(workflowId).catch(() => {
+ void touchLibraryWorkflowOpenedAt(workflowId, owner.signal).catch(() => {
// Recency bookkeeping only; loading already succeeded.
});
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(
t('commandPalette.workflowLoad.failed'),
getApiErrorMessage(error, t('commandPalette.workflowLoad.couldNotLoad'))
);
}
- })
- );
+ });
+ });
return null;
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts
index 60cdd490db..b1f3e9e13e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts
@@ -1,6 +1,7 @@
import type { ProjectGraphState, WorkflowEdge, WorkflowNode, XYPosition } from '@features/workflow/contracts';
import { createWorkflowId } from '@features/workflow/utility';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -21,6 +22,15 @@ const clipboardStore = createExternalStore<WorkflowClipboardSnapshot>({ edges: [
const PASTE_OFFSET = 32;
+export const clearWorkflowClipboard = (): void => {
+ clipboardStore.setSnapshot({ edges: [], nodes: [] });
+};
+
+registerAccountOwnedResource({
+ clear: clearWorkflowClipboard,
+ name: 'workflow-clipboard',
+});
+
export const copyNodesToClipboard = (document: ProjectGraphState, nodeIds: string[]): number => {
const copiedIds = new Set(nodeIds);
const nodes = document.nodes.filter((node) => copiedIds.has(node.id));
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts
index a3b40ebda2..01410f42b1 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -14,10 +15,19 @@ export interface WorkflowSelectionSnapshot {
selectionRequest: { nodeIds: string[]; token: number } | null;
}
-export const workflowSelectionStore = createExternalStore<WorkflowSelectionSnapshot>({
+const INITIAL_WORKFLOW_SELECTION_SNAPSHOT: WorkflowSelectionSnapshot = {
hoveredNodeId: null,
selectedNodeIds: [],
selectionRequest: null,
+};
+
+export const workflowSelectionStore = createExternalStore<WorkflowSelectionSnapshot>(
+ INITIAL_WORKFLOW_SELECTION_SNAPSHOT
+);
+
+registerAccountOwnedResource({
+ clear: () => workflowSelectionStore.setSnapshot(INITIAL_WORKFLOW_SELECTION_SNAPSHOT),
+ name: 'workflow-selection',
});
const areSameIds = (a: string[], b: string[]): boolean => a.length === b.length && a.every((id, i) => id === b[i]);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts
index d8f6941cf9..58ae001c1c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts
@@ -1,7 +1,18 @@
import type { Viewport } from '@xyflow/react';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+
const viewports = new Map<string, Viewport>();
+export const clearWorkflowViewports = (): void => {
+ viewports.clear();
+};
+
+registerAccountOwnedResource({
+ clear: clearWorkflowViewports,
+ name: 'workflow-viewports',
+});
+
export const getWorkflowViewportKey = (projectId: string, instanceId: string): string => `${projectId}:${instanceId}`;
export const getWorkflowViewport = (key: string): Viewport | null => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index baca2d16b9..fb8e32424c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -5,6 +5,12 @@ import { createListCollection, HStack, Input, Switch, Text } from '@chakra-ui/re
import { galleryDestinations, type GalleryBoard, type GeneratedImageContract } from '@features/gallery';
import { SCHEDULER_OPTIONS } from '@features/generation/settings';
import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { Button, Combobox, ResizableTextarea, Select } from '@platform/ui';
import { lazy, Suspense, useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react';
@@ -273,20 +279,37 @@ const SchedulerInput = ({ id, invalid, onChange, template, value }: WorkflowFiel
/>
);
-let boardOptionsRequest: Promise<GalleryBoard[]> | null = null;
+let boardOptionsRequest: { owner: AccountScope; promise: Promise<GalleryBoard[]> } | null = null;
+
+registerAccountOwnedResource({
+ clear: () => {
+ boardOptionsRequest = null;
+ },
+ name: 'workflow-board-options',
+});
const getBoardOptions = (): Promise<GalleryBoard[]> => {
- if (!boardOptionsRequest) {
- boardOptionsRequest = galleryDestinations
- .list()
- .then((loadedBoards) => loadedBoards.filter((board) => board.kind === 'board'))
+ const owner = captureAccountScope();
+
+ if (boardOptionsRequest?.owner !== owner) {
+ const promise = galleryDestinations
+ .list({ signal: owner.signal })
+ .then((loadedBoards) => {
+ assertAccountScopeCurrent(owner);
+
+ return loadedBoards.filter((board) => board.kind === 'board');
+ })
.catch((error: unknown) => {
- boardOptionsRequest = null;
+ if (boardOptionsRequest?.promise === promise) {
+ boardOptionsRequest = null;
+ }
throw error;
});
+
+ boardOptionsRequest = { owner, promise };
}
- return boardOptionsRequest;
+ return boardOptionsRequest.promise;
};
const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
index c6af20e10f..8d367ac76e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
@@ -18,6 +18,12 @@ import { documentToPreviewGraph, GraphPreviewFlow } from '@features/workflow/ui/
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import { useWorkflowNotifications, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';
import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';
+import {
+ type AccountScope,
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, CloseButton, ConfirmDialog, JsonPreview, Scrollable } from '@platform/ui';
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
@@ -123,8 +129,8 @@ export const WorkflowLibraryDialog = ({
const isWorkflowLoadPending = workflowLoad !== null;
const refresh = useCallback(
- (nextPage: number) => {
- const params = { category, page: nextPage, query: searchTerm };
+ (nextPage: number, owner: AccountScope = captureAccountScope()) => {
+ const params = { category, page: nextPage, query: searchTerm, signal: owner.signal };
const cached = getCachedWorkflowPage(params);
const token = (refreshTokenRef.current += 1);
@@ -139,7 +145,7 @@ export const WorkflowLibraryDialog = ({
listLibraryWorkflowsCached(params)
.then((result) => {
- if (token !== refreshTokenRef.current) {
+ if (!isAccountScopeCurrent(owner) || token !== refreshTokenRef.current) {
return;
}
@@ -155,14 +161,14 @@ export const WorkflowLibraryDialog = ({
}
})
.catch((error: unknown) => {
- if (cached) {
+ if (!isAccountScopeCurrent(owner) || cached) {
return; // Stale-but-rendered beats an error toast on revalidation.
}
notify.error('Workflow library unavailable', getApiErrorMessage(error, 'Failed to list workflows.'));
})
.finally(() => {
- if (token === refreshTokenRef.current) {
+ if (isAccountScopeCurrent(owner) && token === refreshTokenRef.current) {
setIsLoading(false);
}
});
@@ -179,8 +185,10 @@ export const WorkflowLibraryDialog = ({
}
}, [isOpen, refresh]);
- const fetchParsedWorkflow = async (item: WorkflowLibraryListItem) => {
- const raw = await getLibraryWorkflowCached(item.workflow_id);
+ const fetchParsedWorkflow = async (item: WorkflowLibraryListItem, owner: AccountScope) => {
+ const raw = await getLibraryWorkflowCached(item.workflow_id, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const { document, warnings } = parseWorkflowJson(raw);
return { document, raw, warnings };
@@ -190,6 +198,8 @@ export const WorkflowLibraryDialog = ({
item: WorkflowLibraryListItem,
loaded?: { document: ProjectGraphState; warnings: string[] }
) => {
+ const owner = captureAccountScope();
+
if (workflowLoadInFlightRef.current) {
return;
}
@@ -200,9 +210,10 @@ export const WorkflowLibraryDialog = ({
if (!parsed) {
setWorkflowLoad({ id: item.workflow_id, phase: 'fetching' });
- parsed = await fetchParsedWorkflow(item);
+ parsed = await fetchParsedWorkflow(item, owner);
}
+ assertAccountScopeCurrent(owner);
setWorkflowLoad({ id: item.workflow_id, phase: 'applying' });
// Synchronous graph replacement can be expensive for large workflows.
// Give React a full frame to commit and paint the busy overlay first.
@@ -210,60 +221,87 @@ export const WorkflowLibraryDialog = ({
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
+ assertAccountScopeCurrent(owner);
replace(parsed.document, `Loaded "${item.name}" from library`);
for (const warning of parsed.warnings) {
notify.info('Workflow load warning', warning);
}
- void touchLibraryWorkflowOpenedAt(item.workflow_id).catch(() => {
+ void touchLibraryWorkflowOpenedAt(item.workflow_id, owner.signal).catch(() => {
// Recency bookkeeping only; loading already succeeded.
});
onOpenChange(false);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error('Failed to load workflow', getApiErrorMessage(error, `Could not load "${item.name}".`));
} finally {
- workflowLoadInFlightRef.current = false;
- setWorkflowLoad(null);
+ if (isAccountScopeCurrent(owner)) {
+ workflowLoadInFlightRef.current = false;
+ setWorkflowLoad(null);
+ }
}
};
const previewWorkflow = async (item: WorkflowLibraryListItem) => {
+ const owner = captureAccountScope();
+
setPreviewingWorkflowId(item.workflow_id);
try {
- const { document, raw, warnings } = await fetchParsedWorkflow(item);
+ const { document, raw, warnings } = await fetchParsedWorkflow(item, owner);
+ assertAccountScopeCurrent(owner);
setPreview({ document, item, raw, warnings });
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error('Failed to preview workflow', getApiErrorMessage(error, `Could not preview "${item.name}".`));
} finally {
- setPreviewingWorkflowId(null);
+ if (isAccountScopeCurrent(owner)) {
+ setPreviewingWorkflowId(null);
+ }
}
};
const saveToLibrary = async (asNew: boolean) => {
+ const owner = captureAccountScope();
+
setIsSaving(true);
try {
const serialized = serializeWorkflowJson(projectGraph);
if (!asNew && projectGraph.libraryWorkflowId) {
- await updateLibraryWorkflow(projectGraph.libraryWorkflowId, serialized);
+ await updateLibraryWorkflow(projectGraph.libraryWorkflowId, serialized, owner.signal);
+
+ assertAccountScopeCurrent(owner);
notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);
} else {
- const workflowId = await createLibraryWorkflow(serialized);
+ const workflowId = await createLibraryWorkflow(serialized, owner.signal);
+ assertAccountScopeCurrent(owner);
bindLibraryWorkflow(workflowId);
notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);
}
invalidateWorkflowLibraryCache();
- refresh(page);
+ refresh(page, owner);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));
} finally {
- setIsSaving(false);
+ if (isAccountScopeCurrent(owner)) {
+ setIsSaving(false);
+ }
}
};
@@ -508,11 +546,20 @@ export const WorkflowLibraryDialog = ({
return;
}
+ const owner = captureAccountScope();
+ const workflowId = pendingDelete.workflow_id;
+
try {
- await deleteLibraryWorkflow(pendingDelete.workflow_id);
+ await deleteLibraryWorkflow(workflowId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
invalidateWorkflowLibraryCache();
- refresh(page);
+ refresh(page, owner);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error('Failed to delete workflow', getApiErrorMessage(error, 'The workflow could not be deleted.'));
}
}}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
index 9ee56bc21f..f1629434dc 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
@@ -56,4 +56,22 @@ describe('pending library workflow load runtime', () => {
expect(clearRequest.mock.calls.map(([requestId]) => requestId)).toEqual([1, 3]);
stop();
});
+
+ it('does not clear shared state when an in-flight load settles after the runtime stops', async () => {
+ const pending = deferred();
+ const clearRequest = vi.fn();
+ const stop = startPendingLibraryWorkflowLoadRuntime({
+ clearRequest,
+ getRequest: () => ({ requestId: 1, workflowId: 'user-a-workflow' }),
+ load: () => pending.promise,
+ subscribe: () => () => undefined,
+ });
+
+ stop();
+ pending.resolve();
+ await pending.promise;
+ await Promise.resolve();
+
+ expect(clearRequest).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
index 2613b4d12c..b05ab7a548 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
@@ -30,12 +30,13 @@ export const startPendingLibraryWorkflowLoadRuntime = (deps: PendingLibraryWorkf
.load(request.workflowId)
.catch(() => undefined)
.finally(() => {
+ if (!isRunning) {
+ return;
+ }
+
deps.clearRequest(request.requestId);
inFlight = false;
-
- if (isRunning) {
- consume();
- }
+ consume();
});
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts
new file mode 100644
index 0000000000..5529919589
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts
@@ -0,0 +1,23 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { describe, expect, it } from 'vitest';
+
+import { requestLibraryWorkflowLoad, workflowUiStore } from './workflowUiStore';
+
+describe('workflow UI account ownership', () => {
+ it('clears pending UI state without reusing request identities across accounts', () => {
+ accountLifecycle.activate('user-a');
+ requestLibraryWorkflowLoad('workflow-a');
+ const firstRequestId = workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad?.requestId;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ expect(workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad).toBeNull();
+
+ requestLibraryWorkflowLoad('workflow-b');
+ const secondRequestId = workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad?.requestId;
+
+ expect(firstRequestId).toEqual(expect.any(Number));
+ expect(secondRequestId).toEqual(expect.any(Number));
+ expect(secondRequestId).toBeGreaterThan(firstRequestId ?? 0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
index 05ce94cf44..01039c5101 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
@@ -1,5 +1,6 @@
import type { FieldType, XYPosition } from '@features/workflow/contracts';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export type AddNodeConnectionFilter =
@@ -42,7 +43,7 @@ export interface LibraryWorkflowLoadRequest {
let nextLibraryWorkflowLoadRequestId = 0;
-export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({
+const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {
addNodeConnection: null,
addNodePosition: null,
importRequestCount: 0,
@@ -50,6 +51,15 @@ export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({
isLibraryOpen: false,
isNewWorkflowConfirmOpen: false,
pendingLibraryWorkflowLoad: null,
+};
+
+export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>(INITIAL_WORKFLOW_UI_SNAPSHOT);
+
+registerAccountOwnedResource({
+ clear: () => {
+ workflowUiStore.setSnapshot(INITIAL_WORKFLOW_UI_SNAPSHOT);
+ },
+ name: 'workflow-ui',
});
export const setWorkflowLibraryOpen = (isOpen: boolean): void => {
diff --git a/invokeai/frontend/webv2/src/platform/state/accountLifecycle.test.ts b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.test.ts
new file mode 100644
index 0000000000..9bfec7940b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createAccountLifecycle } from './accountLifecycle';
+
+describe('account lifecycle', () => {
+ it('rotates immutable epochs for every authenticated lifetime, including the same account', () => {
+ const lifecycle = createAccountLifecycle();
+ const boot = lifecycle.capture();
+ const first = lifecycle.activate('user-a');
+
+ expect(first).toMatchObject({ accountId: 'user-a', epoch: 1, storageSuffix: '' });
+ expect(lifecycle.isCurrent(boot)).toBe(false);
+ expect(boot.signal.aborted).toBe(true);
+
+ lifecycle.invalidate();
+ const second = lifecycle.activate('user-a', ':user:user-a');
+
+ expect(second).toMatchObject({ accountId: 'user-a', epoch: 3, storageSuffix: ':user:user-a' });
+ expect(lifecycle.isCurrent(first)).toBe(false);
+ expect(first.signal.aborted).toBe(true);
+ expect(lifecycle.isCurrent(second)).toBe(true);
+ expect(second.signal.aborted).toBe(false);
+ expect(Object.isFrozen(second)).toBe(true);
+ });
+
+ it('invalidates before clearing resources and keeps clearing after one resource fails', () => {
+ const lifecycle = createAccountLifecycle();
+ const observed: boolean[] = [];
+ const first = lifecycle.activate('user-a');
+ const finalClear = vi.fn();
+
+ lifecycle.register({
+ clear: () => {
+ observed.push(lifecycle.isCurrent(first));
+ },
+ name: 'observer',
+ });
+ lifecycle.register({
+ clear: () => {
+ throw new Error('broken clear');
+ },
+ name: 'broken',
+ });
+ lifecycle.register({ clear: finalClear, name: 'final' });
+
+ lifecycle.invalidate();
+
+ expect(observed).toEqual([false]);
+ expect(finalClear).toHaveBeenCalledOnce();
+ expect(lifecycle.capture()).toMatchObject({ accountId: null, epoch: 2, storageSuffix: '' });
+ });
+
+ it('unregisters lifetime-owned resources', () => {
+ const lifecycle = createAccountLifecycle();
+ const clear = vi.fn();
+ const unregister = lifecycle.register({ clear, name: 'ephemeral' });
+
+ unregister();
+ lifecycle.invalidate();
+
+ expect(clear).not.toHaveBeenCalled();
+ });
+
+ it('replaces same-name registrations without letting an old disposer remove the replacement', () => {
+ const lifecycle = createAccountLifecycle();
+ const oldClear = vi.fn();
+ const newClear = vi.fn();
+ const disposeOld = lifecycle.register({ clear: oldClear, name: 'hot-resource' });
+
+ lifecycle.register({ clear: newClear, name: 'hot-resource' });
+ disposeOld();
+ lifecycle.invalidate();
+
+ expect(oldClear).not.toHaveBeenCalled();
+ expect(newClear).toHaveBeenCalledOnce();
+ });
+
+ it('rejects empty active identities', () => {
+ const lifecycle = createAccountLifecycle();
+
+ expect(() => lifecycle.activate('')).toThrow('non-empty account id');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts
new file mode 100644
index 0000000000..c12a1c9ec3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts
@@ -0,0 +1,135 @@
+export interface AccountScope {
+ /**
+ * Stable backend identity for this authenticated lifetime. `null` represents
+ * the boot/login lifetime, which is still epoch-scoped so its async work can
+ * be invalidated before an account becomes active.
+ */
+ readonly accountId: string | null;
+ /** Monotonically increasing identity lifetime, including same-user logins. */
+ readonly epoch: number;
+ /** Aborted synchronously when this identity lifetime becomes stale. */
+ readonly signal: AbortSignal;
+ /** Immutable suffix for account-owned browser storage. */
+ readonly storageSuffix: string;
+}
+
+export interface AccountOwnedResource {
+ /** Human-readable owner used by diagnostics and tests. */
+ readonly name: string;
+ /** Synchronously removes all data and cancels work owned by the old scope. */
+ clear(): void;
+}
+
+export interface AccountLifecycle {
+ /** Starts a fresh lifetime for `accountId`; same-account logins still rotate the epoch. */
+ activate(accountId: string, storageSuffix?: string): AccountScope;
+ /** Returns the immutable scope captured by work starting now. */
+ capture(): AccountScope;
+ /** Invalidates the current epoch before synchronously clearing registered resources. */
+ invalidate(): AccountScope;
+ /** True only while `scope` is the exact current identity lifetime. */
+ isCurrent(scope: AccountScope): boolean;
+ /** Registers an account-owned cache/runtime. Returns an unregister function. */
+ register(resource: AccountOwnedResource): () => void;
+}
+
+export class AccountScopeExpiredError extends Error {
+ constructor() {
+ super('The account scope that owned this operation is no longer active.');
+ this.name = 'AccountScopeExpiredError';
+ }
+}
+
+const createScope = (
+ accountId: string | null,
+ epoch: number,
+ signal: AbortSignal,
+ storageSuffix: string
+): AccountScope => Object.freeze({ accountId, epoch, signal, storageSuffix });
+
+/**
+ * Owns identity epochs and the account-resource registry behind one small
+ * interface. Identity decides *when* a transition happens; the App composition
+ * root supplies this lifecycle, and feature caches register independently so
+ * lazy editor modules do not enter the Launchpad's eager dependency graph.
+ */
+export const createAccountLifecycle = (): AccountLifecycle => {
+ let controller = new AbortController();
+ let current = createScope(null, 0, controller.signal, '');
+ const resources = new Map<string, { resource: AccountOwnedResource; token: number }>();
+ let nextRegistrationToken = 1;
+
+ const clearResources = (): void => {
+ for (const { resource } of resources.values()) {
+ try {
+ resource.clear();
+ } catch {
+ // Privacy cleanup is fail-safe: one defective resource must not leave
+ // every later cache live. Resource-specific tests own diagnostics.
+ }
+ }
+ };
+
+ const rotateScope = (accountId: string | null, storageSuffix: string): AccountScope => {
+ const previousController = controller;
+
+ controller = new AbortController();
+ current = createScope(accountId, current.epoch + 1, controller.signal, storageSuffix);
+ previousController.abort();
+
+ return current;
+ };
+
+ const invalidate = (): AccountScope => {
+ // Rotate first. Any completion racing a clear observes a stale epoch and
+ // must become a no-op even if its transport cannot be aborted.
+ rotateScope(null, '');
+ clearResources();
+
+ return current;
+ };
+
+ return {
+ activate(accountId, storageSuffix = '') {
+ if (!accountId) {
+ throw new Error('An active account scope requires a non-empty account id.');
+ }
+
+ rotateScope(accountId, storageSuffix);
+ clearResources();
+
+ return current;
+ },
+ capture: () => current,
+ invalidate,
+ isCurrent: (scope) => scope === current,
+ register(resource) {
+ const registration = { resource, token: nextRegistrationToken };
+
+ nextRegistrationToken += 1;
+ resources.set(resource.name, registration);
+
+ return () => {
+ if (resources.get(resource.name)?.token === registration.token) {
+ resources.delete(resource.name);
+ }
+ };
+ },
+ };
+};
+
+/** App-composed process lifecycle shared by account-owned feature modules. */
+export const accountLifecycle = createAccountLifecycle();
+
+export const captureAccountScope = (): AccountScope => accountLifecycle.capture();
+
+export const isAccountScopeCurrent = (scope: AccountScope): boolean => accountLifecycle.isCurrent(scope);
+
+export const assertAccountScopeCurrent = (scope: AccountScope): void => {
+ if (!isAccountScopeCurrent(scope)) {
+ throw new AccountScopeExpiredError();
+ }
+};
+
+export const registerAccountOwnedResource = (resource: AccountOwnedResource): (() => void) =>
+ accountLifecycle.register(resource);
diff --git a/invokeai/frontend/webv2/src/platform/transport/http.test.ts b/invokeai/frontend/webv2/src/platform/transport/http.test.ts
index 8507388029..83b4e9b5ea 100644
--- a/invokeai/frontend/webv2/src/platform/transport/http.test.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/http.test.ts
@@ -5,7 +5,15 @@ vi.mock('./deploymentBase', () => ({
getDeploymentBaseUrl: () => 'https://app.example/invoke',
}));
-import { absolutizeApiUrl, buildApiUrl, getBackendSocketPath, getBackendSocketUrl } from './http';
+import {
+ absolutizeApiUrl,
+ apiFetch,
+ apiFetchJson,
+ buildApiUrl,
+ configureHttpAuth,
+ getBackendSocketPath,
+ getBackendSocketUrl,
+} from './http';
describe('deployment-aware backend URLs', () => {
beforeEach(() => {
@@ -28,3 +36,121 @@ describe('deployment-aware backend URLs', () => {
expect(getBackendSocketPath()).toBe('/invoke/ws/socket.io');
});
});
+
+describe('request identity ownership', () => {
+ it('does not expire a newer account when an older request returns 401', async () => {
+ let token: string | null = 'token-a';
+ let identity = {};
+ const onUnauthorized = vi.fn();
+ let resolveFetch: ((response: Response) => void) | undefined;
+ let sentInit: RequestInit | undefined;
+ const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
+ sentInit = init;
+
+ return new Promise<Response>((resolve) => {
+ resolveFetch = resolve;
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => token, onUnauthorized });
+
+ const oldRequest = apiFetch('/api/v1/projects/');
+ const sentHeaders = sentInit?.headers as Headers;
+
+ expect(sentHeaders.get('Authorization')).toBe('Bearer token-a');
+
+ token = 'token-b';
+ identity = {};
+ resolveFetch?.(new Response('', { status: 401 }));
+
+ await expect(oldRequest).rejects.toMatchObject({ name: 'HttpRequestIdentityExpiredError' });
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ });
+
+ it('expires the account whose token was rejected', async () => {
+ const onUnauthorized = vi.fn();
+ const identity = {};
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 401 })));
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => 'current-token', onUnauthorized });
+
+ await expect(apiFetch('/api/v1/projects/')).rejects.toMatchObject({ status: 401 });
+
+ expect(onUnauthorized).toHaveBeenCalledWith('current-token', identity);
+ });
+
+ it('does not expire a new epoch when the backend reuses the same token string', async () => {
+ const token = 'stable-token';
+ let identity = {};
+ const onUnauthorized = vi.fn();
+ let resolveFetch: ((response: Response) => void) | undefined;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ resolveFetch = resolve;
+ })
+ )
+ );
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => token, onUnauthorized });
+
+ const oldRequest = apiFetch('/api/v1/projects/');
+
+ identity = {};
+ resolveFetch?.(new Response('', { status: 401 }));
+
+ await expect(oldRequest).rejects.toMatchObject({ name: 'HttpRequestIdentityExpiredError' });
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ });
+
+ it('rejects a tokenless error body that finishes under a newer identity lifetime', async () => {
+ let identity = {};
+ let resolveBody: ((value: string) => void) | undefined;
+ const response = {
+ ok: false,
+ status: 401,
+ statusText: 'Unauthorized',
+ text: () =>
+ new Promise<string>((resolve) => {
+ resolveBody = resolve;
+ }),
+ } as Response;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => null, onUnauthorized: vi.fn() });
+
+ const oldRequest = apiFetch('/api/v1/auth/status');
+ await vi.waitFor(() => {
+ expect(resolveBody).toBeDefined();
+ });
+
+ identity = {};
+ resolveBody?.('Unauthorized');
+
+ await expect(oldRequest).rejects.toMatchObject({ name: 'HttpRequestIdentityExpiredError' });
+ });
+
+ it('rejects a response body that finishes under a newer identity lifetime', async () => {
+ let identity = {};
+ let resolveBody: ((value: unknown) => void) | undefined;
+ const response = {
+ json: () =>
+ new Promise((resolve) => {
+ resolveBody = resolve;
+ }),
+ ok: true,
+ status: 200,
+ } as Response;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => 'stable-token', onUnauthorized: vi.fn() });
+
+ const oldRequest = apiFetchJson<{ owner: string }>('/api/v1/projects/');
+ await vi.waitFor(() => {
+ expect(resolveBody).toBeDefined();
+ });
+
+ identity = {};
+ resolveBody?.({ owner: 'user-a' });
+
+ await expect(oldRequest).rejects.toMatchObject({ name: 'HttpRequestIdentityExpiredError' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/transport/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.ts
index 9a3a050e5d..b483d37707 100644
--- a/invokeai/frontend/webv2/src/platform/transport/http.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts
@@ -9,11 +9,17 @@ import { getDeploymentBasePath, getDeploymentBaseUrl } from './deploymentBase';
const API_BASE_URL = (import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '').trim().replace(/\/$/, '');
export interface HttpAuthAdapter {
+ /** Opaque identity-lifetime token; object identity must rotate on reauthentication. */
+ getIdentity(): unknown;
getToken(): string | null;
- onUnauthorized(): void;
+ onUnauthorized(rejectedToken: string, rejectedIdentity: unknown): void;
}
-let authAdapter: HttpAuthAdapter = { getToken: () => null, onUnauthorized: () => undefined };
+let authAdapter: HttpAuthAdapter = {
+ getIdentity: () => null,
+ getToken: () => null,
+ onUnauthorized: () => undefined,
+};
/** Selected once by the App composition root; Platform owns no Auth policy. */
export const configureHttpAuth = (adapter: HttpAuthAdapter): void => {
@@ -70,6 +76,19 @@ export class ApiError extends Error {
}
}
+export class HttpRequestIdentityExpiredError extends Error {
+ constructor() {
+ super('The identity lifetime that started this HTTP request is no longer active.');
+ this.name = 'HttpRequestIdentityExpiredError';
+ }
+}
+
+const assertHttpIdentityCurrent = (identity: unknown): void => {
+ if (authAdapter.getIdentity() !== identity) {
+ throw new HttpRequestIdentityExpiredError();
+ }
+};
+
const humanizeFieldName = (value: string): string => value.replaceAll('_', ' ');
const getLastString = (values: unknown[]): string | null => {
@@ -122,9 +141,7 @@ export const assertOk = async (response: Response): Promise<Response> => {
throw new ApiError(text || `${response.status} ${response.statusText}`, response.status);
};
-/** Authenticated fetch that leaves status handling to the caller. */
-export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response> => {
- const token = getHttpAuthToken();
+const fetchWithAuthToken = (path: string, init: RequestInit | undefined, token: string | null): Promise<Response> => {
const headers = new Headers(init?.headers);
if (token && !headers.has('Authorization')) {
@@ -134,15 +151,47 @@ export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response>
return fetch(buildApiUrl(path), { ...init, headers });
};
-export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> => {
- const hadToken = getHttpAuthToken() !== null;
- const response = await apiFetchRaw(path, init);
+/** Authenticated fetch that leaves status handling to the caller. */
+export const apiFetchRaw = async (path: string, init?: RequestInit): Promise<Response> => {
+ const requestToken = getHttpAuthToken();
+ const requestIdentity = authAdapter.getIdentity();
+ const response = await fetchWithAuthToken(path, init, requestToken);
+
+ assertHttpIdentityCurrent(requestIdentity);
+
+ return response;
+};
- if (response.status === 401 && hadToken) {
- authAdapter.onUnauthorized();
+export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> => {
+ // Capture one principal for the complete request. A late User A response
+ // must neither use User B's header nor expire User B's newer session.
+ const requestToken = getHttpAuthToken();
+ const requestIdentity = authAdapter.getIdentity();
+ const response = await fetchWithAuthToken(path, init, requestToken);
+ let expiredCurrentIdentity = false;
+
+ assertHttpIdentityCurrent(requestIdentity);
+
+ if (response.status === 401 && requestToken !== null && authAdapter.getToken() === requestToken) {
+ expiredCurrentIdentity = true;
+ authAdapter.onUnauthorized(requestToken, requestIdentity);
}
- return assertOk(response);
+ try {
+ const asserted = await assertOk(response);
+
+ assertHttpIdentityCurrent(requestIdentity);
+
+ return asserted;
+ } catch (error) {
+ // A current-session 401 intentionally rotates identity inside
+ // `onUnauthorized`; callers should still receive the backend ApiError.
+ if (!expiredCurrentIdentity) {
+ assertHttpIdentityCurrent(requestIdentity);
+ }
+
+ throw error;
+ }
};
/**
@@ -177,6 +226,7 @@ export const getApiErrorMessage = (error: unknown, fallback: string): string =>
};
export const apiFetchJson = async <T>(path: string, init?: RequestInit): Promise<T> => {
+ const requestIdentity = authAdapter.getIdentity();
const headers = new Headers(init?.headers);
if (init?.body !== undefined && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
@@ -184,11 +234,28 @@ export const apiFetchJson = async <T>(path: string, init?: RequestInit): Promise
}
const response = await apiFetch(path, { ...init, headers });
+ const body = (await response.json()) as T;
+
+ assertHttpIdentityCurrent(requestIdentity);
- return (await response.json()) as T;
+ return body;
};
-export const sleep = (ms: number): Promise<void> =>
- new Promise((resolve) => {
- window.setTimeout(resolve, ms);
+export const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
+ new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(signal.reason);
+ return;
+ }
+
+ const onAbort = (): void => {
+ window.clearTimeout(timeoutId);
+ reject(signal?.reason);
+ };
+ const timeoutId = window.setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+
+ signal?.addEventListener('abort', onAbort, { once: true });
});
diff --git a/invokeai/frontend/webv2/src/platform/transport/socketHub.test.ts b/invokeai/frontend/webv2/src/platform/transport/socketHub.test.ts
index 871496c5e5..b136def252 100644
--- a/invokeai/frontend/webv2/src/platform/transport/socketHub.test.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/socketHub.test.ts
@@ -135,6 +135,7 @@ describe('socketHub', () => {
expect(sockets).toHaveLength(2);
+ sockets[0]!.fire('queue_item_status_changed', { item_id: 0 });
sockets[1]!.fire('queue_item_status_changed', { item_id: 1 });
expect(handler).toHaveBeenCalledTimes(1);
diff --git a/invokeai/frontend/webv2/src/platform/transport/socketHub.ts b/invokeai/frontend/webv2/src/platform/transport/socketHub.ts
index c00c288d67..68abaa38d4 100644
--- a/invokeai/frontend/webv2/src/platform/transport/socketHub.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/socketHub.ts
@@ -53,6 +53,11 @@ export const createSocketHub = (options: { createSocket?: () => BackendSocket }
const createSocket = options.createSocket ?? createDefaultSocket;
let socket: BackendSocket | null = null;
+ let socketLifecycleHandlers: {
+ connect: (payload: never) => void;
+ connectError: (payload: never) => void;
+ disconnect: (payload: never) => void;
+ } | null = null;
let status: BackendConnectionStatus = 'connecting';
let lastError: string | undefined;
@@ -80,16 +85,25 @@ export const createSocketHub = (options: { createSocket?: () => BackendSocket }
socket = nextSocket;
publishStatus('connecting');
- nextSocket.on('connect', () => {
+ const onConnect = () => {
publishStatus('connected');
nextSocket.emit('subscribe_queue', { queue_id: 'default' });
- });
- nextSocket.on('connect_error', (error: { message: string }) => {
+ };
+ const onConnectError = (error: { message: string }) => {
publishStatus('disconnected', error.message);
- });
- nextSocket.on('disconnect', (reason: string) => {
+ };
+ const onDisconnect = (reason: string) => {
publishStatus('disconnected', reason);
- });
+ };
+
+ socketLifecycleHandlers = {
+ connect: onConnect,
+ connectError: onConnectError as (payload: never) => void,
+ disconnect: onDisconnect as (payload: never) => void,
+ };
+ nextSocket.on('connect', onConnect);
+ nextSocket.on('connect_error', socketLifecycleHandlers.connectError);
+ nextSocket.on('disconnect', socketLifecycleHandlers.disconnect);
// Re-bind consumer listeners so they survive a socket recreation.
for (const [event, handlers] of eventHandlers) {
@@ -102,8 +116,28 @@ export const createSocketHub = (options: { createSocket?: () => BackendSocket }
};
const disconnect = (): void => {
- socket?.disconnect();
+ const oldSocket = socket;
+ const oldLifecycleHandlers = socketLifecycleHandlers;
+
socket = null;
+ socketLifecycleHandlers = null;
+
+ if (oldSocket) {
+ if (oldLifecycleHandlers) {
+ oldSocket.off('connect', oldLifecycleHandlers.connect);
+ oldSocket.off('connect_error', oldLifecycleHandlers.connectError);
+ oldSocket.off('disconnect', oldLifecycleHandlers.disconnect);
+ }
+
+ for (const [event, handlers] of eventHandlers) {
+ for (const handler of handlers) {
+ oldSocket.off(event, handler);
+ }
+ }
+
+ oldSocket.disconnect();
+ }
+
publishStatus('connecting');
};
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index df4855eab3..89df824436 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -4,6 +4,7 @@ import type { ProjectSettings } from '@workbench/settings/contracts';
import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { captureAccountScope } from '@platform/state/accountLifecycle';
import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';
@@ -48,7 +49,8 @@ export const WorkbenchProvider = ({
loadOptions?: WorkbenchLoadOptions;
}) => {
const [store] = useState(() => createWorkbenchStore());
- const [persistence] = useState(createSyncedWorkbenchPersistence);
+ const [owner] = useState(captureAccountScope);
+ const [persistence] = useState(() => createSyncedWorkbenchPersistence(owner));
const [extensions] = useState(createExtensionRegistry);
const hasHydrated = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot).hasHydrated;
@@ -72,6 +74,7 @@ export const WorkbenchProvider = ({
},
loadOptions,
persistence,
+ signal: owner.signal,
});
persistenceRuntime.start();
return () => persistenceRuntime.dispose();
diff --git a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
new file mode 100644
index 0000000000..0679a3baea
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
@@ -0,0 +1,25 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { describe, expect, it } from 'vitest';
+
+import { isHotkeyModalLayerActive, registerHotkeyModalLayer } from './hotkeys/modalLayer';
+import { commandPaletteStore } from './palette/paletteStore';
+import { settingsDialogStore } from './settings/settingsDialogStore';
+import { getLayerPropertiesRequest, requestLayerProperties } from './widgets/layers/layerPropertiesRequestStore';
+
+describe('account-owned workbench UI stores', () => {
+ it('synchronously removes transient UI state on account invalidation', () => {
+ accountLifecycle.activate('user-a');
+ commandPaletteStore.setSnapshot({ isOpen: true });
+ settingsDialogStore.setSnapshot({ isOpen: true, sectionId: 'developer' });
+ const unregisterModal = registerHotkeyModalLayer('settings');
+ requestLayerProperties('user-a-layer', 'filter');
+
+ accountLifecycle.invalidate();
+
+ expect(commandPaletteStore.getSnapshot().isOpen).toBe(false);
+ expect(settingsDialogStore.getSnapshot()).toEqual({ isOpen: false, sectionId: 'appearance' });
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ expect(getLayerPropertiesRequest()).toBeNull();
+ unregisterModal();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.test.ts
index e9c0ad8158..686818c35c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.test.ts
@@ -15,16 +15,22 @@ const jsonResponse = (body: unknown, init: { ok?: boolean; status?: number; stat
describe('uploadCanvasImage', () => {
it('forwards an abort signal to fetch', async () => {
const controller = new AbortController();
- const fetchImpl = vi.fn(() =>
+ const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(jsonResponse({ height: 1, image_name: 'uploaded.png', width: 1 }))
- ) as unknown as typeof fetch;
+ );
+ const fetchImpl = fetchMock as unknown as typeof fetch;
await uploadCanvasImage(new Blob(['pixels'], { type: 'image/png' }), {
fetch: fetchImpl,
signal: controller.signal,
});
- expect(fetchImpl).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: controller.signal }));
+ const signal = (fetchMock.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+
+ expect(signal).toBeInstanceOf(AbortSignal);
+ expect(signal?.aborted).toBe(false);
+ controller.abort();
+ expect(signal?.aborted).toBe(true);
});
it('POSTs a multipart file to the upload endpoint with the persistence params', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
index 1202223b1b..81c2791491 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
@@ -15,6 +15,7 @@
import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { buildApiUrl, getHttpAuthToken } from '@platform/transport/http';
export type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
@@ -66,7 +67,9 @@ export const uploadCanvasImage = async (
blob: Blob,
options: UploadCanvasImageOptions = {}
): Promise<CanvasImageUploadResult> => {
+ const owner = captureAccountScope();
const fetchImpl = options.fetch ?? globalThis.fetch;
+ const signal = options.signal ? AbortSignal.any([options.signal, owner.signal]) : owner.signal;
const query = new URLSearchParams({
image_category: options.imageCategory ?? 'other',
@@ -99,7 +102,7 @@ export const uploadCanvasImage = async (
body,
headers,
method: 'POST',
- signal: options.signal,
+ signal,
});
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
@@ -111,8 +114,11 @@ export const uploadCanvasImage = async (
);
}
+ assertAccountScopeCurrent(owner);
if (!response.ok) {
const text = await response.text().catch(() => '');
+
+ assertAccountScopeCurrent(owner);
throw new CanvasImageUploadError(
text || `Canvas image upload failed: ${response.status} ${response.statusText}`,
response.status
@@ -120,5 +126,7 @@ export const uploadCanvasImage = async (
}
const dto = (await response.json()) as UploadImageResponseDTO;
+
+ assertAccountScopeCurrent(owner);
return { height: dto.height, imageName: dto.image_name, width: dto.width };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
index 14b8321c1e..02ac2ccc9e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
@@ -236,7 +236,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
if (signal?.aborted) {
throw new DOMException('Canvas upload aborted', 'AbortError');
}
- const uploaded = await canvasApplicationPort.uploadImage(blob, { isIntermediate: true });
+ const uploaded = await canvasApplicationPort.uploadImage(blob, { isIntermediate: true, signal });
if (signal?.aborted) {
throw new DOMException('Canvas upload aborted', 'AbortError');
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
index c8ef5a0b60..543d325bb4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
@@ -5,9 +5,10 @@ import type { RasterCompositeExportResult } from '@workbench/canvas-engine/expor
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { uploadCanvasImage } from './backend/canvasImages';
@@ -17,6 +18,15 @@ const bbox = { height: 512, width: 768, x: 31, y: 47 };
const uploadedName = 'bbox-upload.png';
const defaultBlob = new Blob(['pixels'], { type: 'image/png' });
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
+
const galleryImage: GalleryImage = {
boardId: 'none',
height: bbox.height,
@@ -139,6 +149,14 @@ const getCommittedLayers = (harness: ReturnType<typeof createHarness>): readonly
};
describe('createFromBbox', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('create-from-bbox-test');
+ });
+
+ afterEach(() => {
+ accountLifecycle.invalidate();
+ });
+
it('creates a raster layer at the bbox origin from the uploaded composite', async () => {
const harness = createHarness();
@@ -150,7 +168,9 @@ describe('createFromBbox', () => {
fileName: 'bbox.png',
imageCategory: 'other',
isIntermediate: false,
+ signal: expect.any(AbortSignal),
});
+ expect(harness.resolveImages).toHaveBeenCalledWith([uploadedName], expect.any(AbortSignal));
const layers = getCommittedLayers(harness);
expect(layers).toHaveLength(1);
@@ -241,4 +261,21 @@ describe('createFromBbox', () => {
expect(harness.commitStructural).not.toHaveBeenCalled();
});
+
+ it('does not upload account A bbox pixels after account B becomes active', async () => {
+ const harness = createHarness();
+ const exportResult = deferred<RasterCompositeExportResult>();
+
+ harness.exportRasterComposite.mockReturnValueOnce(exportResult.promise);
+ const create = harness.run('raster');
+
+ await vi.waitFor(() => expect(harness.exportRasterComposite).toHaveBeenCalledOnce());
+ accountLifecycle.activate('create-from-bbox-test-b');
+ exportResult.resolve({ blob: defaultBlob, rect: bbox, status: 'ok' });
+
+ await expect(create).resolves.toEqual({ status: 'stale' });
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ expect(harness.resolveImages).not.toHaveBeenCalled();
+ expect(harness.commitStructural).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
index 05e7ce8b7a..adc5913de1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
@@ -5,6 +5,11 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project } from '@workbench/projectContracts';
import { galleryImages } from '@features/gallery';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import type { CanvasCompositeExportEngine } from './exportCanvasComposite';
import type { GalleryCanvasImportDestination } from './importGalleryImages';
@@ -46,9 +51,10 @@ export const createFromBbox = async (options: {
getProject: (projectId: string) => Project | null;
isActiveProject: (projectId: string) => boolean;
project: Project;
- resolveImages?: (imageNames: string[]) => Promise<GalleryImage[]>;
+ resolveImages?: (imageNames: string[], signal?: AbortSignal) => Promise<GalleryImage[]>;
uploadImage?: typeof uploadCanvasImage;
}): Promise<CreateFromBboxResult> => {
+ const owner = captureAccountScope();
const {
applyCanvasMutation,
destination,
@@ -60,43 +66,58 @@ export const createFromBbox = async (options: {
uploadImage = uploadCanvasImage,
} = options;
- const exported = await exportCanvasComposite(engine, 'bbox');
- if (exported.status !== 'ok') {
- return exported;
- }
+ try {
+ const exported = await exportCanvasComposite(engine, 'bbox');
- const uploaded = await uploadImage(exported.blob, {
- fileName: 'bbox.png',
- imageCategory: 'other',
- isIntermediate: false,
- });
+ assertAccountScopeCurrent(owner);
+ if (exported.status !== 'ok') {
+ return exported;
+ }
- if (destination === 'global-reference') {
- return { image: uploaded, status: 'uploaded' };
- }
+ const uploaded = await uploadImage(exported.blob, {
+ fileName: 'bbox.png',
+ imageCategory: 'other',
+ isIntermediate: false,
+ signal: owner.signal,
+ });
- const [galleryImage] = await resolveImages([uploaded.imageName]);
- if (!galleryImage) {
- throw new Error(`Uploaded bbox composite ${uploaded.imageName} could not be resolved to a gallery image`);
- }
+ assertAccountScopeCurrent(owner);
+ if (destination === 'global-reference') {
+ return { image: uploaded, status: 'uploaded' };
+ }
- const imported = await importGalleryImagesToCanvas({
- applyCanvasMutation,
- destination,
- engine,
- getProject,
- images: [galleryImage],
- isActiveProject,
- project,
- });
+ const [galleryImage] = await resolveImages([uploaded.imageName], owner.signal);
- if (imported.status === 'imported') {
- return { destination, layerIds: imported.layerIds, status: 'created' };
- }
- if (imported.status === 'empty') {
- // Unreachable: exactly one image is always passed. Kept for exhaustiveness.
- return { status: 'blocked' };
- }
+ assertAccountScopeCurrent(owner);
+ if (!galleryImage) {
+ throw new Error(`Uploaded bbox composite ${uploaded.imageName} could not be resolved to a gallery image`);
+ }
+
+ const imported = await importGalleryImagesToCanvas({
+ applyCanvasMutation,
+ destination,
+ engine,
+ getProject,
+ images: [galleryImage],
+ isActiveProject,
+ project,
+ });
- return imported;
+ assertAccountScopeCurrent(owner);
+ if (imported.status === 'imported') {
+ return { destination, layerIds: imported.layerIds, status: 'created' };
+ }
+ if (imported.status === 'empty') {
+ // Unreachable: exactly one image is always passed. Kept for exhaustiveness.
+ return { status: 'blocked' };
+ }
+
+ return imported;
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return { status: 'stale' };
+ }
+
+ throw error;
+ }
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
index c748771166..eab95b160a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
@@ -4,6 +4,7 @@ import type {
CanvasRegionalGuidanceLayerContract,
} from '@workbench/canvas-engine/contracts';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import {
@@ -22,7 +23,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { EngineDeps, RegistryTimers } from './engineRegistry';
-import { createEngineRegistry } from './engineRegistry';
+import { createEngineRegistry, getCanvasEngine, getOrCreateEngine } from './engineRegistry';
const createDeferred = <T>() => {
let resolve!: (value: T) => void;
@@ -139,6 +140,17 @@ const createFakeTimers = (): { timers: RegistryTimers; flush: () => void; pendin
};
describe('createEngineRegistry', () => {
+ it('disposes the process registry synchronously when its account expires', () => {
+ accountLifecycle.activate('user-a');
+ const engine = getOrCreateEngine('shared-project-id', createFakeDeps());
+ const dispose = vi.spyOn(engine.lifecycle, 'dispose');
+
+ accountLifecycle.invalidate();
+
+ expect(getCanvasEngine('shared-project-id')).toBeUndefined();
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
it('returns the same instance per project id and distinct instances across ids', () => {
const registry = createEngineRegistry();
const deps = createFakeDeps();
@@ -223,6 +235,44 @@ describe('createEngineRegistry', () => {
engine.lifecycle.dispose();
});
+ it('synchronously disposes every active and cooling engine', () => {
+ const fakeTimers = createFakeTimers();
+ const registry = createEngineRegistry({ timers: fakeTimers.timers });
+ const active = registry.getOrCreateEngine('active', createFakeDeps());
+ const cooling = registry.getOrCreateEngine('cooling', createFakeDeps());
+ const activeDispose = vi.spyOn(active.lifecycle, 'dispose');
+ const coolingDispose = vi.spyOn(cooling.lifecycle, 'dispose');
+
+ registry.releaseEngine('cooling');
+ expect(fakeTimers.pending()).toBe(1);
+
+ registry.disposeAll();
+
+ expect(registry.getEngine('active')).toBeUndefined();
+ expect(registry.getEngine('cooling')).toBeUndefined();
+ expect(fakeTimers.pending()).toBe(0);
+ expect(activeDispose).toHaveBeenCalledOnce();
+ expect(coolingDispose).toHaveBeenCalledOnce();
+ });
+
+ it('continues disposing account-owned engines after one disposal fails', () => {
+ const registry = createEngineRegistry();
+ const first = registry.getOrCreateEngine('first', createFakeDeps());
+ const second = registry.getOrCreateEngine('second', createFakeDeps());
+ const failure = new Error('first engine cleanup failed');
+ const firstDispose = vi.spyOn(first.lifecycle, 'dispose').mockImplementationOnce(() => {
+ throw failure;
+ });
+ const secondDispose = vi.spyOn(second.lifecycle, 'dispose');
+
+ expect(() => registry.disposeAll()).toThrow(failure);
+
+ expect(firstDispose).toHaveBeenCalledOnce();
+ expect(secondDispose).toHaveBeenCalledOnce();
+ expect(registry.getEngine('first')).toBeUndefined();
+ expect(registry.getEngine('second')).toBeUndefined();
+ });
+
it('continues control and regional composites from a detached snapshot after a project switch', async () => {
const fakeTimers = createFakeTimers();
const registry = createEngineRegistry({ timers: fakeTimers.timers });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
index 541b34ab88..d0dfd5524e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
@@ -16,6 +16,7 @@
import type { CanvasEngine as PublicCanvasEngine } from '@workbench/canvas-engine/api';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import {
createCanvasEngine,
type CanvasEngine,
@@ -36,6 +37,8 @@ export interface RegistryTimers {
/** The registry handle. */
export interface EngineRegistry {
+ /** Immediately disposes every engine, including active and cooling leases. */
+ disposeAll(): void;
/** Returns the engine for `projectId`, creating it if needed, and adds a reference. */
getOrCreateEngine(projectId: string, deps: EngineDeps): CanvasEngine;
/** Returns the engine for `projectId` without changing its reference count. */
@@ -94,6 +97,26 @@ export const createEngineRegistry = (
};
return {
+ disposeAll: () => {
+ const ownedEntries = [...entries.values()];
+ let firstError: unknown;
+
+ entries.clear();
+ for (const entry of ownedEntries) {
+ cancelDisposal(entry);
+ try {
+ entry.engine.lifecycle.dispose();
+ } catch (error) {
+ firstError ??= error;
+ }
+ }
+
+ if (firstError !== undefined) {
+ throw new Error(firstError instanceof Error ? firstError.message : 'A canvas engine failed to dispose.', {
+ cause: firstError,
+ });
+ }
+ },
getEngine: (projectId) => entries.get(projectId)?.engine,
getOrCreateEngine: (projectId, deps) => {
const existing = entries.get(projectId);
@@ -129,6 +152,11 @@ export const createEngineRegistry = (
/** The process-wide default registry shared by all widget surfaces. */
const defaultRegistry = createEngineRegistry();
+registerAccountOwnedResource({
+ clear: defaultRegistry.disposeAll,
+ name: 'canvas-engine-registry',
+});
+
export const getOrCreateEngine = defaultRegistry.getOrCreateEngine;
export const releaseEngine = defaultRegistry.releaseEngine;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
index e0de0a565b..9479eb7eb5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
@@ -245,6 +245,36 @@ describe('composeForGeneration', () => {
);
});
+ it('does not start an upload when its account lifetime expires during encoding', async () => {
+ const harness = makeHost(makeDoc([rasterLayer('base')]));
+ const executorDeps = harness.host.getCompositeExecutorDeps();
+ const controller = new AbortController();
+ let resolveEncode: ((blob: Blob) => void) | undefined;
+
+ harness.host.getCompositeExecutorDeps = () => ({
+ ...executorDeps,
+ backend: {
+ ...executorDeps.backend,
+ encodeSurface: () =>
+ new Promise((resolve) => {
+ resolveEncode = resolve;
+ }),
+ },
+ });
+
+ const result = compose(harness.host, { signal: controller.signal });
+ await vi.waitFor(() => {
+ expect(resolveEncode).toBeDefined();
+ });
+
+ controller.abort();
+ resolveEncode?.(new Blob(['encoded']));
+
+ await expect(result).rejects.toMatchObject({ name: 'AbortError' });
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ expect(harness.release).toHaveBeenCalledOnce();
+ });
+
it('resolves txt2img from the bounds pre-pass: no base upload, detectMode never consulted, controls and regionals still composited', async () => {
// No raster layers → no content bounds → txt2img without executing the base
// plan; control + regional composites are mode-independent and still run.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index 3fc9e2f848..b6247345b1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -201,8 +201,9 @@ export const composeForGeneration = async (
byHash: new Map(host.dedupe.byHash),
byKey: new Map(host.dedupe.byKey),
};
+ const executorDeps = host.getCompositeExecutorDeps();
const deps: ExecuteCompositePlanDeps = {
- ...host.getCompositeExecutorDeps(),
+ ...executorDeps,
dedupe: operationDedupe,
getLayerSurface: (layerId) => {
const detached = rasterSnapshot.layerSurfaces.get(layerId);
@@ -210,6 +211,15 @@ export const composeForGeneration = async (
? Promise.resolve(detached)
: Promise.reject(new Error(`Canvas raster snapshot is missing layer ${layerId}.`));
},
+ uploadImage: async (blob) => {
+ // Encoding and hashing yield before upload. Re-check at the transport
+ // boundary so Account A work cannot start with Account B credentials.
+ options.signal.throwIfAborted();
+ const uploaded = await executorDeps.uploadImage(blob);
+ options.signal.throwIfAborted();
+
+ return uploaded;
+ },
};
try {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index e2826ef79e..78b56c15fb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -6,6 +6,7 @@ import type { uploadCanvasImage } from '@workbench/canvas-operations/backend/can
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import {
createControlLayer,
createEmptyPaintLayer,
@@ -565,6 +566,43 @@ describe('importGalleryImagesToCanvas', () => {
await firstImport;
});
+ it('does not upload an old account image after local preprocessing crosses an account switch', async () => {
+ accountLifecycle.activate('user-a');
+ const { project, state } = withProject();
+ let resolveFetch: ((response: Response) => void) | undefined;
+ const fetchImage = vi.fn<typeof fetch>(
+ () =>
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ })
+ );
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>
+ Promise.resolve({ height: 512, imageName: 'must-not-upload', width: 512 })
+ );
+ const applyCanvasMutation = vi.fn();
+
+ const oldImport = importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ applyCanvasMutation,
+ engine: null,
+ fetchImage,
+ ...queriesFor(() => state),
+ images: [image('user-a.png')],
+ project,
+ uploadImage,
+ });
+ const signal = (fetchImage.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+ resolveFetch?.(new Response(new Blob(['user-a-pixels']), { status: 200 }));
+
+ await expect(oldImport).rejects.toBeInstanceOf(AggregateError);
+ expect(signal?.aborted).toBe(true);
+ expect(uploadImage).not.toHaveBeenCalled();
+ expect(applyCanvasMutation).not.toHaveBeenCalled();
+ });
+
it('bounds resized work at four, preserves successful order, and reports partial failures once', async () => {
const { project, state } = withProject();
let active = 0;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
index d952b47461..bca89f9596 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -11,6 +11,11 @@ import {
normalizeGenerateWidgetValues,
} from '@features/generation/settings';
import { getModelsSnapshot } from '@features/models';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';
import {
createControlLayer,
@@ -54,6 +59,13 @@ type LayerImage = CanvasImageRef | GalleryImage;
const activeImports = new Set<string>();
+registerAccountOwnedResource({
+ clear: () => {
+ activeImports.clear();
+ },
+ name: 'canvas-gallery-imports',
+});
+
const imageRef = (image: LayerImage): CanvasImageRef => ({
height: image.height,
imageName: image.imageName,
@@ -180,24 +192,32 @@ const resizeImages = async (
images: readonly GalleryImage[],
project: Project,
fetchImage: typeof fetch,
- uploadImage: typeof uploadCanvasImage
+ uploadImage: typeof uploadCanvasImage,
+ signal: AbortSignal
): Promise<{ images: LayerImage[]; failedImageNames: string[] }> => {
const generateValues = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));
const dimensions = getGenerationDimensions(generateValues?.model);
const results = await mapWithConcurrency(images, 4, async (image): Promise<ResizeResult> => {
try {
- const response = await fetchImage(image.imageUrl);
+ const response = await fetchImage(image.imageUrl, { signal });
+
+ signal.throwIfAborted();
if (!response.ok) {
throw new Error(`Failed to fetch ${image.imageName}: ${response.status} ${response.statusText}`);
}
const blob = await response.blob();
+
+ signal.throwIfAborted();
const resizeTo = calculateNewSize(image.width / image.height, dimensions.optimal ** 2, dimensions.grid);
const uploaded = await uploadImage(blob, {
fileName: image.imageName,
imageCategory: 'other',
isIntermediate: false,
resizeTo,
+ signal,
});
+
+ signal.throwIfAborted();
return { image: uploaded, status: 'fulfilled' };
} catch (reason) {
return { imageName: image.imageName, reason, status: 'rejected' };
@@ -236,6 +256,7 @@ export const importGalleryImagesToCanvas = async (options: {
models?: readonly ModelConfig[];
uploadImage?: typeof uploadCanvasImage;
}): Promise<ImportGalleryImagesResult> => {
+ const owner = captureAccountScope();
const {
applyCanvasMutation,
destination,
@@ -251,10 +272,12 @@ export const importGalleryImagesToCanvas = async (options: {
if (images.length === 0) {
return { status: 'empty' };
}
- if (activeImports.has(project.id)) {
+ const importKey = `${owner.epoch}:${project.id}`;
+
+ if (activeImports.has(importKey)) {
return { status: 'blocked' };
}
- activeImports.add(project.id);
+ activeImports.add(importKey);
try {
const capturedDocument = project.canvas.document;
@@ -266,7 +289,9 @@ export const importGalleryImagesToCanvas = async (options: {
let layerImages: readonly LayerImage[] = images;
let failedImageNames: string[] = [];
if (destination === 'control-resized') {
- const resized = await resizeImages(images, project, fetchImage, uploadImage);
+ const resized = await resizeImages(images, project, fetchImage, uploadImage, owner.signal);
+
+ assertAccountScopeCurrent(owner);
layerImages = resized.images;
failedImageNames = resized.failedImageNames;
}
@@ -287,6 +312,8 @@ export const importGalleryImagesToCanvas = async (options: {
};
const latestProject = getProject(project.id);
+
+ assertAccountScopeCurrent(owner);
if (!latestProject) {
return { status: 'stale-project' };
}
@@ -303,6 +330,6 @@ export const importGalleryImagesToCanvas = async (options: {
}
return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };
} finally {
- activeImports.delete(project.id);
+ activeImports.delete(importKey);
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
index 3a120830c1..21244f3781 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
@@ -6,9 +6,10 @@ import type { Rect } from '@workbench/canvas-engine/types';
import type { Project } from '@workbench/projectContracts';
import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { getProjectWidgetInstance } from '@workbench/widgetState';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { uploadCanvasImage } from './backend/canvasImages';
@@ -25,6 +26,15 @@ const model: MainModelConfig = {
const defaultRect: Rect = { height: 456, width: 123, x: -4, y: 8 };
const defaultBlob = new Blob(['pixels'], { type: 'image/png' });
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
+
const createProject = (boardId = 'board-1', generateOverrides: Partial<GenerateWidgetValues> = {}): Project => {
const project = createInitialWorkbenchState().projects[0]!;
const generate = getProjectWidgetInstance(project, 'generate');
@@ -98,6 +108,14 @@ const createHarness = (
};
describe('saveCanvasToGallery', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('save-canvas-test');
+ });
+
+ afterEach(() => {
+ accountLifecycle.invalidate();
+ });
+
it('flushes before exporting canvas content and uploads with gallery metadata', async () => {
const harness = createHarness();
@@ -125,6 +143,7 @@ describe('saveCanvasToGallery', () => {
seed: 123,
width: 123,
},
+ signal: expect.any(AbortSignal),
});
});
@@ -251,4 +270,24 @@ describe('saveCanvasToGallery', () => {
})
).rejects.toThrow('upload failed');
});
+
+ it('does not upload account A canvas pixels after account B becomes active', async () => {
+ const harness = createHarness();
+ const exportResult = deferred<RasterCompositeExportResult>();
+
+ harness.exportRasterComposite.mockReturnValueOnce(exportResult.promise);
+ const save = saveCanvasToGallery({
+ engine: harness.engine,
+ project: createProject(),
+ region: 'canvas',
+ uploadImage: harness.uploadImage,
+ });
+
+ await vi.waitFor(() => expect(harness.exportRasterComposite).toHaveBeenCalledOnce());
+ accountLifecycle.activate('save-canvas-test-b');
+ exportResult.resolve({ blob: defaultBlob, rect: defaultRect, status: 'ok' });
+
+ await expect(save).resolves.toEqual({ status: 'stale' });
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
index 39c1c281ee..da6a0eaf00 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
@@ -4,6 +4,11 @@ import type { Project } from '@workbench/projectContracts';
import { isGalleryVirtualBoard } from '@features/gallery';
import { toModelIdentifier } from '@features/generation/graph';
import { isSupportedGenerateModel, normalizeGenerateWidgetValues } from '@features/generation/settings';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getProjectWidgetValues } from '@workbench/widgetState';
import type { CanvasCompositeExportEngine, CanvasCompositeRegion } from './exportCanvasComposite';
@@ -48,21 +53,34 @@ export const saveCanvasToGallery = async (options: {
project: Project;
uploadImage?: typeof uploadCanvasImage;
}): Promise<SaveCanvasToGalleryResult> => {
+ const owner = captureAccountScope();
const { engine, project, region, uploadImage = uploadCanvasImage } = options;
const boardId = getCanvasSaveBoardId(project);
- const exported = await exportCanvasComposite(engine, region);
- if (exported.status !== 'ok') {
- return exported;
- }
+ try {
+ const exported = await exportCanvasComposite(engine, region);
+
+ assertAccountScopeCurrent(owner);
+ if (exported.status !== 'ok') {
+ return exported;
+ }
- const uploaded = await uploadImage(exported.blob, {
- boardId,
- fileName: region === 'canvas' ? 'canvas.png' : 'bbox.png',
- imageCategory: 'general',
- isIntermediate: false,
- metadata: buildCanvasSaveMetadata(project, exported.rect),
- });
+ const uploaded = await uploadImage(exported.blob, {
+ boardId,
+ fileName: region === 'canvas' ? 'canvas.png' : 'bbox.png',
+ imageCategory: 'general',
+ isIntermediate: false,
+ metadata: buildCanvasSaveMetadata(project, exported.rect),
+ signal: owner.signal,
+ });
- return { imageName: uploaded.imageName, status: 'saved' };
+ assertAccountScopeCurrent(owner);
+ return { imageName: uploaded.imageName, status: 'saved' };
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return { status: 'stale' };
+ }
+
+ throw error;
+ }
};
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts
index a2adad10d7..bd50a5df31 100644
--- a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts
@@ -1,3 +1,4 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -75,6 +76,17 @@ describe('diagnostics logger', () => {
expect(getProjectDiagnostics('project-b')).toHaveLength(1);
});
+ it('clears every project synchronously when its account lifetime expires', () => {
+ accountLifecycle.activate('user-a');
+ createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).error('A failed');
+ createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-b' }).warn('B warned');
+
+ accountLifecycle.invalidate();
+
+ expect(getProjectDiagnostics('project-a')).toEqual([]);
+ expect(getProjectDiagnostics('project-b')).toEqual([]);
+ });
+
it('filters entries by project logging settings', () => {
configureDiagnostics({
enabled: true,
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts
index 42b34ff02c..07018b8320 100644
--- a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts
+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts
@@ -1,6 +1,7 @@
import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
import type { WidgetContributionSource } from '@workbench/widgetContracts';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { useSyncExternalStore } from 'react';
const MAX_PROJECT_DIAGNOSTIC_ENTRIES = 500;
@@ -178,6 +179,20 @@ export const clearProjectDiagnostics = (projectId: string): void => {
notifyProjectDiagnostics(projectId);
};
+export const clearAllProjectDiagnostics = (): void => {
+ const projectIds = [...entriesByProjectId.keys()];
+
+ entriesByProjectId.clear();
+ for (const projectId of projectIds) {
+ notifyProjectDiagnostics(projectId);
+ }
+};
+
+registerAccountOwnedResource({
+ clear: clearAllProjectDiagnostics,
+ name: 'project-diagnostics',
+});
+
export const subscribeProjectDiagnostics = (projectId: string, listener: DiagnosticListener): (() => void) => {
const listeners = listenersByProjectId.get(projectId) ?? new Set<DiagnosticListener>();
diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
index c8befdb04c..d9498da053 100644
--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
@@ -6,6 +6,7 @@ import type {
} from '@features/generation/contracts';
import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { captureAccountScope } from '@platform/state/accountLifecycle';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { createWorkbenchStore } from '@workbench/workbenchStore';
import { describe, expect, it, vi } from 'vitest';
@@ -69,6 +70,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {
const submitted = resolveAndSubmitGraphPreviewInvocation({
commands,
models: undefined,
+ owner: captureAccountScope(),
prepareCanvasInvocation,
project,
sourceId: 'canvas',
@@ -89,6 +91,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {
const submitted = resolveAndSubmitGraphPreviewInvocation({
commands,
models: undefined,
+ owner: captureAccountScope(),
prepareCanvasInvocation,
project,
sourceId: 'generate',
@@ -111,6 +114,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {
const submitted = resolveAndSubmitGraphPreviewInvocation({
commands,
models: undefined,
+ owner: captureAccountScope(),
prepareCanvasInvocation,
project,
sourceId: undefined,
@@ -130,6 +134,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {
const submitted = resolveAndSubmitGraphPreviewInvocation({
commands,
models: undefined,
+ owner: captureAccountScope(),
prepareCanvasInvocation,
project,
sourceId: 'generate',
diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
index 0e0c2491c6..9941881fc9 100644
--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts
@@ -1,4 +1,7 @@
import type { ModelConfig } from '@features/models';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import type { InvocationSourceId } from './invocationContracts';
import type { Project } from './projectContracts';
@@ -11,6 +14,7 @@ import { submitResolvedInvocation } from './invocationSubmit';
export interface GraphPreviewInvokeDeps {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
models: readonly ModelConfig[] | undefined;
+ owner: AccountScope;
prepareCanvasInvocation: typeof prepareCanvasInvocation;
project: Project;
sourceId: InvocationSourceId | undefined;
@@ -20,11 +24,12 @@ export interface GraphPreviewInvokeDeps {
export const resolveAndSubmitGraphPreviewInvocation = ({
commands,
models,
+ owner,
prepareCanvasInvocation: prepareCanvas,
project,
sourceId,
}: GraphPreviewInvokeDeps): boolean => {
- if (!sourceId) {
+ if (!sourceId || !isAccountScopeCurrent(owner)) {
return false;
}
@@ -39,6 +44,6 @@ export const resolveAndSubmitGraphPreviewInvocation = ({
return false;
}
- submitResolvedInvocation({ commands, models, prepareCanvasInvocation: prepareCanvas, project, route });
+ submitResolvedInvocation({ commands, models, owner, prepareCanvasInvocation: prepareCanvas, project, route });
return true;
};
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index 620c0e90d8..117c975e24 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -10,6 +10,11 @@ import { ensureModelsLoaded, getModelsSnapshot } from '@features/models';
import { queueCommands } from '@features/queue';
import { useInvocationTemplatesSelector } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { getConnectionStatus } from '@platform/transport/connectionStore';
import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';
import { submitResolvedInvocation } from '@workbench/invocationSubmit';
@@ -72,65 +77,90 @@ export const useRegisterFirstPartyCommands = () => {
});
const submitInvocation = useEffectEvent(async () => {
+ const owner = captureAccountScope();
flushGenerateDrafts();
- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
+ try {
+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
- const activeProject = queries.getSnapshot().activeProject;
- const resolvedRoute = resolveInvocationRoute(
- activeProject,
- 'global',
- activeProject.invocation,
- getAvailableModels()
- );
- const { status } = getConnectionStatus();
+ assertAccountScopeCurrent(owner);
+ const activeProject = queries.getSnapshot().activeProject;
+ const resolvedRoute = resolveInvocationRoute(
+ activeProject,
+ 'global',
+ activeProject.invocation,
+ getAvailableModels()
+ );
+ const { status } = getConnectionStatus();
- if (!isInvocationRouteValid(resolvedRoute) || status !== 'connected') {
- return;
- }
+ if (!isInvocationRouteValid(resolvedRoute) || status !== 'connected') {
+ return;
+ }
- submitResolvedInvocation({
- commands,
- models: getAvailableModels(),
- prepareCanvasInvocation,
- project: activeProject,
- route: resolvedRoute,
- });
+ submitResolvedInvocation({
+ commands,
+ models: getAvailableModels(),
+ owner,
+ prepareCanvasInvocation,
+ project: activeProject,
+ route: resolvedRoute,
+ });
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ throw error;
+ }
});
const recallSelectedImage = useEffectEvent(async (kind: ImageRecallKind) => {
- const [{ executeImageRecall }, { getSelectedGalleryImage }] = await Promise.all([
- import('@workbench/image-actions/executeImageRecall'),
- import('@workbench/image-actions/selectedImage'),
- ]);
- const activeProject = queries.getSnapshot().activeProject;
- const image = getSelectedGalleryImage(activeProject);
+ const owner = captureAccountScope();
- if (!image) {
- notifications.add({
- kind: 'info',
- message: 'Select an image in Gallery or Preview first.',
- title: 'No image selected',
- });
- return;
- }
+ try {
+ const [{ executeImageRecall }, { getSelectedGalleryImage }] = await Promise.all([
+ import('@workbench/image-actions/executeImageRecall'),
+ import('@workbench/image-actions/selectedImage'),
+ ]);
+
+ assertAccountScopeCurrent(owner);
+ const activeProject = queries.getSnapshot().activeProject;
+ const image = getSelectedGalleryImage(activeProject);
- const didRecall = await executeImageRecall({
- commands,
- generateValues: getProjectWidgetValues(activeProject, 'generate'),
- image,
- kind,
- models: getAvailableModels() ?? [],
- projectId: activeProject.id,
- });
+ if (!image) {
+ notifications.add({
+ kind: 'info',
+ message: 'Select an image in Gallery or Preview first.',
+ title: 'No image selected',
+ });
+ return;
+ }
- if (didRecall && queries.isActiveProject(activeProject.id)) {
- openWidgetPlacement({
- getWidgetsForRegion,
- options: { preferredRegions: ['left'] },
- typeId: 'generate',
- widgets,
+ const didRecall = await executeImageRecall({
+ commands,
+ generateValues: getProjectWidgetValues(activeProject, 'generate'),
+ image,
+ kind,
+ models: getAvailableModels() ?? [],
+ owner,
+ projectId: activeProject.id,
});
+
+ assertAccountScopeCurrent(owner);
+ if (didRecall && queries.isActiveProject(activeProject.id)) {
+ openWidgetPlacement({
+ getWidgetsForRegion,
+ options: { preferredRegions: ['left'] },
+ typeId: 'generate',
+ widgets,
+ });
+ }
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ throw error;
}
});
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts
index 028943477e..955a073105 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts
@@ -1,7 +1,15 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
const store = createExternalStore<{ activeLayerIds: ReadonlySet<string> }>({ activeLayerIds: new Set<string>() });
+registerAccountOwnedResource({
+ clear: () => {
+ store.setSnapshot({ activeLayerIds: new Set<string>() });
+ },
+ name: 'hotkey-modal-layers',
+});
+
export const registerHotkeyModalLayer = (id: string): (() => void) => {
store.patchSnapshot({ activeLayerIds: new Set([...store.getSnapshot().activeLayerIds, id]) });
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
index 5d3ef3c9f1..4e0e831d67 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
@@ -2,6 +2,7 @@ import type { GalleryImage } from '@features/gallery';
import type { ModelConfig } from '@features/models';
import type { WorkbenchCommands } from '@workbench/workbenchStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const galleryApi = vi.hoisted(() => ({
@@ -54,6 +55,7 @@ const createCommands = () => {
describe('executeImageRecall', () => {
beforeEach(() => {
+ accountLifecycle.activate('test-account');
galleryApi.galleryImages.metadata.mockReset();
galleryApi.galleryImages.resolveMany.mockReset();
});
@@ -74,7 +76,7 @@ describe('executeImageRecall', () => {
})
).resolves.toBe(true);
- expect(galleryApi.galleryImages.metadata).toHaveBeenCalledWith('selected.png');
+ expect(galleryApi.galleryImages.metadata).toHaveBeenCalledWith('selected.png', expect.any(AbortSignal));
expect(setSettings).toHaveBeenCalledWith(
expect.objectContaining({ positivePrompt: 'recalled prompt' }),
'project-1'
@@ -139,7 +141,10 @@ describe('executeImageRecall', () => {
})
).resolves.toBe(true);
- expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledWith(['valid-crop.png', 'deleted-crop.png']);
+ expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledWith(
+ ['valid-crop.png', 'deleted-crop.png'],
+ expect.any(AbortSignal)
+ );
expect(setSettings).toHaveBeenCalledWith(
expect.objectContaining({
positivePrompt: 'keep other fields',
@@ -148,4 +153,72 @@ describe('executeImageRecall', () => {
'project-1'
);
});
+
+ it('does not reuse or commit image metadata from an expired account epoch', async () => {
+ const oldCommands = createCommands();
+ let resolveOldMetadata: ((value: unknown) => void) | undefined;
+
+ galleryApi.galleryImages.metadata.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveOldMetadata = resolve;
+ })
+ );
+ const oldRecall = executeImageRecall({
+ commands: oldCommands.commands,
+ generateValues: { modelKey: model.key },
+ image,
+ kind: 'remix',
+ models: [model],
+ projectId: 'project-a',
+ });
+
+ accountLifecycle.invalidate();
+ accountLifecycle.activate('user-b');
+
+ const newCommands = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValueOnce({ positive_prompt: 'user b' });
+ await expect(
+ executeImageRecall({
+ commands: newCommands.commands,
+ generateValues: { modelKey: model.key },
+ image,
+ kind: 'remix',
+ models: [model],
+ projectId: 'project-b',
+ })
+ ).resolves.toBe(true);
+
+ resolveOldMetadata?.({ positive_prompt: 'user a' });
+ await expect(oldRecall).resolves.toBe(false);
+
+ expect(oldCommands.setSettings).not.toHaveBeenCalled();
+ expect(newCommands.setSettings).toHaveBeenCalledWith(
+ expect.objectContaining({ positivePrompt: 'user b' }),
+ 'project-b'
+ );
+ expect(galleryApi.galleryImages.metadata).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not recapture the current account when a caller-owned scope has already expired', async () => {
+ const oldCommands = createCommands();
+ const owner = accountLifecycle.capture();
+
+ accountLifecycle.activate('new-account');
+
+ await expect(
+ executeImageRecall({
+ commands: oldCommands.commands,
+ generateValues: { modelKey: model.key },
+ image,
+ kind: 'remix',
+ models: [model],
+ owner,
+ projectId: 'project-a',
+ })
+ ).resolves.toBe(false);
+
+ expect(galleryApi.galleryImages.metadata).not.toHaveBeenCalled();
+ expect(oldCommands.setSettings).not.toHaveBeenCalled();
+ expect(oldCommands.add).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
index bcd68ea3fc..29a6045fa3 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
@@ -11,6 +11,13 @@ import {
isVaeModelConfig,
normalizeGenerateWidgetValues,
} from '@features/generation/settings';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import {
buildImageRecallSettings,
@@ -19,24 +26,39 @@ import {
type ImageRecallKind,
} from './imageRecall';
-const imageMetadataRequests = new Map<string, Promise<unknown>>();
+const imageMetadataRequests = new Map<string, { owner: AccountScope; promise: Promise<unknown> }>();
+
+registerAccountOwnedResource({
+ clear: () => {
+ imageMetadataRequests.clear();
+ },
+ name: 'image-recall-metadata',
+});
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
-const loadImageMetadata = (imageName: string): Promise<unknown> => {
+const loadImageMetadata = (imageName: string, owner: AccountScope): Promise<unknown> => {
const cachedRequest = imageMetadataRequests.get(imageName);
- if (cachedRequest) {
- return cachedRequest;
+ if (cachedRequest?.owner === owner) {
+ return cachedRequest.promise;
}
- const request = galleryImages.metadata(imageName).catch((error: unknown) => {
- imageMetadataRequests.delete(imageName);
- throw error;
- });
+ const request = galleryImages
+ .metadata(imageName, owner.signal)
+ .then((metadata) => {
+ assertAccountScopeCurrent(owner);
- imageMetadataRequests.set(imageName, request);
+ return metadata;
+ })
+ .catch((error: unknown) => {
+ if (imageMetadataRequests.get(imageName)?.promise === request) {
+ imageMetadataRequests.delete(imageName);
+ }
+ throw error;
+ });
+ imageMetadataRequests.set(imageName, { owner, promise: request });
return request;
};
@@ -73,6 +95,7 @@ export const executeImageRecall = async ({
image,
kind,
models,
+ owner: callerOwner,
projectId,
}: {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
@@ -81,8 +104,15 @@ export const executeImageRecall = async ({
image: GalleryImage;
kind: ImageRecallKind;
models: ModelConfig[];
+ /** Caller-captured identity lifetime; direct synchronous callers may omit it. */
+ owner?: AccountScope;
projectId?: string;
}): Promise<boolean> => {
+ const owner = callerOwner ?? captureAccountScope();
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
const supportedModels = models.filter(isSupportedGenerateModel);
const vaeModels = models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig);
const currentGenerateValues = getCurrentGenerateValues({
@@ -100,7 +130,9 @@ export const executeImageRecall = async ({
return false;
}
- const metadata = kind === 'dimensions' ? null : await loadImageMetadata(image.imageName);
+ const metadata = kind === 'dimensions' ? null : await loadImageMetadata(image.imageName, owner);
+
+ assertAccountScopeCurrent(owner);
const result = buildImageRecallSettings({
currentValues: currentGenerateValues,
image,
@@ -125,10 +157,12 @@ export const executeImageRecall = async ({
referenceImage.config.image ? [getEffectiveReferenceImage(referenceImage.config.image).image_name] : []
);
const availableNames = new Set(
- (await galleryImages.resolveMany([...new Set(effectiveNames)])).map(
+ (await galleryImages.resolveMany([...new Set(effectiveNames)], owner.signal)).map(
(availableImage) => availableImage.imageName
)
);
+
+ assertAccountScopeCurrent(owner);
result.values.referenceImages = result.values.referenceImages.filter((referenceImage) => {
const referenceAsset = referenceImage.config.image;
return referenceAsset && availableNames.has(getEffectiveReferenceImage(referenceAsset).image_name);
@@ -156,6 +190,10 @@ export const executeImageRecall = async ({
});
return true;
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
commands.notifications.reportError({
area: 'image-recall',
message: toErrorMessage(error),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 593cac75cb..ccf250031c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -10,6 +10,11 @@ import {
import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import {
getCanvasImportNotice,
getCanvasEngine,
@@ -136,31 +141,55 @@ export const useImageActions = ({
return {
copyImage: async (image) => {
+ const owner = captureAccountScope();
+
try {
- const response = await fetch(image.imageUrl);
- const blob = await toPngBlob(await response.blob());
+ const response = await fetch(image.imageUrl, { signal: owner.signal });
+ const sourceBlob = await response.blob();
+
+ assertAccountScopeCurrent(owner);
+ const blob = await toPngBlob(sourceBlob);
+ assertAccountScopeCurrent(owner);
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ assertAccountScopeCurrent(owner);
recordSuccess('Copied image to clipboard');
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
deleteImages: async (imageNames) => {
+ const owner = captureAccountScope();
+
try {
- await galleryOrganization.deleteImages(imageNames);
+ await galleryOrganization.deleteImages(imageNames, owner.signal);
+
+ assertAccountScopeCurrent(owner);
gallery.removeImages(imageNames, projectId);
onImagesDeleted?.(imageNames);
recordSuccess(imageNames.length === 1 ? 'Deleted image' : `Deleted ${imageNames.length} images`);
refreshGallery();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
downloadImage: async (image) => {
+ const owner = captureAccountScope();
+
try {
- const response = await fetch(image.imageUrl);
- const objectUrl = URL.createObjectURL(await response.blob());
+ const response = await fetch(image.imageUrl, { signal: owner.signal });
+ const blob = await response.blob();
+
+ assertAccountScopeCurrent(owner);
+ const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
@@ -168,10 +197,16 @@ export const useImageActions = ({
anchor.click();
URL.revokeObjectURL(objectUrl);
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
downloadImages: async (imageNames) => {
+ const owner = captureAccountScope();
+
try {
notifications.add({
kind: 'info',
@@ -179,22 +214,30 @@ export const useImageActions = ({
title: 'Preparing download',
});
- const { blob, fileName } = await galleryTransfers.downloadArchive({ imageNames });
+ const { blob, fileName } = await galleryTransfers.downloadArchive({ imageNames, signal: owner.signal });
+ assertAccountScopeCurrent(owner);
saveBlobToDisk(blob, fileName);
recordSuccess('Download ready');
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
getImageRecallCapabilities: async (image) => {
+ const owner = captureAccountScope();
+
if (!currentGenerateValues) {
return EMPTY_IMAGE_RECALL_CAPABILITIES;
}
try {
- const metadata = await galleryImages.metadata(image.imageName);
+ const metadata = await galleryImages.metadata(image.imageName, owner.signal);
+ assertAccountScopeCurrent(owner);
return getImageRecallCapabilities({
currentValues: currentGenerateValues,
image,
@@ -204,6 +247,10 @@ export const useImageActions = ({
vaeModels,
});
} catch {
+ if (!isAccountScopeCurrent(owner)) {
+ return EMPTY_IMAGE_RECALL_CAPABILITIES;
+ }
+
return {
...EMPTY_IMAGE_RECALL_CAPABILITIES,
dimensions:
@@ -212,13 +259,16 @@ export const useImageActions = ({
}
},
moveImagesToBoard: async (imageNames, boardId) => {
+ const owner = captureAccountScope();
+
try {
if (boardId === 'none') {
- await galleryOrganization.removeFromBoard(imageNames);
+ await galleryOrganization.removeFromBoard(imageNames, owner.signal);
} else {
- await galleryOrganization.addToBoard(boardId, imageNames);
+ await galleryOrganization.addToBoard(boardId, imageNames, owner.signal);
}
+ assertAccountScopeCurrent(owner);
recordSuccess(
imageNames.length === 1
? `Moved image to ${getBoardName(boardId)}`
@@ -226,6 +276,10 @@ export const useImageActions = ({
);
refreshGallery();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordError(error);
}
},
@@ -234,6 +288,7 @@ export const useImageActions = ({
openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });
},
recallImageData: async (image, kind) => {
+ const owner = captureAccountScope();
const didRecall = await executeImageRecall({
commands,
generateValues,
@@ -244,7 +299,7 @@ export const useImageActions = ({
projectId,
});
- if (didRecall && (!projectId || queries.isActiveProject(projectId))) {
+ if (isAccountScopeCurrent(owner) && didRecall && (!projectId || queries.isActiveProject(projectId))) {
openWorkbenchWidget('generate', { preferredRegions: ['left'] });
}
},
@@ -252,6 +307,8 @@ export const useImageActions = ({
gallery.setCompareImage(image, projectId);
},
sendToCanvas: async (images, destination) => {
+ const owner = captureAccountScope();
+
try {
const targetProjectId = projectId ?? queries.getSnapshot().activeProject.id;
const project = queries.getProject(targetProjectId);
@@ -271,6 +328,8 @@ export const useImageActions = ({
isActiveProject: queries.isActiveProject,
project,
});
+
+ assertAccountScopeCurrent(owner);
const notice = getCanvasImportNotice(result);
notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });
@@ -278,6 +337,10 @@ export const useImageActions = ({
openWorkbenchWidget('canvas', { preferredRegions: ['center'], requireCenterView: true });
}
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
recordCanvasImportError({
error,
localizedMessage: t('widgets.canvas.import.failed'),
@@ -287,12 +350,20 @@ export const useImageActions = ({
}
},
setImagesStarred: async (imageNames, starred) => {
+ const owner = captureAccountScope();
+
onStarredChange?.(imageNames, starred);
try {
- await galleryOrganization.setStarred(imageNames, starred);
+ await galleryOrganization.setStarred(imageNames, starred, owner.signal);
+
+ assertAccountScopeCurrent(owner);
refreshGalleryImages();
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
onStarredChange?.(imageNames, !starred);
recordError(error);
}
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index ff115a6258..c39e9f6ca1 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -12,6 +12,7 @@ import type { WidgetId } from '@workbench/widgetContracts';
import { getDefaultGenerateSettings } from '@features/generation/settings';
import { createDefaultUpscaleWidgetValues } from '@features/upscale';
+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -346,14 +347,16 @@ describe('submitResolvedInvocation', () => {
const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
const prepareCanvasInvocation = vi.fn();
const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'canvas' });
+ const owner = captureAccountScope();
- submitResolvedInvocation({ commands, models: undefined, prepareCanvasInvocation, project, route });
+ submitResolvedInvocation({ commands, models: undefined, owner, prepareCanvasInvocation, project, route });
expect(submitResolved).not.toHaveBeenCalled();
expect(prepareCanvasInvocation).toHaveBeenCalledTimes(1);
// The resolved destination rides through so a Canvas source can target the Gallery.
expect(prepareCanvasInvocation.mock.calls[0]?.[0]).toMatchObject({
destination: 'gallery',
+ owner,
projectId: project.id,
});
});
@@ -367,7 +370,14 @@ describe('submitResolvedInvocation', () => {
const prepareCanvasInvocation = vi.fn();
const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });
- submitResolvedInvocation({ commands, models: undefined, prepareCanvasInvocation, project, route });
+ submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation,
+ project,
+ route,
+ });
expect(prepareCanvasInvocation).not.toHaveBeenCalled();
expect(submitResolved).toHaveBeenCalledTimes(1);
@@ -375,4 +385,19 @@ describe('submitResolvedInvocation', () => {
route: expect.objectContaining({ destination: 'gallery', sourceId: 'generate' }),
});
});
+
+ it('quietly ignores a submission owned by an expired account scope', () => {
+ const project = getActiveProject(createGenerateValues(animaModel));
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+ const prepareCanvasInvocation = vi.fn();
+ const route = routeFor(project, { ...project.invocation, sourceId: 'generate' });
+ const owner = captureAccountScope();
+
+ accountLifecycle.invalidate();
+ submitResolvedInvocation({ commands, models: undefined, owner, prepareCanvasInvocation, project, route });
+
+ expect(prepareCanvasInvocation).not.toHaveBeenCalled();
+ expect(submitResolved).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 1b6fc84ebc..3766689b26 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -14,9 +14,12 @@
*/
import type { ModelConfig } from '@features/models';
+import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';
import type { Project } from '@workbench/projectContracts';
+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+
import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';
import type { WorkbenchCommands } from './workbenchStore';
@@ -31,6 +34,8 @@ export interface SubmitResolvedInvocationDeps {
project: Project;
/** Loaded models (or `undefined` while loading), forwarded verbatim to both paths. */
models: readonly ModelConfig[] | undefined;
+ /** Identity lifetime that initiated this submission. */
+ owner: AccountScope;
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
/**
* The async canvas-invoke entry point, injected for testability. The real
@@ -46,10 +51,15 @@ export const submitResolvedInvocation = ({
commands,
formatControlLayerError,
models,
+ owner,
prepareCanvasInvocation,
project,
route,
}: SubmitResolvedInvocationDeps): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
if (route.sourceId === 'canvas') {
// The canvas graph is composited + compiled asynchronously outside the
// reducer; fire-and-track (the orchestrator records any failure notice and
@@ -63,6 +73,7 @@ export const submitResolvedInvocation = ({
formatControlLayerError,
generateValues: getProjectWidgetValues(project, 'generate'),
models,
+ owner,
projectId: project.id,
projectSettings: project.settings,
strength: readCanvasDenoisingStrength(getProjectWidgetValues(project, 'canvas')),
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
index 4efe46f921..b43ae490c9 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx
@@ -2,6 +2,12 @@ import type { SystemStyleObject } from '@chakra-ui/react';
import { Flex, Heading, HStack, Stack, Text } from '@chakra-ui/react';
import { useAuthSession } from '@features/identity';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, Scrollable, toaster } from '@platform/ui';
import { Link, useNavigate } from '@tanstack/react-router';
import { KnownBrowserIssuesAlert } from '@workbench/launchpad/KnownBrowserIssuesAlert';
@@ -9,7 +15,7 @@ import { ProjectsGrid } from '@workbench/launchpad/ProjectsGrid';
import { refreshProjectLibrary } from '@workbench/projects/library';
import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';
import { FileUpIcon, PlusIcon } from 'lucide-react';
-import { useCallback, useEffect } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
/**
@@ -31,9 +37,9 @@ export const ProjectsPage = () => {
const navigate = useNavigate();
const { t } = useTranslation();
- useEffect(() => {
+ useMountEffect(() => {
void refreshProjectLibrary();
- }, []);
+ });
const displayName = session.user?.display_name?.trim();
const greeting = displayName
@@ -41,17 +47,24 @@ export const ProjectsPage = () => {
: t('launchpad.projectsGreeting');
const handleImport = useCallback(async () => {
- const file = await pickProjectFile();
+ const owner = captureAccountScope();
+ const file = await pickProjectFile(owner);
- if (!file) {
+ if (!file || !isAccountScopeCurrent(owner)) {
return;
}
try {
- const record = await importProjectFile(file);
+ const record = await importProjectFile(file, owner);
+ assertAccountScopeCurrent(owner);
await navigate({ search: { project: record.project_id }, to: '/app' });
+ assertAccountScopeCurrent(owner);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
toaster.create({
description: error instanceof Error ? error.message : undefined,
title: t('projects.importFailed'),
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
index 8f2e60874a..5d7f73f9c4 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStoreCore } from '@platform/state/externalStoreCore';
import { useSyncExternalStore } from 'react';
@@ -17,6 +18,14 @@ export const useIsCommandPaletteOpen = (): boolean =>
let returnFocusElement: HTMLElement | null = null;
+registerAccountOwnedResource({
+ clear: () => {
+ returnFocusElement = null;
+ commandPaletteStore.setSnapshot({ isOpen: false });
+ },
+ name: 'command-palette',
+});
+
const captureReturnFocusElement = (): void => {
const activeElement = document.activeElement;
diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.ts
index 51dac6bb05..48b01ef929 100644
--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts
@@ -1,13 +1,16 @@
+import type { WorkbenchState } from '@workbench/projectContracts';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ createLocalStorageWorkbenchPersistence,
hydratePersistedWorkbenchSnapshot,
- localStorageWorkbenchPersistence,
serializeWorkbenchPersistenceSnapshot,
} from './persistence';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
const storage = new Map<string, string>();
+const localStorageWorkbenchPersistence = createLocalStorageWorkbenchPersistence('');
vi.stubGlobal('window', {
localStorage: {
@@ -160,4 +163,32 @@ describe('workbench persistence migration', () => {
expect(storage.has('invokeai:v7:webv2:workbench')).toBe(true);
});
+
+ it('keeps each constructed persistence adapter bound to its immutable account bucket', async () => {
+ const accountA = createLocalStorageWorkbenchPersistence(':user:a');
+ const accountB = createLocalStorageWorkbenchPersistence(':user:b');
+ const stateA = createInitialWorkbenchState();
+ const stateB = createInitialWorkbenchState();
+
+ stateA.projects[0]!.name = 'Account A';
+ stateB.projects[0]!.name = 'Account B';
+
+ await accountA.saveWorkbench(stateA);
+ await accountB.saveWorkbench(stateB);
+
+ // This late A write still targets A even though B's adapter was constructed
+ // and used in between.
+ stateA.projects[0]!.name = 'Account A late save';
+ await accountA.saveWorkbench(stateA);
+
+ const persistedA = JSON.parse(storage.get('invokeai:v7:webv2:workbench:user:a') ?? 'null') as {
+ state: WorkbenchState;
+ };
+ const persistedB = JSON.parse(storage.get('invokeai:v7:webv2:workbench:user:b') ?? 'null') as {
+ state: WorkbenchState;
+ };
+
+ expect(persistedA.state.projects[0]?.name).toBe('Account A late save');
+ expect(persistedB.state.projects[0]?.name).toBe('Account B');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.ts
index 20f077c66e..31f2e4ff52 100644
--- a/invokeai/frontend/webv2/src/workbench/persistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts
@@ -1,20 +1,11 @@
import type { HydratedWorkbenchSnapshot, PersistedWorkbenchSnapshotV1 } from '@workbench/persistenceContracts';
import type { WorkbenchState } from '@workbench/projectContracts';
-import { getUserStorageScope } from '@features/identity';
-
import { timeWorkbenchPerf } from './performanceMarks';
const BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';
const WORKBENCH_SCHEMA_VERSION = 1;
-/**
- * Projects and the editor session are account-owned on multi-user backends, so
- * each signed-in user gets their own storage bucket on this browser.
- * Single-user mode keeps the unscoped key, so existing data is untouched.
- */
-const getStorageKey = (): string => `${BASE_STORAGE_KEY}${getUserStorageScope()}`;
-
export interface WorkbenchPersistenceService {
loadWorkbench(): Promise<HydratedWorkbenchSnapshot | null>;
saveWorkbench(state: WorkbenchState): Promise<HydratedWorkbenchSnapshot>;
@@ -82,55 +73,64 @@ export const serializeWorkbenchPersistenceSnapshot = (
version: WORKBENCH_SCHEMA_VERSION,
});
-export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {
- clearWorkbench() {
- if (!isBrowser()) {
- return Promise.resolve();
- }
-
- window.localStorage.removeItem(getStorageKey());
-
- return Promise.resolve();
- },
- loadWorkbench() {
- if (!isBrowser()) {
- return Promise.resolve(null);
- }
-
- const value = window.localStorage.getItem(getStorageKey());
+/**
+ * Construct one account-owned browser cache. The suffix is captured once,
+ * rather than read from mutable auth state when a debounced save eventually
+ * executes, so work started by account A can never land in account B's bucket.
+ */
+export const createLocalStorageWorkbenchPersistence = (storageSuffix: string): WorkbenchPersistenceService => {
+ const storageKey = `${BASE_STORAGE_KEY}${storageSuffix}`;
- if (!value) {
- return Promise.resolve(null);
- }
+ return {
+ clearWorkbench() {
+ if (!isBrowser()) {
+ return Promise.resolve();
+ }
- try {
- return Promise.resolve(hydratePersistedWorkbenchSnapshot(JSON.parse(value)));
- } catch {
- window.localStorage.removeItem(getStorageKey());
+ window.localStorage.removeItem(storageKey);
- return Promise.resolve(null);
- }
- },
- saveWorkbench(state) {
- const snapshot = createSnapshot(state);
+ return Promise.resolve();
+ },
+ loadWorkbench() {
+ if (!isBrowser()) {
+ return Promise.resolve(null);
+ }
+
+ const value = window.localStorage.getItem(storageKey);
+
+ if (!value) {
+ return Promise.resolve(null);
+ }
+
+ try {
+ return Promise.resolve(hydratePersistedWorkbenchSnapshot(JSON.parse(value)));
+ } catch {
+ window.localStorage.removeItem(storageKey);
+
+ return Promise.resolve(null);
+ }
+ },
+ saveWorkbench(state) {
+ const snapshot = createSnapshot(state);
+
+ if (!isBrowser()) {
+ return Promise.resolve(snapshot);
+ }
+
+ try {
+ window.localStorage.setItem(
+ storageKey,
+ timeWorkbenchPerf(
+ 'workbench:persistence-localstorage-stringify',
+ { area: 'persistence', kind: 'workbench', projectId: state.activeProjectId },
+ () => JSON.stringify(serializeWorkbenchPersistenceSnapshot(snapshot))
+ )
+ );
+ } catch {
+ // The backend remains the source of truth; localStorage is only an offline cache.
+ }
- if (!isBrowser()) {
return Promise.resolve(snapshot);
- }
-
- try {
- window.localStorage.setItem(
- getStorageKey(),
- timeWorkbenchPerf(
- 'workbench:persistence-localstorage-stringify',
- { area: 'persistence', kind: 'workbench', projectId: state.activeProjectId },
- () => JSON.stringify(serializeWorkbenchPersistenceSnapshot(snapshot))
- )
- );
- } catch {
- // The backend remains the source of truth; localStorage is only an offline cache.
- }
-
- return Promise.resolve(snapshot);
- },
+ },
+ };
};
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
index a00def113a..19e31f3c19 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
@@ -380,6 +380,29 @@ describe('Workbench persistence runtime', () => {
expect(listener).toHaveBeenCalledTimes(1);
});
+ it('disposes immediately when its owning account signal is aborted', async () => {
+ const aggregate = createAggregate();
+ const { persistence } = createPersistence(() => Promise.resolve(null));
+ const clock = new FakeClock();
+ const controller = new AbortController();
+ const runtime = createWorkbenchPersistenceRuntime({
+ aggregate: aggregate.port,
+ clock,
+ persistence,
+ signal: controller.signal,
+ });
+
+ runtime.start();
+ await flushPromises();
+ aggregate.edit('Account A edit');
+
+ controller.abort();
+ clock.runAll();
+
+ expect(runtime.getSnapshot().phase).toBe('disposed');
+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();
+ });
+
it('hydrates through a fresh instance after a prior one was disposed mid-load (StrictMode remount)', async () => {
const aggregate = createAggregate();
const loadedState = createInitialWorkbenchState();
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
index 8b761dec5d..b80914e623 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
@@ -53,12 +53,15 @@ export const createWorkbenchPersistenceRuntime = ({
loadOptions,
persistence,
saveDelayMs = 500,
+ signal,
}: {
aggregate: PersistenceAggregatePort;
clock?: PersistenceClock;
loadOptions?: WorkbenchLoadOptions;
persistence: WorkbenchPersistencePort;
saveDelayMs?: number;
+ /** Cancels this runtime when the account lifetime that owns it expires. */
+ signal?: AbortSignal;
}): WorkbenchPersistenceRuntime => {
let snapshot: PersistenceRuntimeSnapshot = { error: null, phase: 'idle' };
const listeners = new Set<() => void>();
@@ -247,26 +250,34 @@ export const createWorkbenchPersistenceRuntime = ({
}
};
+ const dispose = (): void => {
+ if (disposed) {
+ return;
+ }
+ disposed = true;
+ generation += 1;
+ queuedSaveRequireCurrentRevision = null;
+ clearScheduledSave();
+ unsubscribeAggregate?.();
+ unsubscribeAggregate = null;
+ signal?.removeEventListener('abort', dispose);
+ snapshot = { error: null, phase: 'disposed' };
+ listeners.clear();
+ };
+
return {
- dispose() {
- if (disposed) {
- return;
- }
- disposed = true;
- generation += 1;
- queuedSaveRequireCurrentRevision = null;
- clearScheduledSave();
- unsubscribeAggregate?.();
- unsubscribeAggregate = null;
- snapshot = { error: null, phase: 'disposed' };
- listeners.clear();
- },
+ dispose,
getSnapshot: () => snapshot,
start() {
if (started || disposed) {
return;
}
+ if (signal?.aborted) {
+ dispose();
+ return;
+ }
started = true;
+ signal?.addEventListener('abort', dispose, { once: true });
unsubscribeAggregate = aggregate.subscribe(onAggregateChange);
void load();
},
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.ts
index 5deae9daec..5892151a24 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts
@@ -35,22 +35,28 @@ export interface ProjectUpdateRequest {
expected_revision: number;
}
-export const listProjects = (): Promise<ProjectSummaryDTO[]> => apiFetchJson<ProjectSummaryDTO[]>(`${PROJECTS_BASE}/`);
+export const listProjects = (signal?: AbortSignal): Promise<ProjectSummaryDTO[]> =>
+ apiFetchJson<ProjectSummaryDTO[]>(`${PROJECTS_BASE}/`, { signal });
-export const getProject = (projectId: string): Promise<ProjectRecordDTO> =>
- apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`);
+export const getProject = (projectId: string, signal?: AbortSignal): Promise<ProjectRecordDTO> =>
+ apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { signal });
-export const createProject = (request: ProjectCreateRequest): Promise<ProjectRecordDTO> =>
- apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/`, { body: JSON.stringify(request), method: 'POST' });
+export const createProject = (request: ProjectCreateRequest, signal?: AbortSignal): Promise<ProjectRecordDTO> =>
+ apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/`, { body: JSON.stringify(request), method: 'POST', signal });
-export const updateProject = (projectId: string, request: ProjectUpdateRequest): Promise<ProjectRecordDTO> =>
+export const updateProject = (
+ projectId: string,
+ request: ProjectUpdateRequest,
+ signal?: AbortSignal
+): Promise<ProjectRecordDTO> =>
apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, {
body: JSON.stringify(request),
method: 'PUT',
+ signal,
});
-export const deleteProject = async (projectId: string): Promise<void> => {
- await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { method: 'DELETE' });
+export const deleteProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { method: 'DELETE', signal });
};
/** A save was based on a stale revision — another tab or device saved first. */
@@ -58,17 +64,18 @@ export const isProjectConflictError = (error: unknown): boolean => error instanc
export const isProjectNotFoundError = (error: unknown): boolean => error instanceof ApiError && error.status === 404;
-export const getClientStateValue = (key: string): Promise<string | null> =>
- apiFetchJson<string | null>(`${CLIENT_STATE_BASE}/get_by_key?key=${encodeURIComponent(key)}`);
+export const getClientStateValue = (key: string, signal?: AbortSignal): Promise<string | null> =>
+ apiFetchJson<string | null>(`${CLIENT_STATE_BASE}/get_by_key?key=${encodeURIComponent(key)}`, { signal });
/** The endpoint takes a JSON-encoded string body, hence the stringify of a string. */
-export const setClientStateValue = async (key: string, value: string): Promise<void> => {
+export const setClientStateValue = async (key: string, value: string, signal?: AbortSignal): Promise<void> => {
await apiFetchJson<string>(`${CLIENT_STATE_BASE}/set_by_key?key=${encodeURIComponent(key)}`, {
body: JSON.stringify(value),
method: 'POST',
+ signal,
});
};
-export const deleteClientStateValue = async (key: string): Promise<void> => {
- await apiFetch(`${CLIENT_STATE_BASE}/delete_by_key?key=${encodeURIComponent(key)}`, { method: 'POST' });
+export const deleteClientStateValue = async (key: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`${CLIENT_STATE_BASE}/delete_by_key?key=${encodeURIComponent(key)}`, { method: 'POST', signal });
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
index 4cee8c998d..c81c04541b 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx
@@ -1,6 +1,11 @@
import { Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
import { flushGenerateDrafts } from '@features/generation/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { areArraysEqual } from '@platform/state/selectors';
import { Button, CloseButton, Row, Scrollable } from '@platform/ui';
import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';
@@ -48,35 +53,54 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos
const openProject = useCallback(
async (summary: ProjectSummary) => {
+ const owner = captureAccountScope();
+
setBusyProjectId(summary.id);
- const project = await persistence.hydrateProjectFromServer(summary.id);
+ try {
+ const project = await persistence.hydrateProjectFromServer(summary.id);
- setBusyProjectId(null);
+ assertAccountScopeCurrent(owner);
+ if (!project) {
+ notify.error(t('projects.couldNotOpen'), t('projects.couldNotOpenDescription', { name: summary.name }));
+ void refreshProjectLibrary();
- if (!project) {
- notify.error(t('projects.couldNotOpen'), t('projects.couldNotOpenDescription', { name: summary.name }));
- void refreshProjectLibrary();
+ return;
+ }
- return;
+ flushGenerateDrafts();
+ projects.open(project);
+ onClose();
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ notify.error(
+ t('projects.couldNotOpen'),
+ error instanceof Error ? error.message : t('projects.couldNotOpenDescription', { name: summary.name })
+ );
+ } finally {
+ if (isAccountScopeCurrent(owner)) {
+ setBusyProjectId(null);
+ }
}
-
- flushGenerateDrafts();
- projects.open(project);
- onClose();
},
[notify, onClose, persistence, projects, t]
);
const handleImport = useCallback(async () => {
- const file = await pickProjectFile();
+ const owner = captureAccountScope();
+ const file = await pickProjectFile(owner);
- if (!file) {
+ if (!file || !isAccountScopeCurrent(owner)) {
return;
}
try {
- const record = await importProjectFile(file);
+ const record = await importProjectFile(file, owner);
+
+ assertAccountScopeCurrent(owner);
const project = persistence.adoptProjectRecord(record);
if (project) {
@@ -85,6 +109,10 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos
onClose();
}
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notify.error(t('projects.importFailed'), error instanceof Error ? error.message : undefined);
}
}, [notify, onClose, persistence, projects, t]);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
index 4d6d7d321d..bc7d500aab 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
@@ -1,3 +1,5 @@
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as libraryModule from './library';
@@ -19,6 +21,7 @@ const api = vi.hoisted(() => ({
vi.mock('./api', () => api);
let library: typeof libraryModule;
+let account: typeof accountLifecycleModule;
const summaryDto = (id: string, name: string, updatedAt: string) => ({
created_at: '2026-06-01 08:00:00.000',
@@ -37,6 +40,7 @@ beforeEach(async () => {
api.updateProject.mockReset();
library = await import('./library');
+ account = await import('@platform/state/accountLifecycle');
});
describe('refreshProjectLibrary', () => {
@@ -68,6 +72,27 @@ describe('refreshProjectLibrary', () => {
expect(error).toBe('offline');
expect(summaries.map((summary) => summary.id)).toEqual(['kept']);
});
+
+ it('cannot commit a delayed response into a later account epoch', async () => {
+ account.accountLifecycle.activate('user-a');
+ let resolveUserA: ((value: ReturnType<typeof summaryDto>[]) => void) | undefined;
+ api.listProjects.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveUserA = resolve;
+ })
+ );
+ const userARefresh = library.refreshProjectLibrary();
+
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b');
+ api.listProjects.mockResolvedValueOnce([summaryDto('b', 'User B', '2026-06-11 10:00:00.000')]);
+ await library.refreshProjectLibrary();
+
+ resolveUserA?.([summaryDto('a', 'User A', '2026-06-12 10:00:00.000')]);
+ await userARefresh;
+
+ expect(library.getProjectLibrary().summaries.map((summary) => summary.name)).toEqual(['User B']);
+ });
});
describe('upsertProjectSummary', () => {
@@ -78,7 +103,7 @@ describe('upsertProjectSummary', () => {
]);
await library.refreshProjectLibrary();
- library.upsertProjectSummary({ id: 'a', name: 'A renamed', revision: 2 });
+ library.upsertProjectSummary({ id: 'a', name: 'A renamed', revision: 2 }, account.accountLifecycle.capture());
const { summaries } = library.getProjectLibrary();
@@ -96,7 +121,7 @@ describe('library mutations', () => {
await library.deleteLibraryProject('doomed');
- expect(api.deleteProject).toHaveBeenCalledWith('doomed');
+ expect(api.deleteProject).toHaveBeenCalledWith('doomed', expect.any(AbortSignal));
expect(library.getProjectLibrary().summaries).toHaveLength(0);
});
@@ -113,11 +138,15 @@ describe('library mutations', () => {
await library.renameLibraryProject('p1', 'New name');
- expect(api.updateProject).toHaveBeenCalledWith('p1', {
- data: { id: 'p1', layout: {}, name: 'New name' },
- expected_revision: 1,
- name: 'New name',
- });
+ expect(api.updateProject).toHaveBeenCalledWith(
+ 'p1',
+ {
+ data: { id: 'p1', layout: {}, name: 'New name' },
+ expected_revision: 1,
+ name: 'New name',
+ },
+ expect.any(AbortSignal)
+ );
expect(library.getProjectLibrary().summaries[0]?.name).toBe('New name');
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.ts
index ea42a8c490..53603fb657 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts
@@ -1,3 +1,10 @@
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { createSingleFlight } from '@platform/state/singleFlight';
import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';
@@ -40,7 +47,15 @@ export interface ProjectLibrarySnapshot {
error?: string;
}
-const store = createExternalStore<ProjectLibrarySnapshot>({ status: 'idle', summaries: [] });
+const EMPTY_PROJECT_LIBRARY: ProjectLibrarySnapshot = { status: 'idle', summaries: [] };
+const store = createExternalStore<ProjectLibrarySnapshot>(EMPTY_PROJECT_LIBRARY);
+
+registerAccountOwnedResource({
+ clear: () => {
+ store.setSnapshot(EMPTY_PROJECT_LIBRARY);
+ },
+ name: 'project-library',
+});
const toSummary = (dto: ProjectSummaryDTO): ProjectSummary => ({
createdAt: normalizeServerTimestamp(dto.created_at),
@@ -61,7 +76,11 @@ export const useProjectLibrarySelector = store.useSelector;
export const getProjectLibrary = (): ProjectLibrarySnapshot => store.getSnapshot();
/** Adopt summaries already fetched elsewhere (the workbench boot pass). */
-export const seedProjectLibrary = (dtos: ProjectSummaryDTO[]): void => {
+export const seedProjectLibrary = (dtos: ProjectSummaryDTO[], owner: AccountScope): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
store.setSnapshot({ status: 'ready', summaries: sortSummaries(dtos.map(toSummary)) });
};
@@ -69,25 +88,40 @@ const refreshFlight = createSingleFlight<void>();
/** Re-list from the server; concurrent calls share one request. */
export const refreshProjectLibrary = (): Promise<void> =>
- refreshFlight.run('project-library', () =>
- listProjects()
- .then((dtos) => {
- seedProjectLibrary(dtos);
- })
- .catch((error: unknown) => {
- store.patchSnapshot({
- error: error instanceof Error ? error.message : 'Failed to load projects.',
- status: 'error',
- });
- })
- );
+ (() => {
+ const owner = captureAccountScope();
+
+ return refreshFlight.run(`project-library:${owner.epoch}`, () =>
+ listProjects(owner.signal)
+ .then((dtos) => {
+ seedProjectLibrary(dtos, owner);
+ })
+ .catch((error: unknown) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load projects.',
+ status: 'error',
+ });
+ })
+ );
+ })();
/**
* Reflect a save the editor just pushed, so the library stays current without
* a refetch. `updatedAt` is stamped locally; the next refresh replaces it
* with the server's value.
*/
-export const upsertProjectSummary = (entry: { id: string; name: string; revision: number | null }): void => {
+export const upsertProjectSummary = (
+ entry: { id: string; name: string; revision: number | null },
+ owner: AccountScope
+): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
const { summaries } = store.getSnapshot();
const existing = summaries.find((summary) => summary.id === entry.id);
const updatedAt = new Date().toISOString();
@@ -107,7 +141,10 @@ export const upsertProjectSummary = (entry: { id: string; name: string; revision
/** Permanently remove a project from the server. The only deletion path. */
export const deleteLibraryProject = async (projectId: string): Promise<void> => {
- await apiDeleteProject(projectId);
+ const owner = captureAccountScope();
+
+ await apiDeleteProject(projectId, owner.signal);
+ assertAccountScopeCurrent(owner);
store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });
};
@@ -117,29 +154,44 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>
* revision chain stay consistent.
*/
export const renameLibraryProject = async (projectId: string, name: string): Promise<void> => {
- const record = await apiGetProject(projectId);
- const updated = await apiUpdateProject(projectId, {
- data: { ...record.data, name },
- expected_revision: record.revision,
- name,
- });
+ const owner = captureAccountScope();
+ const record = await apiGetProject(projectId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ const updated = await apiUpdateProject(
+ projectId,
+ {
+ data: { ...record.data, name },
+ expected_revision: record.revision,
+ name,
+ },
+ owner.signal
+ );
- upsertProjectSummary({ id: updated.project_id, name: updated.name, revision: updated.revision });
+ assertAccountScopeCurrent(owner);
+ upsertProjectSummary({ id: updated.project_id, name: updated.name, revision: updated.revision }, owner);
};
/** Copy a project under a fresh id; returns the new summary. */
export const duplicateLibraryProject = async (projectId: string): Promise<ProjectSummary> => {
- const record = await apiGetProject(projectId);
+ const owner = captureAccountScope();
+ const record = await apiGetProject(projectId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
const newId = createProjectId();
const name = `${record.name} copy`;
- const created = await apiCreateProject({
- data: { ...record.data, id: newId, name },
- name,
- project_id: newId,
- });
+ const created = await apiCreateProject(
+ {
+ data: { ...record.data, id: newId, name },
+ name,
+ project_id: newId,
+ },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
const summary = toSummary(created);
- upsertProjectSummary({ id: summary.id, name: summary.name, revision: summary.revision });
+ upsertProjectSummary({ id: summary.id, name: summary.name, revision: summary.revision }, owner);
return summary;
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index fadadd5b8d..cdc55e28d9 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -20,6 +20,15 @@ vi.mock('./api', () => api);
let projectFile: typeof projectFileModule;
let persistence: typeof persistenceModule;
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
+
beforeEach(async () => {
vi.resetModules();
api.createProject.mockReset();
@@ -89,4 +98,23 @@ describe('importProjectFile', () => {
await expect(projectFile.importProjectFile(fileFor({ some: 'json' }))).rejects.toThrow('not an Invoke project');
expect(api.createProject).not.toHaveBeenCalled();
});
+
+ it('does not upload an account A file after local parsing completes under account B', async () => {
+ const account = await import('@platform/state/accountLifecycle');
+ const project = { ...createDraftProject([]), name: 'Account A project' };
+ const document = persistence.serializeProjectDocument(project);
+ const contents = deferred<string>();
+ const file = fileFor('');
+
+ vi.spyOn(file, 'text').mockReturnValue(contents.promise);
+ account.accountLifecycle.activate('project-import-a');
+ const imported = projectFile.importProjectFile(file);
+
+ account.accountLifecycle.activate('project-import-b');
+ contents.resolve(JSON.stringify(projectFile.buildProjectFile(document)));
+
+ await expect(imported).rejects.toThrow('no longer active');
+ expect(api.createProject).not.toHaveBeenCalled();
+ account.accountLifecycle.invalidate();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 5bb8b205bd..25b985cf13 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -1,5 +1,12 @@
import type { Project } from '@workbench/projectContracts';
+import {
+ type AccountScope,
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+
import { createProject as apiCreateProject, getProject as apiGetProject, type ProjectRecordDTO } from './api';
import { createProjectId } from './ids';
import { upsertProjectSummary } from './library';
@@ -66,9 +73,13 @@ const downloadProjectFile = (name: string, projectDocument: Record<string, unkno
};
/** Export a closed project straight from its server record. */
-export const exportLibraryProject = async (projectId: string): Promise<void> => {
- const record = await apiGetProject(projectId);
+export const exportLibraryProject = async (
+ projectId: string,
+ owner: AccountScope = captureAccountScope()
+): Promise<void> => {
+ const record = await apiGetProject(projectId, owner.signal);
+ assertAccountScopeCurrent(owner);
downloadProjectFile(record.name, record.data);
};
@@ -82,9 +93,14 @@ export const exportOpenProject = (project: Project): void => {
* id — never the one in the file — so an import can never collide with (and
* overwrite) an existing project. Throws with a user-readable message.
*/
-export const importProjectFile = async (file: File): Promise<ProjectRecordDTO> => {
+export const importProjectFile = async (
+ file: File,
+ owner: AccountScope = captureAccountScope()
+): Promise<ProjectRecordDTO> => {
const projectDocument = parseProjectFile(await file.text());
+ assertAccountScopeCurrent(owner);
+
if (!projectDocument) {
throw new Error('This file is not an Invoke project export.');
}
@@ -100,21 +116,43 @@ export const importProjectFile = async (file: File): Promise<ProjectRecordDTO> =
throw new Error('The project file is damaged and cannot be opened.');
}
- const record = await apiCreateProject({ data: document, name, project_id: id });
+ const record = await apiCreateProject({ data: document, name, project_id: id }, owner.signal);
- upsertProjectSummary({ id: record.project_id, name: record.name, revision: record.revision });
+ assertAccountScopeCurrent(owner);
+ upsertProjectSummary({ id: record.project_id, name: record.name, revision: record.revision }, owner);
return record;
};
/** Open the browser's file picker for a project file; null when dismissed. */
-export const pickProjectFile = (): Promise<File | null> =>
+export const pickProjectFile = (owner: AccountScope = captureAccountScope()): Promise<File | null> =>
new Promise((resolve) => {
const input = document.createElement('input');
+ let isSettled = false;
+
+ const finish = (file: File | null): void => {
+ if (isSettled) {
+ return;
+ }
+
+ isSettled = true;
+ owner.signal.removeEventListener('abort', handleAbort);
+ input.onchange = null;
+ input.oncancel = null;
+ resolve(isAccountScopeCurrent(owner) ? file : null);
+ };
+ const handleAbort = (): void => finish(null);
input.type = 'file';
input.accept = 'application/json,.json';
- input.onchange = () => resolve(input.files?.[0] ?? null);
- input.oncancel = () => resolve(null);
+ input.onchange = () => finish(input.files?.[0] ?? null);
+ input.oncancel = () => finish(null);
+ owner.signal.addEventListener('abort', handleAbort, { once: true });
+
+ if (owner.signal.aborted) {
+ finish(null);
+ return;
+ }
+
input.click();
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.ts
index 88c39c2627..72fd320b5e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts
@@ -67,10 +67,12 @@ export const serializeSessionBlob = (state: WorkbenchState): string =>
openProjectIds: state.projects.map((project) => project.id),
} satisfies WorkbenchSessionBlob);
-export const fetchSessionBlob = async (): Promise<WorkbenchSessionBlob | null> => {
+export const fetchSessionBlob = async (signal?: AbortSignal): Promise<WorkbenchSessionBlob | null> => {
try {
- return parseSessionBlob(await getClientStateValue(SESSION_STATE_KEY));
+ return parseSessionBlob(await getClientStateValue(SESSION_STATE_KEY, signal));
} catch {
+ signal?.throwIfAborted();
+
return null;
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index 44dbbdd13b..1d119993a3 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -1,3 +1,4 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -19,10 +20,18 @@ export interface ProjectSyncSnapshot {
lastSyncedAt: string | null;
}
-const store = createExternalStore<ProjectSyncSnapshot>({
+const EMPTY_PROJECT_SYNC: ProjectSyncSnapshot = {
hasPendingChanges: false,
lastSyncedAt: null,
projects: {},
+};
+const store = createExternalStore<ProjectSyncSnapshot>(EMPTY_PROJECT_SYNC);
+
+registerAccountOwnedResource({
+ clear: () => {
+ store.setSnapshot(EMPTY_PROJECT_SYNC);
+ },
+ name: 'project-sync',
});
export const useProjectSync = (): ProjectSyncSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
index 6a24930298..b2de0b81cd 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
@@ -1,3 +1,4 @@
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { createWorkbenchPersistenceRuntime, type PersistenceClock } from '@workbench/persistenceRuntime';
@@ -131,6 +132,17 @@ vi.mock('./api', () => api);
const storage = new Map<string, string>();
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+
+ return { promise, reject, resolve };
+};
+
vi.stubGlobal('window', {
localStorage: {
getItem: (key: string): string | null => storage.get(key) ?? null,
@@ -147,8 +159,10 @@ const SESSION_KEY = 'webv2:workbench-account';
let persistence: typeof persistenceModule;
let library: typeof libraryModule;
+let account: typeof accountLifecycleModule;
let service: persistenceModule.SyncedWorkbenchPersistence;
const defaultUpdateProject = api.updateProject.getMockImplementation()!;
+const defaultSetClientStateValue = api.setClientStateValue.getMockImplementation()!;
const seedSessionBlob = (blob: Record<string, unknown>): void => {
api.__clientState.set(SESSION_KEY, JSON.stringify(blob));
@@ -179,9 +193,13 @@ beforeEach(async () => {
api.listProjects.mockClear();
api.updateProject.mockReset();
api.updateProject.mockImplementation(defaultUpdateProject);
+ api.setClientStateValue.mockReset();
+ api.setClientStateValue.mockImplementation(defaultSetClientStateValue);
+ account = await import('@platform/state/accountLifecycle');
+ account.accountLifecycle.activate('single-user', '');
persistence = await import('./syncedPersistence');
- service = persistence.createSyncedWorkbenchPersistence();
+ service = persistence.createSyncedWorkbenchPersistence(account.captureAccountScope());
library = await import('./library');
});
@@ -298,6 +316,49 @@ describe('loadWorkbench session hydration', () => {
});
describe('saveWorkbench', () => {
+ it('cancels an account-A save queued behind the mutation microtask before it can touch account B', async () => {
+ const ownerA = account.accountLifecycle.activate('user-a', ':user:a');
+ const accountAService = persistence.createSyncedWorkbenchPersistence(ownerA);
+ const stateA = createInitialWorkbenchState();
+
+ stateA.projects[0]!.name = 'Account A queued edit';
+ const queuedSave = accountAService.saveWorkbench(stateA);
+
+ account.accountLifecycle.activate('user-b', ':user:b');
+
+ await expect(queuedSave).rejects.toHaveProperty('name', 'AccountScopeExpiredError');
+ expect(storage.has('invokeai:v7:webv2:workbench:user:a')).toBe(false);
+ expect(storage.has('invokeai:v7:webv2:workbench:user:b')).toBe(false);
+ expect(api.setClientStateValue).not.toHaveBeenCalled();
+ expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.updateProject).not.toHaveBeenCalled();
+ });
+
+ it('stops an in-flight account-A save before the next backend request after account B activates', async () => {
+ const ownerA = account.accountLifecycle.activate('user-a', ':user:a');
+ const accountAService = persistence.createSyncedWorkbenchPersistence(ownerA);
+ const stateA = createInitialWorkbenchState();
+ const sessionWrite = deferred<void>();
+
+ stateA.projects[0]!.name = 'Account A in-flight edit';
+ api.setClientStateValue.mockImplementationOnce(() => sessionWrite.promise);
+
+ const inFlightSave = accountAService.saveWorkbench(stateA);
+
+ await vi.waitFor(() => expect(api.setClientStateValue).toHaveBeenCalledOnce());
+ expect(storage.has('invokeai:v7:webv2:workbench:user:a')).toBe(true);
+
+ account.accountLifecycle.activate('user-b', ':user:b');
+ sessionWrite.resolve();
+
+ await expect(inFlightSave).rejects.toHaveProperty('name', 'AccountScopeExpiredError');
+ expect(storage.has('invokeai:v7:webv2:workbench:user:b')).toBe(false);
+ // The already-started client-state request belonged to A. Its late
+ // completion must not advance the chain to a project create under B.
+ expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.updateProject).not.toHaveBeenCalled();
+ });
+
it('serializes concurrent saves against the latest acknowledged project revision', async () => {
const project = seedServerProject('Original');
const account = createInitialWorkbenchState().account;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
index ddc82d690d..82c4ba4eaa 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
@@ -1,9 +1,13 @@
import type { HydratedWorkbenchSnapshot } from '@workbench/persistenceContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
-import { getUserStorageScope } from '@features/identity';
+import { assertAccountScopeCurrent, captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';
import { timeWorkbenchPerf } from '@workbench/performanceMarks';
-import { localStorageWorkbenchPersistence, stripTransientWorkbenchState } from '@workbench/persistence';
+import {
+ createLocalStorageWorkbenchPersistence,
+ stripTransientWorkbenchState,
+ type WorkbenchPersistenceService,
+} from '@workbench/persistence';
import { createDraftProject, createInitialWorkbenchState, normalizeWorkbenchProject } from '@workbench/workbenchState';
import {
@@ -78,20 +82,29 @@ interface SyncedPersistenceState {
/** Ids deleted in this runtime lifetime, guarding against racing saves. */
deletedProjectIds: Set<string>;
hasPending: boolean;
+ localPersistence: WorkbenchPersistenceService;
lastPushedAccount: string | null;
+ /** Immutable owner captured when this synchronization lifetime was constructed. */
+ owner: AccountScope;
projectDocumentJsonCache: WeakMap<Project, { document: Record<string, unknown>; json: string }>;
/** Server-known projects, keyed by project id. */
syncEntries: Map<string, SyncEntry>;
}
-const createSyncedPersistenceState = (): SyncedPersistenceState => ({
+const createSyncedPersistenceState = (owner: AccountScope): SyncedPersistenceState => ({
deletedProjectIds: new Set(),
hasPending: false,
+ localPersistence: createLocalStorageWorkbenchPersistence(owner.storageSuffix),
lastPushedAccount: null,
+ owner,
projectDocumentJsonCache: new WeakMap(),
syncEntries: new Map(),
});
+const assertOwner = (syncState: SyncedPersistenceState): void => {
+ assertAccountScopeCurrent(syncState.owner);
+};
+
/**
* Undo/redo stacks are session-only (each entry is a full project snapshot,
* far too heavy to autosave); everything else in the project document is the
@@ -193,7 +206,8 @@ export const deserializeProjectDocument = (data: Record<string, unknown>): Proje
} as unknown as Project);
};
-const getSyncMapStorageKey = (): string => `${SYNC_MAP_BASE_KEY}${getUserStorageScope()}`;
+const getSyncMapStorageKey = (syncState: SyncedPersistenceState): string =>
+ `${SYNC_MAP_BASE_KEY}${syncState.owner.storageSuffix}`;
/**
* The revision map survives reloads so that, while offline, we can still tell
@@ -202,6 +216,8 @@ const getSyncMapStorageKey = (): string => `${SYNC_MAP_BASE_KEY}${getUserStorage
* (push it)".
*/
const persistSyncMap = (syncState: SyncedPersistenceState): void => {
+ assertOwner(syncState);
+
try {
const revisions: Record<string, number> = {};
@@ -209,15 +225,17 @@ const persistSyncMap = (syncState: SyncedPersistenceState): void => {
revisions[projectId] = entry.revision;
}
- window.localStorage.setItem(getSyncMapStorageKey(), JSON.stringify({ revisions }));
+ window.localStorage.setItem(getSyncMapStorageKey(syncState), JSON.stringify({ revisions }));
} catch {
// Cache only; sync still works for this session.
}
};
-const loadPersistedRevisions = (): Record<string, number> => {
+const loadPersistedRevisions = (syncState: SyncedPersistenceState): Record<string, number> => {
+ assertOwner(syncState);
+
try {
- const raw = window.localStorage.getItem(getSyncMapStorageKey());
+ const raw = window.localStorage.getItem(getSyncMapStorageKey(syncState));
const parsed = raw ? (JSON.parse(raw) as { revisions?: Record<string, number> }) : null;
return parsed?.revisions ?? {};
@@ -234,21 +252,29 @@ const createSnapshot = (state: WorkbenchState): HydratedWorkbenchSnapshot => ({
/** Import a never-synced project to the server; returns false when it could not reach it. */
const pushNewProject = async (syncState: SyncedPersistenceState, project: Project): Promise<boolean> => {
+ assertOwner(syncState);
const document = serializeProjectDocument(project);
try {
- const created = await apiCreateProject({ data: document, name: project.name, project_id: project.id });
+ const created = await apiCreateProject(
+ { data: document, name: project.name, project_id: project.id },
+ syncState.owner.signal
+ );
+ assertOwner(syncState);
syncState.syncEntries.set(project.id, { pushedDoc: JSON.stringify(document), revision: created.revision });
return true;
} catch (error) {
+ assertOwner(syncState);
+
if (isProjectConflictError(error)) {
// The id already exists server-side (e.g. a previous import raced a
// reload). Adopt the server revision; the regular save path will PUT.
try {
- const existing = await apiGetProject(project.id);
+ const existing = await apiGetProject(project.id, syncState.owner.signal);
+ assertOwner(syncState);
syncState.syncEntries.set(project.id, {
pushedDoc: JSON.stringify(existing.data),
revision: existing.revision,
@@ -256,6 +282,8 @@ const pushNewProject = async (syncState: SyncedPersistenceState, project: Projec
return true;
} catch {
+ assertOwner(syncState);
+
return false;
}
}
@@ -317,8 +345,12 @@ const recoverConflictingProject = async (
documentJson: string,
basePushedDoc: string | null
): Promise<ConflictOutcome> => {
+ assertOwner(syncState);
+
try {
- const server = await apiGetProject(project.id);
+ const server = await apiGetProject(project.id, syncState.owner.signal);
+
+ assertOwner(syncState);
const serverDocJson = JSON.stringify(server.data);
syncState.syncEntries.set(project.id, { pushedDoc: serverDocJson, revision: server.revision });
@@ -344,8 +376,12 @@ const recoverConflictingProject = async (
return { kind: 'failed' };
}
- const created = await apiCreateProject({ data: recoveredDocument, name: recoveredName, project_id: recoveredId });
+ const created = await apiCreateProject(
+ { data: recoveredDocument, name: recoveredName, project_id: recoveredId },
+ syncState.owner.signal
+ );
+ assertOwner(syncState);
syncState.syncEntries.set(recoveredId, {
pushedDoc: JSON.stringify(recoveredDocument),
revision: created.revision,
@@ -353,6 +389,8 @@ const recoverConflictingProject = async (
return { kind: 'forked', resolution: { projectId: project.id, recoveredProject, serverProject } };
} catch {
+ assertOwner(syncState);
+
return { kind: 'failed' };
}
};
@@ -362,6 +400,7 @@ const pushProject = async (
project: Project,
conflicts: ProjectConflictResolution[]
): Promise<string> => {
+ assertOwner(syncState);
const { document, json: documentJson } = getSerializedProjectDocument(syncState, project);
const entry = syncState.syncEntries.get(project.id);
@@ -371,35 +410,51 @@ const pushProject = async (
if (!entry) {
if (!(await pushNewProject(syncState, project))) {
+ assertOwner(syncState);
syncState.hasPending = true;
}
+ assertOwner(syncState);
return documentJson;
}
try {
- const updated = await apiUpdateProject(project.id, {
- data: document,
- expected_revision: entry.revision,
- name: project.name,
- });
+ const updated = await apiUpdateProject(
+ project.id,
+ {
+ data: document,
+ expected_revision: entry.revision,
+ name: project.name,
+ },
+ syncState.owner.signal
+ );
+ assertOwner(syncState);
syncState.syncEntries.set(project.id, { pushedDoc: documentJson, revision: updated.revision });
} catch (error) {
+ assertOwner(syncState);
+
if (isProjectConflictError(error)) {
const outcome = await recoverConflictingProject(syncState, project, document, documentJson, entry.pushedDoc);
+ assertOwner(syncState);
if (outcome.kind === 'retry') {
try {
const baseRevision = syncState.syncEntries.get(project.id)?.revision ?? entry.revision;
- const retried = await apiUpdateProject(project.id, {
- data: document,
- expected_revision: baseRevision,
- name: project.name,
- });
-
+ const retried = await apiUpdateProject(
+ project.id,
+ {
+ data: document,
+ expected_revision: baseRevision,
+ name: project.name,
+ },
+ syncState.owner.signal
+ );
+
+ assertOwner(syncState);
syncState.syncEntries.set(project.id, { pushedDoc: documentJson, revision: retried.revision });
} catch {
+ assertOwner(syncState);
// A genuinely concurrent writer; the next save re-evaluates.
syncState.hasPending = true;
}
@@ -414,6 +469,7 @@ const pushProject = async (
syncState.syncEntries.delete(project.id);
if (!(await pushNewProject(syncState, project))) {
+ assertOwner(syncState);
syncState.hasPending = true;
}
} else {
@@ -421,10 +477,12 @@ const pushProject = async (
}
}
+ assertOwner(syncState);
return documentJson;
};
const pushSessionState = async (syncState: SyncedPersistenceState, state: WorkbenchState): Promise<void> => {
+ assertOwner(syncState);
const blob = serializeSessionBlob(state);
if (blob === syncState.lastPushedAccount) {
@@ -432,9 +490,12 @@ const pushSessionState = async (syncState: SyncedPersistenceState, state: Workbe
}
try {
- await setClientStateValue(SESSION_STATE_KEY, blob);
+ await setClientStateValue(SESSION_STATE_KEY, blob, syncState.owner.signal);
+
+ assertOwner(syncState);
syncState.lastPushedAccount = blob;
} catch {
+ assertOwner(syncState);
syncState.hasPending = true;
}
};
@@ -444,25 +505,34 @@ const loadFromBackend = async (
local: HydratedWorkbenchSnapshot | null,
options?: WorkbenchLoadOptions
): Promise<HydratedWorkbenchSnapshot> => {
- const [summaries, sessionBlob] = await Promise.all([listProjects(), fetchSessionBlob()]);
- const persistedRevisions = loadPersistedRevisions();
+ assertOwner(syncState);
+ const [summaries, sessionBlob] = await Promise.all([
+ listProjects(syncState.owner.signal),
+ fetchSessionBlob(syncState.owner.signal),
+ ]);
- seedProjectLibrary(summaries);
+ assertOwner(syncState);
+ const persistedRevisions = loadPersistedRevisions(syncState);
+
+ seedProjectLibrary(summaries, syncState.owner);
// First contact: a backend with no projects adopts the browser's existing
// workbench (one-time import of the pre-backend localStorage data).
if (summaries.length === 0 && local && local.state.projects.length > 0) {
for (const project of local.state.projects) {
if (!(await pushNewProject(syncState, project))) {
+ assertOwner(syncState);
syncState.hasPending = true;
}
+ assertOwner(syncState);
const entry = syncState.syncEntries.get(project.id);
- upsertProjectSummary({ id: project.id, name: project.name, revision: entry?.revision ?? null });
+ upsertProjectSummary({ id: project.id, name: project.name, revision: entry?.revision ?? null }, syncState.owner);
}
await pushSessionState(syncState, local.state);
+ assertOwner(syncState);
persistSyncMap(syncState);
return local;
@@ -485,7 +555,17 @@ const loadFromBackend = async (
// Only the open set is hydrated into full documents; everything else stays
// a summary in the library. A project deleted between list and get is
// simply dropped from the session.
- const records = await Promise.all(openIds.map((id) => apiGetProject(id).catch(() => null)));
+ const records = await Promise.all(
+ openIds.map((id) =>
+ apiGetProject(id, syncState.owner.signal).catch(() => {
+ assertOwner(syncState);
+
+ return null;
+ })
+ )
+ );
+
+ assertOwner(syncState);
const serverProjects: Project[] = [];
for (const record of records) {
@@ -572,7 +652,8 @@ const loadFromBackend = async (
const snapshot = createSnapshot(state);
// Refresh the offline cache with what the server gave us.
- await localStorageWorkbenchPersistence.saveWorkbench(state);
+ await syncState.localPersistence.saveWorkbench(state);
+ assertOwner(syncState);
return snapshot;
};
@@ -597,39 +678,55 @@ export interface SyncedWorkbenchPersistence {
* Independent of any mounted Workbench lifetime; callers are expected to
* reload afterwards.
*/
-export const clearAllWorkbenchData = async (): Promise<void> => {
+export const clearAllWorkbenchData = async (owner: AccountScope = captureAccountScope()): Promise<void> => {
+ const syncState = createSyncedPersistenceState(owner);
+
+ assertOwner(syncState);
+
try {
- const summaries = await listProjects();
+ const summaries = await listProjects(syncState.owner.signal);
- await Promise.all(summaries.map((summary) => apiDeleteProject(summary.project_id)));
- await deleteClientStateValue(SESSION_STATE_KEY);
+ assertOwner(syncState);
+ await Promise.all(summaries.map((summary) => apiDeleteProject(summary.project_id, syncState.owner.signal)));
+ assertOwner(syncState);
+ await deleteClientStateValue(SESSION_STATE_KEY, syncState.owner.signal);
+ assertOwner(syncState);
} catch {
+ assertOwner(syncState);
// Backend unreachable; at least reset this browser.
}
- seedProjectLibrary([]);
+ seedProjectLibrary([], owner);
try {
- window.localStorage.removeItem(getSyncMapStorageKey());
+ window.localStorage.removeItem(getSyncMapStorageKey(syncState));
} catch {
// Nothing to clear if storage is unavailable.
}
- await localStorageWorkbenchPersistence.clearWorkbench();
+ await syncState.localPersistence.clearWorkbench();
+ assertOwner(syncState);
};
/** Construct one synchronization lifetime per mounted Workbench. */
-export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence => {
- const syncState = createSyncedPersistenceState();
+export const createSyncedWorkbenchPersistence = (
+ owner: AccountScope = captureAccountScope()
+): SyncedWorkbenchPersistence => {
+ const syncState = createSyncedPersistenceState(owner);
let loadPromise: Promise<HydratedWorkbenchSnapshot | null> | null = null;
// Every mutation below shares syncEntries and its optimistic revisions.
// Serialize them so this browser cannot race itself and manufacture a 409.
let mutationTail: Promise<void> = Promise.resolve();
const enqueueMutation = <Result>(operation: () => Promise<Result>): Promise<Result> => {
+ const run = (): Promise<Result> => {
+ assertOwner(syncState);
+
+ return operation();
+ };
const result = mutationTail.then(
- () => operation(),
- () => operation()
+ () => run(),
+ () => run()
);
mutationTail = result.then(
@@ -641,6 +738,7 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
};
const adoptProjectRecord = (record: ProjectRecordDTO): Project | null => {
+ assertOwner(syncState);
const project = deserializeProjectDocument(record.data);
if (!project) {
@@ -661,8 +759,9 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
/** Clear everywhere: server projects + session blob, local cache, sync map, and this lifetime's sync state. */
clearWorkbench(): Promise<void> {
return enqueueMutation(async () => {
- await clearAllWorkbenchData();
+ await clearAllWorkbenchData(syncState.owner);
+ assertOwner(syncState);
syncState.syncEntries.clear();
syncState.deletedProjectIds.clear();
syncState.lastPushedAccount = null;
@@ -674,16 +773,25 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
const conflicts: ProjectConflictResolution[] = [];
await pushProject(syncState, project, conflicts);
+ assertOwner(syncState);
persistSyncMap(syncState);
});
},
hasPendingChanges(): boolean {
+ assertOwner(syncState);
return syncState.hasPending;
},
async hydrateProjectFromServer(projectId): Promise<Project | null> {
+ assertOwner(syncState);
+
try {
- return adoptProjectRecord(await apiGetProject(projectId));
+ const record = await apiGetProject(projectId, syncState.owner.signal);
+
+ assertOwner(syncState);
+ return adoptProjectRecord(record);
} catch {
+ assertOwner(syncState);
+
return null;
}
},
@@ -701,22 +809,26 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
}
loadPromise = (async () => {
+ assertOwner(syncState);
let local: HydratedWorkbenchSnapshot | null = null;
try {
- local = await localStorageWorkbenchPersistence.loadWorkbench();
+ local = await syncState.localPersistence.loadWorkbench();
+ assertOwner(syncState);
} catch {
+ assertOwner(syncState);
local = null;
}
try {
return await loadFromBackend(syncState, local, options);
} catch {
+ assertOwner(syncState);
// Backend unreachable: run from the cache; saves queue up locally and
// replay on reconnect.
syncState.hasPending = true;
- const persistedRevisions = loadPersistedRevisions();
+ const persistedRevisions = loadPersistedRevisions(syncState);
for (const [projectId, revision] of Object.entries(persistedRevisions)) {
syncState.syncEntries.set(projectId, { pushedDoc: null, revision });
@@ -749,6 +861,7 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
* and removal happens only through the library's explicit delete.
*/
markProjectDeleted(projectId): void {
+ assertOwner(syncState);
syncState.deletedProjectIds.add(projectId);
syncState.syncEntries.delete(projectId);
persistSyncMap(syncState);
@@ -757,19 +870,23 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
return enqueueMutation(async () => {
const emptied: WorkbenchState = { ...state, activeProjectId: '', projects: [] };
- await localStorageWorkbenchPersistence.saveWorkbench(emptied);
+ await syncState.localPersistence.saveWorkbench(emptied);
+ assertOwner(syncState);
try {
const blob = serializeSessionBlob(emptied);
- await setClientStateValue(SESSION_STATE_KEY, blob);
+ await setClientStateValue(SESSION_STATE_KEY, blob, syncState.owner.signal);
+ assertOwner(syncState);
syncState.lastPushedAccount = blob;
} catch {
+ assertOwner(syncState);
syncState.hasPending = true;
}
});
},
releaseProjectSync(projectId): void {
+ assertOwner(syncState);
syncState.syncEntries.delete(projectId);
persistSyncMap(syncState);
},
@@ -777,18 +894,23 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
return enqueueMutation(async () => {
const snapshot = createSnapshot(state);
- await localStorageWorkbenchPersistence.saveWorkbench(state);
+ await syncState.localPersistence.saveWorkbench(state);
+ assertOwner(syncState);
syncState.hasPending = false;
const conflicts: ProjectConflictResolution[] = [];
const projectSyncInfos: Record<string, ProjectSyncInfo> = {};
await pushSessionState(syncState, state);
+ assertOwner(syncState);
for (const project of state.projects) {
+ assertOwner(syncState);
const lastAckedDoc = syncState.syncEntries.get(project.id)?.pushedDoc ?? null;
const documentJson = await pushProject(syncState, project, conflicts);
+
+ assertOwner(syncState);
const entry = syncState.syncEntries.get(project.id);
projectSyncInfos[project.id] = {
@@ -799,7 +921,7 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
// The server acknowledged new content for this project — keep the
// library summary current without a refetch.
if (entry && entry.pushedDoc === documentJson && lastAckedDoc !== documentJson) {
- upsertProjectSummary({ id: project.id, name: project.name, revision: entry.revision });
+ upsertProjectSummary({ id: project.id, name: project.name, revision: entry.revision }, syncState.owner);
}
}
@@ -810,6 +932,7 @@ export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence =
});
},
unmarkProjectDeleted(projectId): void {
+ assertOwner(syncState);
syncState.deletedProjectIds.delete(projectId);
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
index 13b9f05c4c..851849f7b2 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
@@ -1,5 +1,6 @@
import type { SettingsSectionId } from '@workbench/widgetContracts';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -14,9 +15,18 @@ interface SettingsDialogSnapshot {
sectionId: SettingsSectionId;
}
-export const settingsDialogStore = createExternalStore<SettingsDialogSnapshot>({
+const INITIAL_SETTINGS_DIALOG_SNAPSHOT: SettingsDialogSnapshot = {
isOpen: false,
sectionId: 'appearance',
+};
+
+export const settingsDialogStore = createExternalStore<SettingsDialogSnapshot>(INITIAL_SETTINGS_DIALOG_SNAPSHOT);
+
+registerAccountOwnedResource({
+ clear: () => {
+ settingsDialogStore.setSnapshot(INITIAL_SETTINGS_DIALOG_SNAPSHOT);
+ },
+ name: 'settings-dialog',
});
/** Open the workbench settings dialog, optionally at a specific section. */
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
index 3619e2a33a..90fee9da74 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
@@ -1,3 +1,5 @@
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as storeModule from './store';
@@ -50,6 +52,7 @@ const SETTINGS_KEY = 'webv2:workbench-settings';
const SESSION_KEY = 'webv2:workbench-account';
let store: typeof storeModule;
+let account: typeof accountLifecycleModule;
const seedBackendPreferences = (preferences: Record<string, unknown>): void => {
api.__clientState.set(SETTINGS_KEY, JSON.stringify(preferences));
@@ -61,13 +64,25 @@ const readBackendPreferences = (): Record<string, unknown> =>
beforeEach(async () => {
vi.resetModules();
api.__clientState.clear();
- api.deleteClientStateValue.mockClear();
- api.getClientStateValue.mockClear();
- api.setClientStateValue.mockClear();
+ api.deleteClientStateValue.mockReset();
+ api.deleteClientStateValue.mockImplementation((key: string) => {
+ api.__clientState.delete(key);
+
+ return Promise.resolve();
+ });
+ api.getClientStateValue.mockReset();
+ api.getClientStateValue.mockImplementation((key: string) => Promise.resolve(api.__clientState.get(key) ?? null));
+ api.setClientStateValue.mockReset();
+ api.setClientStateValue.mockImplementation((key: string, value: string) => {
+ api.__clientState.set(key, value);
+
+ return Promise.resolve();
+ });
auth.scope = '';
storage.clear();
store = await import('./store');
+ account = await import('@platform/state/accountLifecycle');
});
describe('loadWorkbenchSettings', () => {
@@ -147,6 +162,28 @@ describe('loadWorkbenchSettings', () => {
expect(preferences.themeId).toBe('classic');
});
+
+ it('does not share a same-user single-flight or publish a prior epoch response', async () => {
+ account.accountLifecycle.activate('user-a', ':user:a');
+ let resolveOld: ((value: string | null) => void) | undefined;
+ api.getClientStateValue
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve;
+ })
+ )
+ .mockResolvedValueOnce(JSON.stringify({ themeId: 'light' }));
+ const oldLoad = store.loadWorkbenchSettings();
+
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-a', ':user:a');
+ await expect(store.loadWorkbenchSettings()).resolves.toMatchObject({ themeId: 'light' });
+
+ resolveOld?.(JSON.stringify({ themeId: 'forest' }));
+ await expect(oldLoad).rejects.toThrow('no longer active');
+ expect(store.getWorkbenchPreferences().themeId).toBe('light');
+ });
});
describe('patchWorkbenchPreferences', () => {
@@ -198,6 +235,57 @@ describe('patchWorkbenchPreferences', () => {
expect(preferences.themeId).toBe('light');
expect(readBackendPreferences().themeId).toBe('light');
});
+
+ it('serializes writes so an older completion cannot overwrite a newer preference snapshot', async () => {
+ await store.loadWorkbenchSettings();
+ api.setClientStateValue.mockClear();
+ let resolveFirstWrite: (() => void) | undefined;
+ api.setClientStateValue.mockImplementationOnce(
+ (key: string, value: string) =>
+ new Promise<void>((resolve) => {
+ resolveFirstWrite = () => {
+ api.__clientState.set(key, value);
+ resolve();
+ };
+ })
+ );
+
+ const first = store.patchWorkbenchPreferences({ themeId: 'forest' });
+ const second = store.patchWorkbenchPreferences({ themeId: 'light' });
+
+ await vi.waitFor(() => {
+ expect(api.setClientStateValue).toHaveBeenCalledTimes(1);
+ });
+ resolveFirstWrite?.();
+ await Promise.all([first, second]);
+
+ expect(readBackendPreferences().themeId).toBe('light');
+ expect(store.getWorkbenchPreferences().themeId).toBe('light');
+ });
+
+ it('settles without publishing an error when its account expires during a write', async () => {
+ account.accountLifecycle.activate('user-a', ':user:a');
+ await store.loadWorkbenchSettings();
+ api.setClientStateValue.mockClear();
+ let resolveWrite: (() => void) | undefined;
+ api.setClientStateValue.mockImplementationOnce(
+ (key: string, value: string) =>
+ new Promise<void>((resolve) => {
+ resolveWrite = () => {
+ api.__clientState.set(key, value);
+ resolve();
+ };
+ })
+ );
+
+ const write = store.patchWorkbenchPreferences({ themeId: 'forest' });
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b', ':user:b');
+ resolveWrite?.();
+
+ await expect(write).resolves.toBeUndefined();
+ expect(store.getWorkbenchPreferences().themeId).toBe('classic');
+ });
});
describe('clearWorkbenchSettings', () => {
@@ -210,6 +298,36 @@ describe('clearWorkbenchSettings', () => {
expect(store.getWorkbenchPreferences().themeId).toBe('classic');
expect(api.__clientState.has(SETTINGS_KEY)).toBe(false);
});
+
+ it('orders reset after an in-flight patch so the older write cannot restore backend or local settings', async () => {
+ await store.loadWorkbenchSettings();
+ api.setClientStateValue.mockClear();
+ api.deleteClientStateValue.mockClear();
+ let resolvePatch: (() => void) | undefined;
+ api.setClientStateValue.mockImplementationOnce(
+ (key: string, value: string) =>
+ new Promise<void>((resolve) => {
+ resolvePatch = () => {
+ api.__clientState.set(key, value);
+ resolve();
+ };
+ })
+ );
+
+ const patch = store.patchWorkbenchPreferences({ themeId: 'forest' });
+ const clear = store.clearWorkbenchSettings();
+
+ await vi.waitFor(() => {
+ expect(api.setClientStateValue).toHaveBeenCalledTimes(1);
+ });
+ expect(api.deleteClientStateValue).not.toHaveBeenCalled();
+ resolvePatch?.();
+ await Promise.all([patch, clear]);
+
+ expect(api.__clientState.has(SETTINGS_KEY)).toBe(false);
+ expect(storage.has('invokeai:v7:webv2:settings')).toBe(false);
+ expect(store.getWorkbenchPreferences().themeId).toBe('classic');
+ });
});
describe('normalizeProjectSettings', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.ts
index 69d4f40bf5..5667b666f5 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts
@@ -3,6 +3,13 @@ import type { ProjectSettings, WorkbenchPreferences } from '@workbench/settings/
import { getUserStorageScope } from '@features/identity';
import { normalizeWorkbenchLanguage } from '@platform/i18n/languages';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
import { createSingleFlight } from '@platform/state/singleFlight';
import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '@theme/themes';
@@ -72,20 +79,40 @@ interface WorkbenchSettingsSnapshot {
error?: string;
}
-const store = createExternalStore<WorkbenchSettingsSnapshot>({
+const INITIAL_SETTINGS_SNAPSHOT: WorkbenchSettingsSnapshot = {
hydratedStorageKey: null,
preferences: DEFAULT_PREFERENCES,
scope: 'global',
status: 'idle',
+};
+const store = createExternalStore<WorkbenchSettingsSnapshot>(INITIAL_SETTINGS_SNAPSHOT);
+
+interface SettingsMutationQueue {
+ latestRevision: number;
+ owner: AccountScope;
+ tail: Promise<void>;
+}
+
+let settingsMutationQueue: SettingsMutationQueue | null = null;
+
+registerAccountOwnedResource({
+ clear: () => {
+ settingsMutationQueue = null;
+ store.setSnapshot(INITIAL_SETTINGS_SNAPSHOT);
+ },
+ name: 'workbench-settings',
});
const isBrowser = (): boolean => typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
-const getSettingsStorageKey = (): string => `${SETTINGS_BASE_STORAGE_KEY}${getUserStorageScope()}`;
+const getSettingsStorageKey = (storageSuffix = getUserStorageScope()): string =>
+ `${SETTINGS_BASE_STORAGE_KEY}${storageSuffix}`;
-const getLegacyWorkbenchStorageKey = (): string => `${LEGACY_WORKBENCH_BASE_STORAGE_KEY}${getUserStorageScope()}`;
+const getLegacyWorkbenchStorageKey = (storageSuffix = getUserStorageScope()): string =>
+ `${LEGACY_WORKBENCH_BASE_STORAGE_KEY}${storageSuffix}`;
-const getSettingsScope = (): WorkbenchSettingsSnapshot['scope'] => (getUserStorageScope() ? 'user' : 'global');
+const getSettingsScope = (storageSuffix = getUserStorageScope()): WorkbenchSettingsSnapshot['scope'] =>
+ storageSuffix ? 'user' : 'global';
const isDeveloperLogLevel = (value: unknown): value is DeveloperLogLevel =>
typeof value === 'string' && DEVELOPER_LOG_LEVELS.includes(value as DeveloperLogLevel);
@@ -250,13 +277,13 @@ interface StoredSettings {
pendingPush?: boolean;
}
-const readLocalSettings = (): StoredSettings | null => {
+const readLocalSettings = (storageKey: string): StoredSettings | null => {
if (!isBrowser()) {
return null;
}
try {
- const parsed = JSON.parse(window.localStorage.getItem(getSettingsStorageKey()) ?? 'null') as
+ const parsed = JSON.parse(window.localStorage.getItem(storageKey) ?? 'null') as
| (Partial<StoredSettings> & Partial<WorkbenchPreferences>)
| null;
@@ -278,31 +305,31 @@ const readLocalSettings = (): StoredSettings | null => {
}
};
-const writeLocalSettings = (preferences: WorkbenchPreferences, pendingPush?: boolean): void => {
+const writeLocalSettings = (storageKey: string, preferences: WorkbenchPreferences, pendingPush?: boolean): void => {
if (!isBrowser()) {
return;
}
const payload: StoredSettings = pendingPush ? { pendingPush, preferences } : { preferences };
- window.localStorage.setItem(getSettingsStorageKey(), JSON.stringify(payload));
+ window.localStorage.setItem(storageKey, JSON.stringify(payload));
};
-const removeLocalSettings = (): void => {
+const removeLocalSettings = (storageKey: string): void => {
if (!isBrowser()) {
return;
}
- window.localStorage.removeItem(getSettingsStorageKey());
+ window.localStorage.removeItem(storageKey);
};
-const readLegacyLocalPreferences = (): WorkbenchPreferences | null => {
+const readLegacyLocalPreferences = (storageSuffix: string): WorkbenchPreferences | null => {
if (!isBrowser()) {
return null;
}
try {
- const raw = window.localStorage.getItem(getLegacyWorkbenchStorageKey());
+ const raw = window.localStorage.getItem(getLegacyWorkbenchStorageKey(storageSuffix));
const parsed = raw ? (JSON.parse(raw) as { state?: { account?: { preferences?: unknown } } }) : null;
return parsed?.state?.account?.preferences
@@ -313,31 +340,64 @@ const readLegacyLocalPreferences = (): WorkbenchPreferences | null => {
}
};
-const loadLegacySessionPreferences = async (): Promise<WorkbenchPreferences | null> => {
- const blob = await fetchSessionBlob();
+const loadLegacySessionPreferences = async (owner: AccountScope): Promise<WorkbenchPreferences | null> => {
+ const blob = await fetchSessionBlob(owner.signal);
+ assertAccountScopeCurrent(owner);
return blob?.account.preferences ? normalizeWorkbenchPreferences(blob.account.preferences) : null;
};
const replaceSnapshot = (
preferences: WorkbenchPreferences,
status: WorkbenchSettingsSnapshot['status'],
- hydratedStorageKey: string | null = store.getSnapshot().hydratedStorageKey
+ hydratedStorageKey: string | null = store.getSnapshot().hydratedStorageKey,
+ storageSuffix = getUserStorageScope()
): void => {
- store.setSnapshot({ hydratedStorageKey, preferences, scope: getSettingsScope(), status });
+ store.setSnapshot({ hydratedStorageKey, preferences, scope: getSettingsScope(storageSuffix), status });
+};
+
+const pushPreferences = (preferences: WorkbenchPreferences, signal: AbortSignal): Promise<void> =>
+ setClientStateValue(SETTINGS_CLIENT_STATE_KEY, JSON.stringify(preferences), signal);
+
+const getSettingsMutationQueue = (owner: AccountScope): SettingsMutationQueue => {
+ if (settingsMutationQueue?.owner === owner) {
+ return settingsMutationQueue;
+ }
+
+ settingsMutationQueue = { latestRevision: 0, owner, tail: Promise.resolve() };
+
+ return settingsMutationQueue;
};
-const pushPreferences = (preferences: WorkbenchPreferences): Promise<void> =>
- setClientStateValue(SETTINGS_CLIENT_STATE_KEY, JSON.stringify(preferences));
+const enqueueSettingsMutation = (
+ owner: AccountScope,
+ operation: (queue: SettingsMutationQueue, revision: number) => Promise<void>
+): Promise<void> => {
+ const queue = getSettingsMutationQueue(owner);
+ const revision = (queue.latestRevision += 1);
+ const run = (): Promise<void> => operation(queue, revision);
+ const result = queue.tail.then(run, run);
+
+ queue.tail = result.catch(() => undefined);
+
+ return result;
+};
-const resolveSettings = async (local: StoredSettings | null): Promise<WorkbenchPreferences> => {
+const resolveSettings = async (
+ local: StoredSettings | null,
+ owner: AccountScope,
+ storageSuffix: string
+): Promise<WorkbenchPreferences> => {
if (local?.pendingPush) {
- await pushPreferences(local.preferences);
+ await pushPreferences(local.preferences, owner.signal);
+ assertAccountScopeCurrent(owner);
return local.preferences;
}
- const backendPreferences = parsePreferences(await getClientStateValue(SETTINGS_CLIENT_STATE_KEY));
+ const backendPreferences = parsePreferences(await getClientStateValue(SETTINGS_CLIENT_STATE_KEY, owner.signal));
+
+ assertAccountScopeCurrent(owner);
if (backendPreferences) {
return backendPreferences;
@@ -346,12 +406,13 @@ const resolveSettings = async (local: StoredSettings | null): Promise<WorkbenchP
// First contact for this account: adopt whatever the legacy locations
// hold and write the new backend key once.
const preferences =
- (await loadLegacySessionPreferences()) ??
+ (await loadLegacySessionPreferences(owner)) ??
local?.preferences ??
- readLegacyLocalPreferences() ??
+ readLegacyLocalPreferences(storageSuffix) ??
normalizeWorkbenchPreferences();
- await pushPreferences(preferences);
+ await pushPreferences(preferences, owner.signal);
+ assertAccountScopeCurrent(owner);
return preferences;
};
@@ -364,33 +425,40 @@ const settingsLoad = createSingleFlight<WorkbenchPreferences>();
* and the next load retries the backend.
*/
export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {
- const storageKey = getSettingsStorageKey();
+ const owner = captureAccountScope();
+ const storageSuffix = owner.accountId === null ? getUserStorageScope() : owner.storageSuffix;
+ const storageKey = getSettingsStorageKey(storageSuffix);
if (store.getSnapshot().hydratedStorageKey === storageKey) {
return Promise.resolve(getWorkbenchPreferences());
}
- return settingsLoad.run(storageKey, async () => {
- store.patchSnapshot({ scope: getSettingsScope(), status: 'loading' });
- const local = readLocalSettings();
+ return settingsLoad.run(`${storageKey}:${owner.epoch}`, async () => {
+ store.patchSnapshot({ scope: getSettingsScope(storageSuffix), status: 'loading' });
+ const local = readLocalSettings(storageKey);
try {
- const preferences = await resolveSettings(local);
+ const preferences = await resolveSettings(local, owner, storageSuffix);
- writeLocalSettings(preferences);
- replaceSnapshot(preferences, 'ready', storageKey);
+ assertAccountScopeCurrent(owner);
+ writeLocalSettings(storageKey, preferences);
+ replaceSnapshot(preferences, 'ready', storageKey, storageSuffix);
return preferences;
} catch (error) {
- const fallback = local?.preferences ?? readLegacyLocalPreferences();
+ if (!isAccountScopeCurrent(owner)) {
+ throw error;
+ }
+
+ const fallback = local?.preferences ?? readLegacyLocalPreferences(storageSuffix);
const preferences = fallback ?? normalizeWorkbenchPreferences();
- writeLocalSettings(preferences, local?.pendingPush);
+ writeLocalSettings(storageKey, preferences, local?.pendingPush);
store.setSnapshot({
error: error instanceof Error ? error.message : 'Failed to load settings from the backend.',
hydratedStorageKey: null,
preferences,
- scope: getSettingsScope(),
+ scope: getSettingsScope(storageSuffix),
status: fallback ? 'ready' : 'error',
});
@@ -431,29 +499,58 @@ export const useWorkbenchReduceMotion = (): boolean =>
store.useSelector((snapshot) => snapshot.preferences.reduceMotion);
export const patchWorkbenchPreferences = async (preferences: Partial<WorkbenchPreferences>): Promise<void> => {
+ const owner = captureAccountScope();
+ const storageSuffix = owner.accountId === null ? getUserStorageScope() : owner.storageSuffix;
+ const storageKey = getSettingsStorageKey(storageSuffix);
const next = normalizeWorkbenchPreferences({ ...store.getSnapshot().preferences, ...preferences });
- replaceSnapshot(next, 'ready');
- writeLocalSettings(next, true);
+ replaceSnapshot(next, 'ready', store.getSnapshot().hydratedStorageKey, storageSuffix);
+ writeLocalSettings(storageKey, next, true);
- try {
- await pushPreferences(next);
- writeLocalSettings(next);
- } catch (error) {
- store.patchSnapshot({
- error: error instanceof Error ? error.message : 'Failed to save settings.',
- status: 'error',
- });
- }
+ await enqueueSettingsMutation(owner, async (queue, revision) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ try {
+ await pushPreferences(next, owner.signal);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ if (queue.latestRevision === revision) {
+ writeLocalSettings(storageKey, next);
+ }
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner) || queue.latestRevision !== revision) {
+ return;
+ }
+
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to save settings.',
+ status: 'error',
+ });
+ }
+ });
};
export const clearWorkbenchSettings = async (): Promise<void> => {
- removeLocalSettings();
- replaceSnapshot(normalizeWorkbenchPreferences(), 'ready', getSettingsStorageKey());
+ const owner = captureAccountScope();
+ const storageSuffix = owner.accountId === null ? getUserStorageScope() : owner.storageSuffix;
+ const storageKey = getSettingsStorageKey(storageSuffix);
- try {
- await deleteClientStateValue(SETTINGS_CLIENT_STATE_KEY);
- } catch {
- // Backend persistence is best-effort; the local reset should still complete.
- }
+ removeLocalSettings(storageKey);
+ replaceSnapshot(normalizeWorkbenchPreferences(), 'ready', storageKey, storageSuffix);
+
+ await enqueueSettingsMutation(owner, async () => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ try {
+ await deleteClientStateValue(SETTINGS_CLIENT_STATE_KEY, owner.signal);
+ } catch {
+ // Backend persistence is best-effort; the local reset should still complete.
+ }
+ });
};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
index 3344c07909..1ab8aba4e8 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
@@ -6,6 +6,11 @@ import { sanitizeBatchCount } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useInvocationTemplatesSelector } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, IconButton, Tooltip } from '@platform/ui';
import {
formatRoute,
@@ -133,32 +138,45 @@ export const InvokeControl = () => {
});
const onInvoke = useCallback(async () => {
+ const owner = captureAccountScope();
flushGenerateDrafts();
- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
- const snapshot = queries.getSnapshot();
- const postFlushRoute = resolveInvocationRoute(
- snapshot.activeProject,
- 'global',
- snapshot.activeProject.invocation,
- availabilityModels
- );
- if (!isInvocationRouteValid(postFlushRoute) || snapshot.backendConnection.status !== 'connected') {
- return;
- }
+ try {
+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
+
+ assertAccountScopeCurrent(owner);
+ const snapshot = queries.getSnapshot();
+ const postFlushRoute = resolveInvocationRoute(
+ snapshot.activeProject,
+ 'global',
+ snapshot.activeProject.invocation,
+ availabilityModels
+ );
- submitResolvedInvocation({
- commands,
- formatControlLayerError: (code, layerName) =>
- t('widgets.layers.control.invalidLayer', {
- name: layerName,
- reason: t(`widgets.layers.control.validation.${code}`),
- }),
- models: availabilityModels,
- prepareCanvasInvocation,
- project: snapshot.activeProject,
- route: postFlushRoute,
- });
+ if (!isInvocationRouteValid(postFlushRoute) || snapshot.backendConnection.status !== 'connected') {
+ return;
+ }
+
+ submitResolvedInvocation({
+ commands,
+ formatControlLayerError: (code, layerName) =>
+ t('widgets.layers.control.invalidLayer', {
+ name: layerName,
+ reason: t(`widgets.layers.control.validation.${code}`),
+ }),
+ models: availabilityModels,
+ owner,
+ prepareCanvasInvocation,
+ project: snapshot.activeProject,
+ route: postFlushRoute,
+ });
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ throw error;
+ }
}, [availabilityModels, commands, queries, t]);
const tooltipContent = useMemo(
() => (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index b8fe335873..a26b1f2763 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -524,6 +524,21 @@ describe('runCanvasInvocation', () => {
expect(harness.submittedGraphs()).toHaveLength(0);
});
+ it('quietly stops when its account signal expires during composition', async () => {
+ const harness = makeHarness();
+ const controller = new AbortController();
+ harness.deps.signal = controller.signal;
+ harness.deps.composeForGeneration = () => {
+ controller.abort(new DOMException('account changed', 'AbortError'));
+ return Promise.reject(controller.signal.reason);
+ };
+
+ await runCanvasInvocation(harness.deps);
+
+ expect(harness.submittedGraphs()).toHaveLength(0);
+ expect(harness.notices()).toHaveLength(0);
+ });
+
it('uses the frozen canvas and detached pixels after edits at composite, upload, and queue-dispatch boundaries', async () => {
let liveDocument = makeDoc([rasterLayer('frozen-layer')], 96);
liveDocument.bbox = { height: 64, width: 64, x: 7, y: 11 };
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index b929c3f146..5f71f0137e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -57,6 +57,12 @@ import {
resolveGenerateSeed,
} from '@features/generation/graph';
import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@features/generation/settings';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
import { getCanvasEngine, getCanvasOperations } from '@workbench/canvas-operations/api';
import {
DEFAULT_CANVAS_COMPOSITING,
@@ -98,6 +104,8 @@ export interface RunCanvasInvocationDeps {
flushPendingUploads: () => Promise<void>;
/** Project ids with a prepare currently in flight (module/registry-scoped). */
inFlight: Set<string>;
+ /** Account-qualified concurrency key; defaults to `projectId` for isolated orchestrator callers. */
+ inFlightKey?: string;
/** The generate widget's raw persisted values (model/prompt/steps, shared with Generate). */
generateValues: Record<string, unknown>;
/** Loaded models, for the same value/model sync the generate path performs. */
@@ -308,13 +316,14 @@ const createRegionalGuidanceCollector = (
*/
export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promise<void> => {
const { commands, inFlight, projectId } = deps;
+ const inFlightKey = deps.inFlightKey ?? projectId;
// Concurrency guard: ignore a re-invoke while a prior prepare for this project
// is still settling (the hotkey can be mashed). Cleared in `finally`.
- if (inFlight.has(projectId)) {
+ if (inFlight.has(inFlightKey)) {
return;
}
- inFlight.add(projectId);
+ inFlight.add(inFlightKey);
try {
const values = normalizeGenerateWidgetValues(deps.generateValues);
@@ -348,6 +357,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
shouldCompositeRegionalMask: regions.shouldComposite,
signal: deps.signal,
});
+ deps.signal.throwIfAborted();
if (composed.status !== 'ok') {
recordNotice(
commands.notifications,
@@ -395,6 +405,10 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
});
composed.dedupeCommit.commit();
} catch (error) {
+ if (deps.signal.aborted) {
+ return;
+ }
+
const message =
error instanceof ControlLayerValidationError && deps.formatControlLayerError
? deps.formatControlLayerError(error.code, error.layerName)
@@ -403,13 +417,20 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
: String(error);
recordNotice(commands.notifications, 'error', message);
} finally {
- inFlight.delete(projectId);
+ inFlight.delete(inFlightKey);
}
};
// Project ids with a prepare in flight (survives across the async orchestrator).
const inFlightProjects = new Set<string>();
+registerAccountOwnedResource({
+ clear: () => {
+ inFlightProjects.clear();
+ },
+ name: 'canvas-invocation-guards',
+});
+
/** Arguments for the thin command-layer {@link prepareCanvasInvocation}. */
export interface PrepareCanvasInvocationArgs {
projectId: string;
@@ -417,6 +438,8 @@ export interface PrepareCanvasInvocationArgs {
destination: ResultDestination;
generateValues: Record<string, unknown>;
models?: readonly ModelConfig[];
+ /** Caller-captured identity lifetime; direct synchronous callers may omit it. */
+ owner?: AccountScope;
projectSettings: Pick<ProjectSettings, 'useCpuNoise'>;
strength: number;
signal?: AbortSignal;
@@ -435,12 +458,18 @@ export interface PrepareCanvasInvocationArgs {
* Fire-and-track: the caller does not await it (the Invoke command stays sync).
*/
export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs): Promise<void> => {
+ const owner = args.owner ?? captureAccountScope();
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
const engine = getCanvasEngine(args.projectId);
if (!engine) {
recordNotice(args.commands.notifications, 'error', 'Open the canvas before invoking it.');
return;
}
const operations = getCanvasOperations(engine);
+ const signal = args.signal ? AbortSignal.any([args.signal, owner.signal]) : owner.signal;
await runCanvasInvocation({
compositing: args.compositing ?? DEFAULT_CANVAS_COMPOSITING,
@@ -451,10 +480,11 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)
formatControlLayerError: args.formatControlLayerError,
generateValues: args.generateValues,
inFlight: inFlightProjects,
+ inFlightKey: `${owner.epoch}:${args.projectId}`,
models: args.models,
projectId: args.projectId,
projectSettings: args.projectSettings,
- signal: args.signal ?? new AbortController().signal,
+ signal,
strength: args.strength,
});
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 422bcbcca3..bb696247b3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -63,7 +63,7 @@ import {
getLayerContextMenuLayout,
getLayerContextMenuRenderEntries,
} from './layerContextMenuLayout';
-import { copyBlobToClipboard } from './layerExportActions';
+import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';
import { reorderWithinGroupByKind } from './layerGroups';
import { resolveMenuTargetForRender } from './layerMenuState';
import {
@@ -468,12 +468,14 @@ const LayerMenu = ({
if (!engine) {
throw makeStatusError('not-ready');
}
- const result = await engine.exports.exportBakedLayerBlob(layer.id, { includeDisabled: true });
- if (result.status !== 'ok') {
- throw makeStatusError(result.status);
+
+ const result = await saveLayerToAssets(layer.id, {
+ exportLayer: engine.exports.exportBakedLayerBlob,
+ upload: galleryTransfers.upload,
+ });
+ if (result !== 'saved' && result !== 'stale') {
+ throw makeStatusError(result);
}
- const file = new File([result.blob], `layer-${layer.id}.png`, { type: result.blob.type || 'image/png' });
- await galleryTransfers.upload(file, 'none');
}, [engine, layer.id, makeStatusError]);
const handleCopyToClipboard = useCallback(async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts
index 485e8ea25b..5b630e4e14 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts
@@ -1,6 +1,7 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { describe, expect, it, vi } from 'vitest';
-import { copyBlobToClipboard } from './layerExportActions';
+import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';
describe('copyBlobToClipboard', () => {
it('writes a ClipboardItem using the blob MIME type', async () => {
@@ -30,3 +31,58 @@ describe('copyBlobToClipboard', () => {
await expect(copyBlobToClipboard(new Blob(['pixels']))).rejects.toThrow('Clipboard image copy is unavailable');
});
});
+
+describe('saveLayerToAssets', () => {
+ it('threads the account signal through export and upload', async () => {
+ const owner = accountLifecycle.activate('layer-export-a', ':user:layer-export-a');
+ const blob = new Blob(['pixels'], { type: 'image/png' });
+ const exportLayer = vi.fn(() => Promise.resolve({ blob, status: 'ok' as const }));
+ let uploadedFile: File | null = null;
+ const upload = vi.fn((file: File) => {
+ uploadedFile = file;
+ return Promise.resolve();
+ });
+
+ await expect(saveLayerToAssets('layer-a', { exportLayer, upload })).resolves.toBe('saved');
+
+ expect(exportLayer).toHaveBeenCalledWith('layer-a', { includeDisabled: true, signal: owner.signal });
+ expect(upload).toHaveBeenCalledWith(expect.any(File), 'none', { signal: owner.signal });
+ expect(uploadedFile).toMatchObject({ name: 'layer-layer-a.png', type: 'image/png' });
+ });
+
+ it('does not upload an account A export that completes after account B activates', async () => {
+ const owner = accountLifecycle.activate('layer-export-a', ':user:layer-export-a');
+ let resolveExport!: (value: { status: 'empty' }) => void;
+ const exportResult = new Promise<{ status: 'empty' }>((resolve) => {
+ resolveExport = resolve;
+ });
+ const exportLayer = vi.fn(() => exportResult);
+ const upload = vi.fn(() => Promise.resolve());
+ const pendingSave = saveLayerToAssets('layer-a', { exportLayer, upload });
+
+ accountLifecycle.activate('layer-export-b', ':user:layer-export-b');
+ resolveExport({ status: 'empty' });
+
+ await expect(pendingSave).resolves.toBe('stale');
+ expect(owner.signal.aborted).toBe(true);
+ expect(upload).not.toHaveBeenCalled();
+ });
+
+ it('quietly drops an account A upload that completes after account B activates', async () => {
+ const owner = accountLifecycle.activate('layer-export-a', ':user:layer-export-a');
+ const exportLayer = vi.fn(() => Promise.resolve({ blob: new Blob(['pixels']), status: 'ok' as const }));
+ let resolveUpload!: () => void;
+ const uploadResult = new Promise<void>((resolve) => {
+ resolveUpload = resolve;
+ });
+ const upload = vi.fn(() => uploadResult);
+ const pendingSave = saveLayerToAssets('layer-a', { exportLayer, upload });
+ await vi.waitFor(() => expect(upload).toHaveBeenCalledOnce());
+
+ accountLifecycle.activate('layer-export-b', ':user:layer-export-b');
+ resolveUpload();
+
+ await expect(pendingSave).resolves.toBe('stale');
+ expect(owner.signal.aborted).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
index 259d904af0..f88835f396 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
@@ -1,3 +1,11 @@
+import type { ExportBakedLayerBlobResult } from '@workbench/canvas-engine/api';
+
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+
type ClipboardLike = { write(items: ClipboardItem[]): Promise<void> };
type ClipboardItemCtor = new (items: Record<string, Blob>) => ClipboardItem;
@@ -15,3 +23,48 @@ export const copyBlobToClipboard = async (blob: Blob, deps: CopyBlobToClipboardD
const type = blob.type || 'image/png';
await clipboard.write([new ClipboardItemImpl({ [type]: blob })]);
};
+
+type LayerAssetExportFailureStatus = Exclude<ExportBakedLayerBlobResult['status'], 'ok'>;
+type LayerAssetExportResult = { status: 'ok'; blob: Blob } | { status: LayerAssetExportFailureStatus };
+
+interface SaveLayerToAssetsDeps {
+ exportLayer(
+ layerId: string,
+ options: { includeDisabled: boolean; signal: AbortSignal }
+ ): Promise<LayerAssetExportResult>;
+ upload(file: File, boardId: string, options: { signal: AbortSignal }): Promise<unknown>;
+}
+
+export type SaveLayerToAssetsResult = 'saved' | 'stale' | LayerAssetExportFailureStatus;
+
+/**
+ * Owns the complete local-export → gallery-upload boundary. A stale account
+ * reports `stale` instead of leaking an abort into the next account's UI.
+ */
+export const saveLayerToAssets = async (
+ layerId: string,
+ { exportLayer, upload }: SaveLayerToAssetsDeps
+): Promise<SaveLayerToAssetsResult> => {
+ const owner = captureAccountScope();
+
+ try {
+ const result = await exportLayer(layerId, { includeDisabled: true, signal: owner.signal });
+
+ assertAccountScopeCurrent(owner);
+ if (result.status !== 'ok') {
+ return result.status;
+ }
+
+ const file = new File([result.blob], `layer-${layerId}.png`, { type: result.blob.type || 'image/png' });
+ await upload(file, 'none', { signal: owner.signal });
+
+ assertAccountScopeCurrent(owner);
+ return 'saved';
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return 'stale';
+ }
+
+ throw error;
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts
index 3a041f6a8a..837ca11ce8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts
@@ -1,5 +1,6 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
export type LayerPropertiesSection = 'filter' | 'adjustments';
@@ -16,6 +17,13 @@ export const layerPropertiesRequestStore = createExternalStore<{ request: LayerP
let nextToken = 1;
+registerAccountOwnedResource({
+ clear: () => {
+ layerPropertiesRequestStore.setSnapshot({ request: null });
+ },
+ name: 'layer-properties-requests',
+});
+
export const requestLayerProperties = (layerId: string, section: LayerPropertiesSection): void => {
layerPropertiesRequestStore.setSnapshot({ request: { layerId, section, token: nextToken++ } });
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
index b4064f71b6..ec88457614 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
@@ -1,6 +1,7 @@
import type { GalleryImage } from '@features/gallery';
import type { ImageActions } from '@workbench/image-actions';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
@@ -45,4 +46,9 @@ export const previewHeaderStore = {
},
};
+registerAccountOwnedResource({
+ clear: previewHeaderStore.clear,
+ name: 'preview-header',
+});
+
export const usePreviewHeaderContext = (): PreviewHeaderContext => store.useSelector((snapshot) => snapshot);