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): rerun store refreshes requested mid-flight

joshistoast4c7fcabd10f8
diff --git a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts
index d640bbf383..e2766b8e1a 100644
--- a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts
@@ -4,6 +4,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import {
getExternalProviderConfigs,
@@ -30,50 +31,39 @@ export interface ExternalProvidersSnapshot {
const EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT: ExternalProvidersSnapshot = { configs: null, error: null, status: 'idle' };
const store = createExternalStore<ExternalProvidersSnapshot>(EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT);
-let inflightRefresh: Promise<void> | null = null;
+const refreshFlight = createTrailingSingleFlight();
registerAccountOwnedResource({
clear: () => {
- inflightRefresh = null;
+ refreshFlight.reset();
store.setSnapshot(EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT);
},
name: 'external-providers',
});
/** Re-fetch the configs; rejects on failure (after recording it) so callers can toast. */
-export const refreshExternalProviders = (): Promise<void> => {
- if (inflightRefresh) {
- return inflightRefresh;
- }
-
- const owner = captureAccountScope();
-
- store.patchSnapshot({ status: store.getSnapshot().configs ? 'loaded' : 'loading' });
-
- const refresh = getExternalProviderConfigs(owner.signal)
- .then((configs) => {
- if (isAccountScopeCurrent(owner)) {
- store.patchSnapshot({ configs, error: null, status: 'loaded' });
- }
- })
- .catch((error: unknown) => {
- if (isAccountScopeCurrent(owner)) {
- store.patchSnapshot({
- error: error instanceof Error ? error.message : null,
- status: store.getSnapshot().configs ? 'loaded' : 'error',
- });
- }
- throw error;
- })
- .finally(() => {
- if (inflightRefresh === refresh) {
- inflightRefresh = null;
- }
- });
-
- inflightRefresh = refresh;
- return inflightRefresh;
-};
+export const refreshExternalProviders = (): Promise<void> =>
+ refreshFlight.run(() => {
+ const owner = captureAccountScope();
+
+ store.patchSnapshot({ status: store.getSnapshot().configs ? 'loaded' : 'loading' });
+
+ return getExternalProviderConfigs(owner.signal)
+ .then((configs) => {
+ if (isAccountScopeCurrent(owner)) {
+ store.patchSnapshot({ configs, error: null, status: 'loaded' });
+ }
+ })
+ .catch((error: unknown) => {
+ if (isAccountScopeCurrent(owner)) {
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : null,
+ status: store.getSnapshot().configs ? 'loaded' : 'error',
+ });
+ }
+ throw error;
+ });
+ });
/** Fetch on first use; callers share the request and can catch its failure. */
export const ensureExternalProvidersLoaded = (): Promise<void> => {
@@ -83,7 +73,7 @@ export const ensureExternalProvidersLoaded = (): Promise<void> => {
return refreshExternalProviders();
}
- return inflightRefresh ?? Promise.resolve();
+ return refreshFlight.inflight() ?? Promise.resolve();
};
const replaceConfigInStore = (next: ExternalProviderConfig): void => {
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 85d0d072bc..b67b5ced0e 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts
@@ -75,7 +75,12 @@ describe('model install event interpretation', () => {
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);
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ // The join during the replacement flight queues a trailing rerun.
+ .mockResolvedValueOnce([{ id: 2, source: 'new/account', status: 'waiting' }]);
const store = await import('./installsStore');
const { accountLifecycle } = await import('@platform/state/accountLifecycle');
@@ -96,7 +101,9 @@ describe('model install event interpretation', () => {
second.resolve([{ id: 2, source: 'new/account', status: 'waiting' }]);
await currentRefresh;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(3);
expect(store.getInstallsSnapshot()).toEqual({
error: null,
jobs: [{ id: 2, source: 'new/account', status: 'waiting' }],
@@ -104,6 +111,33 @@ describe('model install event interpretation', () => {
});
});
+ it('re-fetches once more when a refresh lands while another is in flight', async () => {
+ const stale = deferred<Array<{ id: number; source: string; status: string }>>();
+
+ dependencies.listModelInstalls
+ .mockReset()
+ .mockReturnValueOnce(stale.promise)
+ .mockResolvedValueOnce([{ id: 1, source: 'org/model', status: 'completed' }]);
+
+ const store = await import('./installsStore');
+
+ // First completion schedules the coalesced refresh, which starts and hangs.
+ store.handleModelInstallSocketEvent('model_install_complete', { config: {}, id: 1, source: 'org/model' });
+ await vi.advanceTimersByTimeAsync(250);
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);
+
+ // Second completion's refresh joins the in-flight request...
+ store.handleModelInstallSocketEvent('model_install_complete', { config: {}, id: 1, source: 'org/model' });
+ await vi.advanceTimersByTimeAsync(250);
+
+ // ...so when the stale response lands, one trailing re-fetch brings the fresh list.
+ stale.resolve([{ id: 1, source: 'org/model', status: 'running' }]);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(2);
+ expect(store.getInstallsSnapshot().jobs).toEqual([{ id: 1, source: 'org/model', status: 'completed' }]);
+ });
+
it('ignores socket events owned by an expired account scope', async () => {
const store = await import('./installsStore');
const { accountLifecycle } = await import('@platform/state/accountLifecycle');
diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
index 4d6b617351..0de4b8d018 100644
--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts
@@ -7,6 +7,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import { listModelInstalls } from './api';
import { refreshModels } from './modelsStore';
@@ -81,7 +82,7 @@ let nextOutcomeId = 1;
const progressByJobId = createKeyedTransientStore<number, InstallDownloadProgress>();
-let inflightRefresh: Promise<void> | null = null;
+const refreshFlight = createTrailingSingleFlight();
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
registerAccountOwnedResource({
@@ -91,7 +92,7 @@ registerAccountOwnedResource({
refreshTimer = null;
}
- inflightRefresh = null;
+ refreshFlight.reset();
nextOutcomeId = 1;
progressByJobId.clear();
outcomesStore.setSnapshot(EMPTY_INSTALL_OUTCOMES);
@@ -100,48 +101,37 @@ registerAccountOwnedResource({
name: 'model-installs',
});
-export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Promise<void> => {
- if (inflightRefresh) {
- return inflightRefresh;
- }
-
- store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+export const refreshInstalls = (owner: AccountScope = captureAccountScope()): Promise<void> =>
+ refreshFlight.run(() => {
+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
- const refresh = listModelInstalls(owner.signal)
- .then((jobs) => {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ return listModelInstalls(owner.signal)
+ .then((jobs) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
- const activeJobIds = new Set(jobs.map((job) => job.id));
+ const activeJobIds = new Set(jobs.map((job) => job.id));
- for (const [jobId] of progressByJobId.entries()) {
- if (!activeJobIds.has(jobId)) {
- progressByJobId.delete(jobId);
+ for (const [jobId] of progressByJobId.entries()) {
+ if (!activeJobIds.has(jobId)) {
+ progressByJobId.delete(jobId);
+ }
}
- }
- store.patchSnapshot({ error: null, jobs, status: 'loaded' });
- })
- .catch((error: unknown) => {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ 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',
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load install queue.',
+ status: store.getSnapshot().jobs.length > 0 ? 'loaded' : 'error',
+ });
});
- })
- .finally(() => {
- if (inflightRefresh === refresh) {
- inflightRefresh = null;
- }
- });
-
- inflightRefresh = refresh;
- return inflightRefresh;
-};
+ });
export const ensureInstallsLoaded = (): void => {
if (store.getSnapshot().status === 'idle') {
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 84d0882d7b..4a7580ba82 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
@@ -49,6 +49,19 @@ describe('models store loading', () => {
const account = await import('@platform/state/accountLifecycle');
account.accountLifecycle.activate('user-a');
const modelsStore = await import('./modelsStore');
+ const modelB: ModelConfig = {
+ 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',
+ } as ModelConfig;
let resolveA: ((value: ModelConfig[]) => void) | undefined;
let resolveB: ((value: ModelConfig[]) => void) | undefined;
api.listModels
@@ -61,7 +74,9 @@ describe('models store loading', () => {
new Promise((resolve) => {
resolveB = resolve;
})
- );
+ )
+ // The join during user B's flight queues a trailing rerun.
+ .mockResolvedValueOnce([modelB]);
const userARefresh = modelsStore.refreshModels();
account.accountLifecycle.invalidate();
@@ -72,23 +87,16 @@ describe('models store loading', () => {
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',
- },
- ]);
+ resolveB?.([modelB]);
await userBRefresh;
expect(modelsStore.getModelsSnapshot().models.map((model) => model.key)).toEqual(['model-b']);
+
+ // The mid-flight join re-fetches once more after the shared flight settles.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ expect(api.listModels).toHaveBeenCalledTimes(3);
+ 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 7193456284..fe9842b8cd 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
@@ -7,6 +7,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import { getModelsDir, listMissingModels, listModels } from './api';
@@ -43,64 +44,53 @@ const EMPTY_MODELS_SNAPSHOT: ModelsSnapshot = {
};
const store = createExternalStore<ModelsSnapshot>(EMPTY_MODELS_SNAPSHOT);
-let inflightRefresh: Promise<void> | null = null;
+const refreshFlight = createTrailingSingleFlight();
registerAccountOwnedResource({
clear: () => {
- inflightRefresh = null;
+ refreshFlight.reset();
store.setSnapshot(EMPTY_MODELS_SNAPSHOT);
},
name: 'models-library',
});
-/** Re-fetch the library; concurrent calls share one request. */
-export const refreshModels = (owner: AccountScope = captureAccountScope()): Promise<void> => {
- if (inflightRefresh) {
- return inflightRefresh;
- }
-
- store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
-
- const refresh = Promise.all([
- listModels(owner.signal),
- // Missing-file detection is best-effort; never fail the whole library.
- listMissingModels(owner.signal).catch(() => [] as ModelConfig[]),
- // Static server config: fetched once, best-effort.
- store.getSnapshot().modelsDir ?? getModelsDir(owner.signal).catch(() => null),
- ])
- .then(([models, missingModels, modelsDir]) => {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- store.patchSnapshot({
- error: null,
- missingModelKeys:
- missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS,
- models,
- modelsDir,
- status: 'loaded',
- });
- })
- .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',
+/** Re-fetch the library; concurrent calls share one request, and a call made mid-flight queues one trailing rerun. */
+export const refreshModels = (owner: AccountScope = captureAccountScope()): Promise<void> =>
+ refreshFlight.run(() => {
+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+
+ return Promise.all([
+ listModels(owner.signal),
+ // Missing-file detection is best-effort; never fail the whole library.
+ listMissingModels(owner.signal).catch(() => [] as ModelConfig[]),
+ // Static server config: fetched once, best-effort.
+ store.getSnapshot().modelsDir ?? getModelsDir(owner.signal).catch(() => null),
+ ])
+ .then(([models, missingModels, modelsDir]) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ store.patchSnapshot({
+ error: null,
+ missingModelKeys:
+ missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS,
+ models,
+ modelsDir,
+ status: 'loaded',
+ });
+ })
+ .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(() => {
- if (inflightRefresh === refresh) {
- inflightRefresh = null;
- }
- });
-
- inflightRefresh = refresh;
- return inflightRefresh;
-};
+ });
/** Fetch on first use or retry after an error; callers share and can await the request. */
export const ensureModelsLoaded = (): Promise<void> => {
@@ -110,7 +100,7 @@ export const ensureModelsLoaded = (): Promise<void> => {
return refreshModels();
}
- return inflightRefresh ?? Promise.resolve();
+ return refreshFlight.inflight() ?? Promise.resolve();
};
export const getModelsSnapshot = (): ModelsSnapshot => store.getSnapshot();
diff --git a/invokeai/frontend/webv2/src/features/models/data/startersStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/startersStore.test.ts
index 6e3bda9ea0..a0b64de937 100644
--- a/invokeai/frontend/webv2/src/features/models/data/startersStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/startersStore.test.ts
@@ -12,18 +12,21 @@ describe('starters store', () => {
api.getStarterModels.mockReset();
});
- it('dedupes concurrent refreshes and keeps the catalog on later failures', async () => {
+ it('dedupes concurrent refreshes and keeps the catalog when the trailing rerun fails', async () => {
api.getStarterModels.mockResolvedValueOnce(response).mockRejectedValueOnce(new Error('outage'));
const store = await import('./startersStore');
const first = store.refreshStarters();
+ // Joining mid-flight shares the request and queues one trailing rerun.
expect(store.refreshStarters()).toBe(first);
await first;
- expect(store.getStartersSnapshot()).toMatchObject({ error: null, response, status: 'loaded' });
+ expect(store.getStartersSnapshot()).toMatchObject({ response, status: 'loaded' });
- await store.refreshStarters();
- expect(store.getStartersSnapshot()).toMatchObject({ error: 'outage', response, status: 'loaded' });
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
expect(api.getStarterModels).toHaveBeenCalledTimes(2);
+ expect(store.getStartersSnapshot()).toMatchObject({ error: 'outage', response, status: 'loaded' });
});
it('ensures once and revalidates only when already loaded', async () => {
diff --git a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
index 26bed296dc..1f070cfae8 100644
--- a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts
@@ -6,6 +6,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import { getStarterModels } from './api';
@@ -24,51 +25,40 @@ export interface StartersSnapshot {
const EMPTY_STARTERS_SNAPSHOT: StartersSnapshot = { error: null, response: null, status: 'idle' };
const store = createExternalStore<StartersSnapshot>(EMPTY_STARTERS_SNAPSHOT);
-let inflightRefresh: Promise<void> | null = null;
+const refreshFlight = createTrailingSingleFlight();
registerAccountOwnedResource({
clear: () => {
- inflightRefresh = null;
+ refreshFlight.reset();
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' });
-
- 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',
+export const refreshStarters = (): Promise<void> =>
+ refreshFlight.run(() => {
+ const owner = captureAccountScope();
+ store.patchSnapshot({ status: store.getSnapshot().response ? 'loaded' : 'loading' });
+
+ return 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(() => {
- if (inflightRefresh === refresh) {
- inflightRefresh = null;
- }
- });
-
- inflightRefresh = refresh;
- return inflightRefresh;
-};
+ });
export const ensureStartersLoaded = (): void => {
if (store.getSnapshot().status === 'idle') {
diff --git a/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts b/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts
index f847cd2363..07d39f6d70 100644
--- a/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts
+++ b/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
-import { createSingleFlight } from './singleFlight';
+import { createSingleFlight, createTrailingSingleFlight } from './singleFlight';
const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {
let resolve!: (value: T) => void;
@@ -78,3 +78,98 @@ describe('platform createSingleFlight', () => {
expect(failing).toHaveBeenCalledTimes(2);
});
});
+
+describe('platform createTrailingSingleFlight', () => {
+ it('runs immediately when idle and shares the flight with mid-flight callers', async () => {
+ const flight = createTrailingSingleFlight();
+ const { promise, resolve } = deferred<void>();
+ const task = vi.fn(() => promise);
+
+ const first = flight.run(task);
+ const joined = flight.run(task);
+
+ expect(joined).toBe(first);
+ expect(flight.inflight()).toBe(first);
+ expect(task).toHaveBeenCalledTimes(1);
+ resolve();
+ await first;
+ });
+
+ it('reruns exactly once no matter how many callers joined mid-flight', async () => {
+ const flight = createTrailingSingleFlight();
+ const initial = deferred<void>();
+ const task = vi.fn().mockReturnValueOnce(initial.promise).mockResolvedValue(undefined);
+
+ void flight.run(task);
+ void flight.run(task);
+ void flight.run(task);
+ void flight.run(task);
+
+ initial.resolve();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(task).toHaveBeenCalledTimes(2);
+ expect(flight.inflight()).toBeNull();
+ });
+
+ it('does not rerun when no caller joined mid-flight', async () => {
+ const flight = createTrailingSingleFlight();
+ const task = vi.fn(() => Promise.resolve());
+
+ await flight.run(task);
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+
+ it('reset cancels the in-flight run and any queued rerun', async () => {
+ const flight = createTrailingSingleFlight();
+ const initial = deferred<void>();
+ const task = vi.fn().mockReturnValueOnce(initial.promise).mockResolvedValue(undefined);
+
+ void flight.run(task);
+ void flight.run(task);
+ flight.reset();
+
+ expect(flight.inflight()).toBeNull();
+ initial.resolve();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows a rerun rejection but propagates the joined flight rejection', async () => {
+ const flight = createTrailingSingleFlight();
+ const initial = deferred<void>();
+ const task = vi.fn().mockReturnValueOnce(initial.promise).mockRejectedValue(new Error('rerun failed'));
+
+ const first = flight.run(task);
+ const joined = flight.run(task);
+
+ initial.resolve();
+ await expect(joined).resolves.toBeUndefined();
+ await expect(first).resolves.toBeUndefined();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(task).toHaveBeenCalledTimes(2);
+ expect(flight.inflight()).toBeNull();
+ });
+
+ it('turns a synchronously-throwing task into a rejected flight', async () => {
+ const flight = createTrailingSingleFlight();
+ const task = vi.fn(() => {
+ throw new Error('sync throw');
+ });
+
+ await expect(flight.run(task as () => Promise<void>)).rejects.toThrow('sync throw');
+ expect(flight.inflight()).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/state/singleFlight.ts b/invokeai/frontend/webv2/src/platform/state/singleFlight.ts
index 0da2184f7a..c26922f2cd 100644
--- a/invokeai/frontend/webv2/src/platform/state/singleFlight.ts
+++ b/invokeai/frontend/webv2/src/platform/state/singleFlight.ts
@@ -3,6 +3,69 @@ export interface SingleFlight<T> {
run(key: string, task: () => Promise<T>): Promise<T>;
}
+export interface TrailingSingleFlight {
+ /**
+ * Runs task now, or joins the in-flight run and queues exactly one trailing
+ * rerun. Callers that join resolve when the run they joined settles; the
+ * rerun keeps the result fresh but is not awaited by them.
+ */
+ run(task: () => Promise<void>): Promise<void>;
+ /** The in-flight promise, if any (for ensure* fast paths). */
+ inflight(): Promise<void> | null;
+ /** Forget in-flight state and any queued rerun (account clear). */
+ reset(): void;
+}
+
+/**
+ * Single-flight dedupe for a store refresh that must not lose requests: a
+ * refresh asked for while one is already in flight would otherwise be
+ * absorbed by a request that was issued before the triggering change existed
+ * (e.g. two install completions ~100ms apart). The trailing rerun re-executes
+ * the task once after the current flight settles; its rejection is swallowed
+ * because no caller is attached to it.
+ */
+export const createTrailingSingleFlight = (): TrailingSingleFlight => {
+ let pending: Promise<void> | null = null;
+ let rerunRequested = false;
+
+ const launch = (task: () => Promise<void>): Promise<void> => {
+ rerunRequested = false;
+ let started: Promise<void>;
+ try {
+ started = task();
+ } catch (error) {
+ started = Promise.reject(error);
+ }
+ const flight = started.finally(() => {
+ // reset() may have run mid-flight; it cancelled any queued rerun.
+ if (pending !== flight) {
+ return;
+ }
+ pending = null;
+ if (rerunRequested) {
+ launch(task).catch(() => undefined);
+ }
+ });
+ pending = flight;
+ return flight;
+ };
+
+ return {
+ inflight: () => pending,
+ reset() {
+ pending = null;
+ rerunRequested = false;
+ },
+ run(task) {
+ if (pending) {
+ rerunRequested = true;
+ return pending;
+ }
+ return launch(task);
+ },
+ };
+};
+
export const createSingleFlight = <T>(): SingleFlight<T> => {
let pending: Promise<T> | null = null;
let pendingKey: string | null = null;