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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(webv2): extract deferred resource
joshistoast33f1b3131ee8
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonindex 8518cecd03..40594cb5f6 100644--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -96,6 +96,7 @@"canvasStagingView.ts": "workbench","controlAdapters.ts": "workbench","controlLayerChecks.ts": "workbench",+ "deferredResource.ts": "workbench","floatingWindows.ts": "workbench","focusRegions.tsx": "workbench","generationSettingsOrchestration.ts": "workbench",diff --git a/invokeai/frontend/webv2/src/workbench/deferredResource.test.ts b/invokeai/frontend/webv2/src/workbench/deferredResource.test.tsnew file mode 100644index 0000000000..8085d533ea--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/deferredResource.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from 'vitest';++import { createDeferredResource } from './deferredResource';++describe('deferred resource', () => {+ it('loads once no matter how many callers ask', async () => {+ const loader = vi.fn(() => Promise.resolve('value'));+ const resource = createDeferredResource(loader);++ resource.preload();+ const [first, second] = await Promise.all([resource.load(), resource.load()]);++ expect(loader).toHaveBeenCalledTimes(1);+ expect(first).toBe('value');+ expect(second).toBe('value');+ });++ it('settles the promise so React use() can read it without suspending', async () => {+ const resource = createDeferredResource(() => Promise.resolve('value'));+ const promise = resource.load() as Promise<string> & { status?: string; value?: string };++ await promise;++ expect(promise.status).toBe('fulfilled');+ expect(promise.value).toBe('value');+ expect(resource.getStatus()).toBe('loaded');+ });++ it('reports failure and lets retry start a fresh attempt', async () => {+ let attempt = 0;+ const resource = createDeferredResource(() => {+ attempt += 1;+ return attempt === 1 ? Promise.reject(new Error('cold')) : Promise.resolve('warm');+ });++ await expect(resource.load()).rejects.toThrow('cold');+ expect(resource.getStatus()).toBe('failed');++ await expect(resource.retry()).resolves.toBe('warm');+ expect(resource.getStatus()).toBe('loaded');+ });++ it('rejects when the validator throws', async () => {+ const resource = createDeferredResource(+ () => Promise.resolve('bad'),+ () => {+ throw new TypeError('invalid');+ }+ );++ await expect(resource.load()).rejects.toThrow('invalid');+ });++ it('does not reject an unhandled promise when preload fails', async () => {+ const resource = createDeferredResource(() => Promise.reject(new Error('cold')));++ expect(() => resource.preload()).not.toThrow();+ await expect(resource.load()).rejects.toThrow('cold');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/deferredResource.ts b/invokeai/frontend/webv2/src/workbench/deferredResource.tsnew file mode 100644index 0000000000..208569792f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/deferredResource.ts@@ -0,0 +1,84 @@+/**+ * The shape React's `use()` inspects before deciding to suspend. A bare promise+ * — even an already-resolved one — always costs a suspension on first read,+ * because `use()` cannot read a native promise synchronously; it has to attach a+ * callback, throw, and retry on the ping. Settling these fields as soon as the+ * load completes lets `use()` return the value on the very first render instead.+ *+ * That distinction is worth real time. Suspending shows a fallback, and once a+ * fallback has been shown React withholds the resolved tree for+ * `FALLBACK_THROTTLE_MS` (300ms) to avoid a flash — which measured as the whole+ * cost of switching layout, long after the chunk had finished downloading.+ */+interface TrackedThenable<T> extends Promise<T> {+ reason?: unknown;+ status?: 'fulfilled' | 'pending' | 'rejected';+ value?: T;+}++export type DeferredResourceStatus = 'idle' | 'loading' | 'loaded' | 'failed';++/** Registry-owned, single-flight resource for a deferred module. */+export interface DeferredResource<T> {+ getStatus: () => DeferredResourceStatus;+ load: () => Promise<T>;+ preload: () => void;+ retry: () => Promise<T>;+}++type ResourceState<T> =+ | { status: 'idle' }+ | { promise: Promise<T>; status: 'loading' }+ | { promise: Promise<T>; status: 'loaded'; value: T }+ | { error: unknown; promise: Promise<T>; status: 'failed' };++export const createDeferredResource = <T>(+ loader: () => Promise<T>,+ validate?: (value: T) => T+): DeferredResource<T> => {+ let state: ResourceState<T> = { status: 'idle' };++ const start = (): Promise<T> => {+ const promise: TrackedThenable<T> = Promise.resolve()+ .then(loader)+ .then((value) => (validate ? validate(value) : value));+ promise.status = 'pending';+ state = { promise, status: 'loading' };+ void promise.then(+ (value) => {+ promise.status = 'fulfilled';+ promise.value = value;+ state = { promise, status: 'loaded', value };+ },+ (error: unknown) => {+ promise.status = 'rejected';+ promise.reason = error;+ state = { error, promise, status: 'failed' };+ }+ );+ return promise;+ };++ const load = (): Promise<T> => {+ if (state.status === 'loading' || state.status === 'loaded' || state.status === 'failed') {+ return state.promise;+ }++ return start();+ };++ return {+ getStatus: () => state.status,+ load,+ preload: () => {+ void load().catch(() => undefined);+ },+ retry: () => {+ if (state.status === 'failed') {+ state = { status: 'idle' };+ }++ return load();+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.tsindex d8d6d9c90f..898d8e6ab9 100644--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts@@ -1,6 +1,7 @@import type { TFunction } from 'i18next';import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';+import type { DeferredResource, DeferredResourceStatus } from './deferredResource';import type { DeveloperLogNamespace } from './diagnostics/contracts';import type { GraphId } from './graphContracts';import type { InvocationSourceId } from './invocationContracts';@@ -99,15 +100,10 @@ export interface WidgetImplementation {footer?: WidgetFooter;}-export type WidgetImplementationLoadStatus = 'idle' | 'loading' | 'loaded' | 'failed';+export type WidgetImplementationLoadStatus = DeferredResourceStatus;/** Registry-owned, single-flight resource for a deferred widget implementation. */-export interface WidgetImplementationResource {- getStatus: () => WidgetImplementationLoadStatus;- load: () => Promise<WidgetImplementation>;- preload: () => void;- retry: () => Promise<WidgetImplementation>;-}+export type WidgetImplementationResource = DeferredResource<WidgetImplementation>;export interface WidgetLabelProps {region: WorkbenchRegion;diff --git a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.ts b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.tsindex e91f37879d..d3c553e257 100644--- a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.ts@@ -8,98 +8,18 @@ const TestView = () => null;const implementation: WidgetImplementation = { view: TestView };describe('widget implementation resource', () => {- it('loads once and shares the promise and implementation instance', async () => {+ it('loads a valid implementation', async () => {const loader = vi.fn(() => Promise.resolve(implementation));const resource = createWidgetImplementationResource('test', loader);- const first = resource.load();- const second = resource.load();-- expect(first).toBe(second);- await expect(first).resolves.toBe(implementation);- expect(resource.load()).toBe(first);- expect(loader).toHaveBeenCalledOnce();+ await expect(resource.load()).resolves.toBe(implementation);expect(resource.getStatus()).toBe('loaded');});- it('caches a rejected load and starts exactly one new attempt on retry', async () => {- const failure = new Error('chunk unavailable');- const loader = vi.fn().mockRejectedValueOnce(failure).mockResolvedValueOnce(implementation);- const resource = createWidgetImplementationResource('test', loader);-- const failed = resource.load();- await expect(failed).rejects.toBe(failure);- expect(resource.load()).toBe(failed);- expect(resource.getStatus()).toBe('failed');-- const retry = resource.retry();- expect(resource.retry()).toBe(retry);- await expect(retry).resolves.toBe(implementation);- expect(loader).toHaveBeenCalledTimes(2);- });-it('rejects implementations without a view through the same failure state', async () => {const resource = createWidgetImplementationResource('test', () => Promise.resolve({} as WidgetImplementation));await expect(resource.load()).rejects.toThrow('must provide a view component');expect(resource.getStatus()).toBe('failed');});-- it('preloads without leaking a rejected promise', async () => {- const loader = vi.fn().mockRejectedValue(new Error('offline'));- const resource = createWidgetImplementationResource('test', loader);-- resource.preload();- await vi.waitFor(() => expect(resource.getStatus()).toBe('failed'));- expect(loader).toHaveBeenCalledOnce();- });-- // React's `use()` reads these fields off the thenable before deciding whether- // to suspend. Without them a settled promise still costs a suspension on first- // read — `use()` cannot inspect a native promise synchronously, so it attaches- // a callback and throws. That suspension shows a fallback, and once a fallback- // is on screen React withholds the resolved tree for FALLBACK_THROTTLE_MS- // (300ms) to avoid a flash. That throttle was the entire measured cost of- // switching layout, long after the chunk had finished downloading, so these- // three fields are load-bearing rather than decorative.- describe('exposes its settled state on the promise for React `use()`', () => {- it('marks the promise pending, then fulfilled with the value', async () => {- const resource = createWidgetImplementationResource('test', () => Promise.resolve(implementation));-- const pending = resource.load() as Promise<WidgetImplementation> & {- status?: string;- value?: WidgetImplementation;- };- expect(pending.status).toBe('pending');-- await pending;-- expect(pending.status).toBe('fulfilled');- expect(pending.value).toBe(implementation);- });-- it('marks the promise rejected with the reason', async () => {- const error = new Error('offline');- const resource = createWidgetImplementationResource('test', () => Promise.reject(error));-- const pending = resource.load() as Promise<WidgetImplementation> & { reason?: unknown; status?: string };- await expect(pending).rejects.toThrow('offline');-- expect(pending.status).toBe('rejected');- expect(pending.reason).toBe(error);- });-- it('keeps the settled state on the promise handed to later callers', async () => {- const resource = createWidgetImplementationResource('test', () => Promise.resolve(implementation));-- await resource.load();- const again = resource.load() as Promise<WidgetImplementation> & {- status?: string;- value?: WidgetImplementation;- };-- expect(again.status).toBe('fulfilled');- expect(again.value).toBe(implementation);- });- });});diff --git a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.ts b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.tsindex bbed381b0b..ee61e69fea 100644--- a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.ts@@ -1,33 +1,6 @@-import type {- WidgetImplementation,- WidgetImplementationLoadStatus,- WidgetImplementationResource,- WidgetTypeId,-} from './widgetContracts';+import type { WidgetImplementation, WidgetImplementationResource, WidgetTypeId } from './widgetContracts';-type ResourceState =- | { status: 'idle' }- | { promise: Promise<WidgetImplementation>; status: 'loading' }- | { promise: Promise<WidgetImplementation>; status: 'loaded'; value: WidgetImplementation }- | { error: unknown; promise: Promise<WidgetImplementation>; status: 'failed' };--/**- * The shape React's `use()` inspects before deciding to suspend. A bare promise- * — even an already-resolved one — always costs a suspension on first read,- * because `use()` cannot read a native promise synchronously; it has to attach a- * callback, throw, and retry on the ping. Settling these fields as soon as the- * load completes lets `use()` return the value on the very first render instead.- *- * That distinction is worth real time. Suspending shows a fallback, and once a- * fallback has been shown React withholds the resolved tree for- * `FALLBACK_THROTTLE_MS` (300ms) to avoid a flash — which measured as the whole- * cost of switching layout, long after the chunk had finished downloading.- */-interface TrackedThenable<T> extends Promise<T> {- reason?: unknown;- status?: 'fulfilled' | 'pending' | 'rejected';- value?: T;-}+import { createDeferredResource } from './deferredResource';const validateImplementation = (widgetId: WidgetTypeId, value: WidgetImplementation): WidgetImplementation => {if (!value || typeof value !== 'object' || typeof value.view !== 'function') {@@ -40,50 +13,5 @@ const validateImplementation = (widgetId: WidgetTypeId, value: WidgetImplementatexport const createWidgetImplementationResource = (widgetId: WidgetTypeId,loader: () => Promise<WidgetImplementation>-): WidgetImplementationResource => {- let state: ResourceState = { status: 'idle' };-- const start = (): Promise<WidgetImplementation> => {- const promise: TrackedThenable<WidgetImplementation> = Promise.resolve()- .then(loader)- .then((implementation) => validateImplementation(widgetId, implementation));- promise.status = 'pending';- state = { promise, status: 'loading' };- void promise.then(- (value) => {- promise.status = 'fulfilled';- promise.value = value;- state = { promise, status: 'loaded', value };- },- (error: unknown) => {- promise.status = 'rejected';- promise.reason = error;- state = { error, promise, status: 'failed' };- }- );- return promise;- };-- const load = (): Promise<WidgetImplementation> => {- if (state.status === 'loading' || state.status === 'loaded' || state.status === 'failed') {- return state.promise;- }-- return start();- };-- return {- getStatus: (): WidgetImplementationLoadStatus => state.status,- load,- preload: () => {- void load().catch(() => undefined);- },- retry: () => {- if (state.status === 'failed') {- state = { status: 'idle' };- }-- return load();- },- };-};+): WidgetImplementationResource =>+ createDeferredResource(loader, (implementation) => validateImplementation(widgetId, implementation));