Skip to content

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

fix(ui): adopt trailing single-flight for custom node pack refreshes

joshistoaste3578d19ff93
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts
new file mode 100644
index 0000000000..d22e1c9562
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({ listCustomNodePacks: vi.fn() }));
+
+vi.mock('./api', () => api);
+
+const pack = (name: string, nodeCount = 1) => ({
+ name,
+ nodeCount,
+ nodeTypes: [],
+ path: `/custom_nodes/${name}`,
+});
+
+const response = (...names: string[]) => ({
+ customNodesPath: '/custom_nodes',
+ nodePacks: names.map((name) => pack(name)),
+});
+
+describe('custom node packs store', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ api.listCustomNodePacks.mockReset();
+ });
+
+ it('shares the request between concurrent ensures and retries after an error', async () => {
+ api.listCustomNodePacks.mockRejectedValueOnce(new Error('outage')).mockResolvedValueOnce(response('pack-a'));
+ const store = await import('./nodesStore');
+
+ const first = store.ensureCustomNodePacksLoaded();
+ expect(store.ensureCustomNodePacksLoaded()).toBe(first);
+ await first;
+ expect(store.getCustomNodesSnapshot()).toMatchObject({ error: 'outage', status: 'error' });
+
+ await store.ensureCustomNodePacksLoaded();
+ expect(store.getCustomNodesSnapshot()).toMatchObject({ error: null, status: 'loaded' });
+ expect(store.getCustomNodesSnapshot().nodePacks.map((candidate) => candidate.name)).toEqual(['pack-a']);
+ expect(api.listCustomNodePacks).toHaveBeenCalledTimes(2);
+ });
+
+ it('reruns once when a refresh joins mid-flight', async () => {
+ let resolveFirst: ((value: unknown) => void) | undefined;
+
+ api.listCustomNodePacks
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveFirst = resolve;
+ })
+ )
+ .mockResolvedValueOnce(response('pack-a', 'pack-b'));
+ const store = await import('./nodesStore');
+
+ const first = store.refreshCustomNodePacks();
+ // Joins the in-flight request and queues one trailing rerun.
+ expect(store.refreshCustomNodePacks()).toBe(first);
+
+ resolveFirst?.(response('pack-a'));
+ await first;
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(api.listCustomNodePacks).toHaveBeenCalledTimes(2);
+ expect(store.getCustomNodesSnapshot().nodePacks.map((candidate) => candidate.name)).toEqual(['pack-a', 'pack-b']);
+ });
+
+ it('keeps loaded packs and records the error when a refresh fails', async () => {
+ api.listCustomNodePacks.mockResolvedValueOnce(response('pack-a')).mockRejectedValueOnce(new Error('outage'));
+ const store = await import('./nodesStore');
+
+ await store.refreshCustomNodePacks();
+ await store.refreshCustomNodePacks();
+
+ // Contract pinned for the maintenance menu's explicit-refresh surfacing:
+ // the stale list keeps rendering, the error waits in the snapshot.
+ expect(store.getCustomNodesSnapshot()).toMatchObject({ error: 'outage', status: 'loaded' });
+ expect(store.getCustomNodesSnapshot().nodePacks.map((candidate) => candidate.name)).toEqual(['pack-a']);
+ });
+
+ it('discards a resolution from a switched-away account', async () => {
+ const account = await import('@platform/state/accountLifecycle');
+
+ account.accountLifecycle.activate('user-a');
+ const store = await import('./nodesStore');
+ let resolveA: ((value: unknown) => void) | undefined;
+
+ api.listCustomNodePacks.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveA = resolve;
+ })
+ );
+
+ const userARefresh = store.refreshCustomNodePacks();
+
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b');
+
+ resolveA?.(response('stale-pack'));
+ await userARefresh;
+
+ expect(store.getCustomNodesSnapshot()).toMatchObject({ nodePacks: [], status: 'idle' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
index fee9b33ffa..69bf1fc7eb 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts
@@ -7,6 +7,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import { getApiErrorMessage } from '@platform/transport/http';
import { listCustomNodePacks } from './api';
@@ -26,61 +27,58 @@ const EMPTY_CUSTOM_NODES_SNAPSHOT: CustomNodesSnapshot = {
};
const store = createExternalStore<CustomNodesSnapshot>(EMPTY_CUSTOM_NODES_SNAPSHOT);
-let inflightRefresh: Promise<void> | null = null;
+const refreshFlight = createTrailingSingleFlight();
registerAccountOwnedResource({
clear: () => {
- inflightRefresh = null;
+ refreshFlight.reset();
store.setSnapshot(EMPTY_CUSTOM_NODES_SNAPSHOT);
},
name: 'custom-node-packs',
});
-export const refreshCustomNodePacks = (owner: AccountScope = captureAccountScope()): Promise<void> => {
- if (inflightRefresh) {
- return inflightRefresh;
- }
+/** Re-fetch the pack list; concurrent calls share one request, and a call made mid-flight queues one trailing rerun. */
+export const refreshCustomNodePacks = (owner: AccountScope = captureAccountScope()): Promise<void> =>
+ refreshFlight.run(() => {
+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+
+ return listCustomNodePacks(owner.signal)
+ .then((response) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ store.patchSnapshot({
+ customNodesPath: response.customNodesPath,
+ error: null,
+ nodePacks: response.nodePacks,
+ status: 'loaded',
+ });
+ })
+ .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',
+ });
+ });
+ });
- store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+/** Fetch on first use or retry after an error; callers share and can await the request. */
+export const ensureCustomNodePacksLoaded = (): Promise<void> => {
+ const { status } = store.getSnapshot();
- const refresh = listCustomNodePacks(owner.signal)
- .then((response) => {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ if (status === 'idle' || status === 'error') {
+ return refreshCustomNodePacks();
+ }
- store.patchSnapshot({
- customNodesPath: response.customNodesPath,
- error: null,
- nodePacks: response.nodePacks,
- status: 'loaded',
- });
- })
- .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(() => {
- if (inflightRefresh === refresh) {
- inflightRefresh = null;
- }
- });
-
- inflightRefresh = refresh;
- return inflightRefresh;
+ return refreshFlight.inflight() ?? Promise.resolve();
};
-export const ensureCustomNodePacksLoaded = (): void => {
- if (store.getSnapshot().status === 'idle') {
- void refreshCustomNodePacks();
- }
-};
+export const getCustomNodesSnapshot = (): CustomNodesSnapshot => store.getSnapshot();
export const removeCustomNodePackFromStore = (packName: string): void => {
store.patchSnapshot({ nodePacks: store.getSnapshot().nodePacks.filter((pack) => pack.name !== packName) });
diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsx
index 806e9eeec7..2870d65f6d 100644
--- a/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsx
+++ b/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsx
@@ -8,7 +8,7 @@ import { LibraryColumn } from './manager/LibraryColumn';
/** Full custom nodes manager: persistent pack library plus right-side detail pane. */
export const NodeManagerView = () => {
useMountEffect(() => {
- ensureCustomNodePacksLoaded();
+ void ensureCustomNodePacksLoaded();
});
return (