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(state): move projected stores to platform
joshistoast68ac1ab066e0
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex 85d592cd89..a6b0408c3e 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -9,6 +9,7 @@ import { nodeExecutionStore } from '@features/nodes';import { hasPendingWorkflowQueueItem } from '@features/queue';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';+import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';import { shallowEqual } from '@platform/state/selectors';import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';import { registerHotkeyModalLayer } from '@workbench/hotkeys';@@ -30,8 +31,6 @@ import {} from '@workbench/WorkbenchContext';import { useMemo } from 'react';-import { createCachedWorkflowReadPort } from './cachedWorkflowReadPort';-const selectInvocationRouteInput = createInvocationRouteInputSelector();const selectWorkflowPreferences = (preferences: WorkbenchPreferences) => ({@@ -102,10 +101,9 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })const project = useMemo(() =>- createCachedWorkflowReadPort(- store.subscribe,- store.getSnapshot,- (snapshot) => ({+ createProjectedExternalStore({+ source: store,+ select: (snapshot) => ({galleryValues: getProjectWidgetValues(snapshot.activeProject, 'gallery'),graphHistory: snapshot.activeProject.graphHistory,id: snapshot.activeProject.id,@@ -113,28 +111,26 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })projectGraph: snapshot.activeProject.projectGraph,workflowValues: getProjectWidgetValues(snapshot.activeProject, 'workflow'),}),- shallowEqual- ),+ isEqual: shallowEqual,+ }),[store]);const preferences = useMemo(() =>- createCachedWorkflowReadPort(- (listener) => subscribeWorkbenchPreferences(listener),- getWorkbenchPreferences,- selectWorkflowPreferences,- shallowEqual- ),+ createProjectedExternalStore({+ source: { getSnapshot: getWorkbenchPreferences, subscribe: subscribeWorkbenchPreferences },+ select: selectWorkflowPreferences,+ isEqual: shallowEqual,+ }),[]);const capabilities = useMemo(() =>- createCachedWorkflowReadPort(- subscribeAuthSession,- getAuthSession,- (session) => ({ canUseCache: !session.multiuserEnabled || session.user?.is_admin === true }),- shallowEqual- ),+ createProjectedExternalStore({+ source: { getSnapshot: getAuthSession, subscribe: subscribeAuthSession },+ select: (session) => ({ canUseCache: !session.multiuserEnabled || session.user?.is_admin === true }),+ isEqual: shallowEqual,+ }),[]);diff --git a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.ts b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.tsdeleted file mode 100644index 58750b1300..0000000000--- a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { shallowEqual } from '@platform/state/selectors';-import { describe, expect, it, vi } from 'vitest';--import { createCachedWorkflowReadPort } from './cachedWorkflowReadPort';--describe('createCachedWorkflowReadPort', () => {- it('keeps mapped snapshots stable and silent for unrelated source changes', () => {- let source = {- modelsRevision: 0,- notificationsRevision: 0,- projectId: 'project-1',- routeRevision: 0,- sessionRevision: 0,- };- const sourceListeners = new Set<() => void>();- const port = createCachedWorkflowReadPort(- (listener) => {- sourceListeners.add(listener);- return () => sourceListeners.delete(listener);- },- () => source,- (snapshot) => ({ id: snapshot.projectId }),- shallowEqual- );- const listener = vi.fn();- port.subscribe(listener);- const initial = port.getSnapshot();-- source = { ...source, modelsRevision: 1, notificationsRevision: 1, routeRevision: 1, sessionRevision: 1 };- sourceListeners.forEach((notify) => notify());-- expect(listener).not.toHaveBeenCalled();- expect(port.getSnapshot()).toBe(initial);-- source = { ...source, projectId: 'project-2' };- sourceListeners.forEach((notify) => notify());-- expect(listener).toHaveBeenCalledOnce();- expect(port.getSnapshot()).toEqual({ id: 'project-2' });- expect(port.getSnapshot()).toBe(port.getSnapshot());- });-- it('notifies every subscriber when one source change refreshes the shared cache', () => {- let source = { projectId: 'project-1' };- const sourceListeners = new Set<() => void>();- const port = createCachedWorkflowReadPort(- (listener) => {- sourceListeners.add(listener);- return () => sourceListeners.delete(listener);- },- () => source,- (snapshot) => ({ id: snapshot.projectId }),- shallowEqual- );- const firstListener = vi.fn();- const secondListener = vi.fn();- const unsubscribeFirst = port.subscribe(firstListener);- const unsubscribeSecond = port.subscribe(secondListener);-- expect(sourceListeners.size).toBe(1);-- source = { projectId: 'project-2' };- sourceListeners.forEach((notify) => notify());-- expect(firstListener).toHaveBeenCalledOnce();- expect(secondListener).toHaveBeenCalledOnce();-- unsubscribeFirst();- unsubscribeSecond();- expect(sourceListeners.size).toBe(0);- });-});diff --git a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.ts b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.tsdeleted file mode 100644index 8198248e6d..0000000000--- a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.ts+++ /dev/null@@ -1,58 +0,0 @@-import type { WorkflowReadPort } from '@features/workflow/react';-import type { EqualityFn } from '@platform/state/selectors';--/** Maps a broad external store to a referentially stable narrow read port. */-export const createCachedWorkflowReadPort = <Source, Snapshot>(- subscribe: (listener: () => void) => () => void,- getSourceSnapshot: () => Source,- mapSnapshot: (source: Source) => Snapshot,- isEqual: EqualityFn<Snapshot> = Object.is-): WorkflowReadPort<Snapshot> => {- let sourceSnapshot = getSourceSnapshot();- let snapshot = mapSnapshot(sourceSnapshot);- const listeners = new Set<() => void>();- let unsubscribeSource: (() => void) | null = null;-- const refresh = (): boolean => {- const nextSourceSnapshot = getSourceSnapshot();- if (Object.is(nextSourceSnapshot, sourceSnapshot)) {- return false;- }- sourceSnapshot = nextSourceSnapshot;- const nextSnapshot = mapSnapshot(nextSourceSnapshot);- if (isEqual(snapshot, nextSnapshot)) {- return false;- }- snapshot = nextSnapshot;- return true;- };-- const notifyIfChanged = (): void => {- if (!refresh()) {- return;- }-- for (const listener of listeners) {- listener();- }- };-- return {- getSnapshot: () => {- refresh();- return snapshot;- },- subscribe: (listener) => {- listeners.add(listener);- unsubscribeSource ??= subscribe(notifyIfChanged);-- return () => {- listeners.delete(listener);- if (listeners.size === 0) {- unsubscribeSource?.();- unsubscribeSource = null;- }- };- },- };-};diff --git a/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.test.ts b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.test.tsnew file mode 100644index 0000000000..9c3817c481--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi } from 'vitest';++import { createProjectedExternalStore } from './projectedExternalStore';+import { shallowEqual } from './selectors';++describe('createProjectedExternalStore', () => {+ it('keeps projected snapshots stable and silent for unrelated source changes', () => {+ let source = {+ modelsRevision: 0,+ notificationsRevision: 0,+ projectId: 'project-1',+ routeRevision: 0,+ sessionRevision: 0,+ };+ const sourceListeners = new Set<() => void>();+ const store = createProjectedExternalStore({+ source: {+ getSnapshot: () => source,+ subscribe: (listener) => {+ sourceListeners.add(listener);+ return () => sourceListeners.delete(listener);+ },+ },+ select: (snapshot) => ({ id: snapshot.projectId }),+ isEqual: shallowEqual,+ });+ const listener = vi.fn();+ store.subscribe(listener);+ const initial = store.getSnapshot();++ source = { ...source, modelsRevision: 1, notificationsRevision: 1, routeRevision: 1, sessionRevision: 1 };+ sourceListeners.forEach((notify) => notify());++ expect(listener).not.toHaveBeenCalled();+ expect(store.getSnapshot()).toBe(initial);++ source = { ...source, projectId: 'project-2' };+ sourceListeners.forEach((notify) => notify());++ expect(listener).toHaveBeenCalledOnce();+ expect(store.getSnapshot()).toEqual({ id: 'project-2' });+ expect(store.getSnapshot()).toBe(store.getSnapshot());+ });++ it('shares one lazy source subscription across every projected-store subscriber', () => {+ let source = { projectId: 'project-1' };+ const sourceListeners = new Set<() => void>();+ const store = createProjectedExternalStore({+ source: {+ getSnapshot: () => source,+ subscribe: (listener) => {+ sourceListeners.add(listener);+ return () => sourceListeners.delete(listener);+ },+ },+ select: (snapshot) => ({ id: snapshot.projectId }),+ isEqual: shallowEqual,+ });+ const firstListener = vi.fn();+ const secondListener = vi.fn();+ const unsubscribeFirst = store.subscribe(firstListener);+ const unsubscribeSecond = store.subscribe(secondListener);++ expect(sourceListeners.size).toBe(1);++ source = { projectId: 'project-2' };+ sourceListeners.forEach((notify) => notify());++ expect(firstListener).toHaveBeenCalledOnce();+ expect(secondListener).toHaveBeenCalledOnce();++ unsubscribeFirst();+ unsubscribeSecond();+ expect(sourceListeners.size).toBe(0);+ });++ it('refreshes on demand after its final source subscription is removed', () => {+ let source = { projectId: 'project-1' };+ const sourceListeners = new Set<() => void>();+ const store = createProjectedExternalStore({+ source: {+ getSnapshot: () => source,+ subscribe: (listener) => {+ sourceListeners.add(listener);+ return () => sourceListeners.delete(listener);+ },+ },+ select: (snapshot) => snapshot.projectId,+ });+ const unsubscribe = store.subscribe(vi.fn());+ unsubscribe();++ source = { projectId: 'project-2' };++ expect(sourceListeners.size).toBe(0);+ expect(store.getSnapshot()).toBe('project-2');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.ts b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.tsnew file mode 100644index 0000000000..770ad5bf5d--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.ts@@ -0,0 +1,73 @@+import type { EqualityFn } from './selectorCore';++/** Domain-neutral read-only external store. */+export interface ReadableExternalStore<Snapshot> {+ getSnapshot(): Snapshot;+ subscribe(listener: () => void): () => void;+}++interface ProjectedExternalStoreOptions<Source, Snapshot> {+ source: ReadableExternalStore<Source>;+ select: (source: Source) => Snapshot;+ isEqual?: EqualityFn<Snapshot>;+}++/**+ * Projects a broad external store into a referentially stable read-only store.+ * The source subscription is shared lazily and unrelated source changes remain+ * silent when the projected snapshot is equal.+ */+export const createProjectedExternalStore = <Source, Snapshot>({+ isEqual = Object.is,+ select,+ source,+}: ProjectedExternalStoreOptions<Source, Snapshot>): ReadableExternalStore<Snapshot> => {+ let sourceSnapshot = source.getSnapshot();+ let snapshot = select(sourceSnapshot);+ const listeners = new Set<() => void>();+ let unsubscribeSource: (() => void) | null = null;++ const refresh = (): boolean => {+ const nextSourceSnapshot = source.getSnapshot();+ if (Object.is(nextSourceSnapshot, sourceSnapshot)) {+ return false;+ }+ sourceSnapshot = nextSourceSnapshot;++ const nextSnapshot = select(nextSourceSnapshot);+ if (isEqual(snapshot, nextSnapshot)) {+ return false;+ }+ snapshot = nextSnapshot;+ return true;+ };++ const notifyIfChanged = (): void => {+ if (!refresh()) {+ return;+ }++ for (const listener of listeners) {+ listener();+ }+ };++ return {+ getSnapshot: () => {+ refresh();+ return snapshot;+ },+ subscribe: (listener) => {+ listeners.add(listener);+ unsubscribeSource ??= source.subscribe(notifyIfChanged);++ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) {+ unsubscribeSource?.();+ unsubscribeSource = null;+ }+ };+ },+ };+};