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.

16.8 KB
Raw Blame
import type { ThunkDispatch, TypedStartListening, UnknownAction } from '@reduxjs/toolkit';
import {
  addListener,
  combineReducers,
  configureStore,
  createAction,
  createListenerMiddleware,
  isAnyOf,
} from '@reduxjs/toolkit';
import { logger } from 'app/logging/logger';
import { errorHandler } from 'app/store/enhancers/reduxRemember/errors';
import { addAdHocPostProcessingRequestedListener } from 'app/store/middleware/listenerMiddleware/listeners/addAdHocPostProcessingRequestedListener';
import { addAnyEnqueuedListener } from 'app/store/middleware/listenerMiddleware/listeners/anyEnqueued';
import { addAppStartedListener } from 'app/store/middleware/listenerMiddleware/listeners/appStarted';
import { addBatchEnqueuedListener } from 'app/store/middleware/listenerMiddleware/listeners/batchEnqueued';
import { addDeleteBoardAndImagesFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/boardAndImagesDeleted';
import { addBoardIdSelectedListener } from 'app/store/middleware/listenerMiddleware/listeners/boardIdSelected';
import { addBulkDownloadListeners } from 'app/store/middleware/listenerMiddleware/listeners/bulkDownload';
import { addGallerySelectionSourceListener } from 'app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource';
import { addGetOpenAPISchemaListener } from 'app/store/middleware/listenerMiddleware/listeners/getOpenAPISchema';
import { addImageAddedToBoardFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/imageAddedToBoard';
import { addImageRemovedFromBoardFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/imageRemovedFromBoard';
import { addModelSelectedListener } from 'app/store/middleware/listenerMiddleware/listeners/modelSelected';
import { addModelsLoadedListener } from 'app/store/middleware/listenerMiddleware/listeners/modelsLoaded';
import { addSetDefaultSettingsListener } from 'app/store/middleware/listenerMiddleware/listeners/setDefaultSettings';
import { addSocketConnectedEventListener } from 'app/store/middleware/listenerMiddleware/listeners/socketConnected';
import { deepClone } from 'common/util/deepClone';
import { merge } from 'es-toolkit';
import { omit, pick } from 'es-toolkit/compat';
import {
  authSliceConfig,
  externalTokenAdopted,
  logout,
  sessionExpiredLogout,
  staleCredentialsDiscarded,
  tokensBelongToSameUser,
} from 'features/auth/store/authSlice';
import { changeBoardModalSliceConfig, changeBoardOperationInvalidated } from 'features/changeBoardModal/store/slice';
import { canvasSettingsSliceConfig } from 'features/controlLayers/store/canvasSettingsSlice';
import { canvasClearHistory, canvasSliceConfig } from 'features/controlLayers/store/canvasSlice';
import { canvasSessionSliceConfig } from 'features/controlLayers/store/canvasStagingAreaSlice';
import { canvasTextSliceConfig } from 'features/controlLayers/store/canvasTextSlice';
import { canvasWorkflowIntegrationSliceConfig } from 'features/controlLayers/store/canvasWorkflowIntegrationSlice';
import { lorasSliceConfig } from 'features/controlLayers/store/lorasSlice';
import { paramsSliceConfig } from 'features/controlLayers/store/paramsSlice';
import { refImagesSliceConfig } from 'features/controlLayers/store/refImagesSlice';
import { cancelDeletion } from 'features/deleteVideoModal/store/state';
import { dynamicPromptsSliceConfig } from 'features/dynamicPrompts/store/dynamicPromptsSlice';
import { gallerySliceConfig } from 'features/gallery/store/gallerySlice';
import { modelManagerSliceConfig } from 'features/modelManagerV2/store/modelManagerV2Slice';
import { nodesSliceConfig } from 'features/nodes/store/nodesSlice';
import { workflowLibrarySliceConfig } from 'features/nodes/store/workflowLibrarySlice';
import { workflowSettingsSliceConfig } from 'features/nodes/store/workflowSettingsSlice';
import { upscaleSliceConfig } from 'features/parameters/store/upscaleSlice';
import { expandPromptSliceConfig } from 'features/prompt/store/expandPromptSlice';
import { queueSliceConfig } from 'features/queue/store/queueSlice';
import { stylePresetSliceConfig } from 'features/stylePresets/store/stylePresetSlice';
import { hotkeysSliceConfig } from 'features/system/store/hotkeysSlice';
import { systemSliceConfig } from 'features/system/store/systemSlice';
import { uiSliceConfig } from 'features/ui/store/uiSlice';
import { diff } from 'jsondiffpatch';
import type { SerializeFunction, UnserializeFunction } from 'redux-remember';
import { REMEMBER_REHYDRATED, rememberEnhancer, rememberReducer } from 'redux-remember';
import undoable, { ActionCreators, newHistory } from 'redux-undo';
import { serializeError } from 'serialize-error';
import { api } from 'services/api';
import type { JsonObject } from 'type-fest';

import { reduxRememberDriver } from './enhancers/reduxRemember/driver';
import { actionSanitizer } from './middleware/devtools/actionSanitizer';
import { actionsDenylist } from './middleware/devtools/actionsDenylist';
import { stateSanitizer } from './middleware/devtools/stateSanitizer';
import { addArchivedOrDeletedBoardListener } from './middleware/listenerMiddleware/listeners/addArchivedOrDeletedBoardListener';
import { addPBRFilterListener } from './middleware/listenerMiddleware/listeners/addPBRFilterListener';
import { addImageUploadedFulfilledListener } from './middleware/listenerMiddleware/listeners/imageUploaded';
import { addVideoUploadedListeners } from './middleware/listenerMiddleware/listeners/videoUploaded';

const listenerMiddleware = createListenerMiddleware();

const log = logger('system');

// When adding a slice, add the config to the SLICE_CONFIGS object below, then add the reducer to ALL_REDUCERS.
const SLICE_CONFIGS = {
  [authSliceConfig.slice.reducerPath]: authSliceConfig,
  [canvasSessionSliceConfig.slice.reducerPath]: canvasSessionSliceConfig,
  [canvasSettingsSliceConfig.slice.reducerPath]: canvasSettingsSliceConfig,
  [canvasTextSliceConfig.slice.reducerPath]: canvasTextSliceConfig,
  [canvasSliceConfig.slice.reducerPath]: canvasSliceConfig,
  [canvasWorkflowIntegrationSliceConfig.slice.reducerPath]: canvasWorkflowIntegrationSliceConfig,
  [changeBoardModalSliceConfig.slice.reducerPath]: changeBoardModalSliceConfig,
  [dynamicPromptsSliceConfig.slice.reducerPath]: dynamicPromptsSliceConfig,
  [expandPromptSliceConfig.slice.reducerPath]: expandPromptSliceConfig,
  [gallerySliceConfig.slice.reducerPath]: gallerySliceConfig,
  [hotkeysSliceConfig.slice.reducerPath]: hotkeysSliceConfig,
  [lorasSliceConfig.slice.reducerPath]: lorasSliceConfig,
  [modelManagerSliceConfig.slice.reducerPath]: modelManagerSliceConfig,
  [nodesSliceConfig.slice.reducerPath]: nodesSliceConfig,
  [paramsSliceConfig.slice.reducerPath]: paramsSliceConfig,
  [queueSliceConfig.slice.reducerPath]: queueSliceConfig,
  [refImagesSliceConfig.slice.reducerPath]: refImagesSliceConfig,
  [stylePresetSliceConfig.slice.reducerPath]: stylePresetSliceConfig,
  [systemSliceConfig.slice.reducerPath]: systemSliceConfig,
  [uiSliceConfig.slice.reducerPath]: uiSliceConfig,
  [upscaleSliceConfig.slice.reducerPath]: upscaleSliceConfig,
  [workflowLibrarySliceConfig.slice.reducerPath]: workflowLibrarySliceConfig,
  [workflowSettingsSliceConfig.slice.reducerPath]: workflowSettingsSliceConfig,
};

// TS makes it really hard to dynamically create this object :/ so it's just hardcoded here.
// Remember to wrap undoable reducers in `undoable()`!
const ALL_REDUCERS = {
  [api.reducerPath]: api.reducer,
  [authSliceConfig.slice.reducerPath]: authSliceConfig.slice.reducer,
  [canvasSessionSliceConfig.slice.reducerPath]: canvasSessionSliceConfig.slice.reducer,
  [canvasSettingsSliceConfig.slice.reducerPath]: canvasSettingsSliceConfig.slice.reducer,
  [canvasTextSliceConfig.slice.reducerPath]: canvasTextSliceConfig.slice.reducer,
  // Undoable!
  [canvasSliceConfig.slice.reducerPath]: undoable(
    canvasSliceConfig.slice.reducer,
    canvasSliceConfig.undoableConfig?.reduxUndoOptions
  ),
  [canvasWorkflowIntegrationSliceConfig.slice.reducerPath]: canvasWorkflowIntegrationSliceConfig.slice.reducer,
  [changeBoardModalSliceConfig.slice.reducerPath]: changeBoardModalSliceConfig.slice.reducer,
  [dynamicPromptsSliceConfig.slice.reducerPath]: dynamicPromptsSliceConfig.slice.reducer,
  [expandPromptSliceConfig.slice.reducerPath]: expandPromptSliceConfig.slice.reducer,
  [gallerySliceConfig.slice.reducerPath]: gallerySliceConfig.slice.reducer,
  [hotkeysSliceConfig.slice.reducerPath]: hotkeysSliceConfig.slice.reducer,
  [lorasSliceConfig.slice.reducerPath]: lorasSliceConfig.slice.reducer,
  [modelManagerSliceConfig.slice.reducerPath]: modelManagerSliceConfig.slice.reducer,
  // Undoable!
  [nodesSliceConfig.slice.reducerPath]: undoable(
    nodesSliceConfig.slice.reducer,
    nodesSliceConfig.undoableConfig?.reduxUndoOptions
  ),
  [paramsSliceConfig.slice.reducerPath]: paramsSliceConfig.slice.reducer,
  [queueSliceConfig.slice.reducerPath]: queueSliceConfig.slice.reducer,
  [refImagesSliceConfig.slice.reducerPath]: refImagesSliceConfig.slice.reducer,
  [stylePresetSliceConfig.slice.reducerPath]: stylePresetSliceConfig.slice.reducer,
  [systemSliceConfig.slice.reducerPath]: systemSliceConfig.slice.reducer,
  [uiSliceConfig.slice.reducerPath]: uiSliceConfig.slice.reducer,
  [upscaleSliceConfig.slice.reducerPath]: upscaleSliceConfig.slice.reducer,
  [workflowLibrarySliceConfig.slice.reducerPath]: workflowLibrarySliceConfig.slice.reducer,
  [workflowSettingsSliceConfig.slice.reducerPath]: workflowSettingsSliceConfig.slice.reducer,
};

const rootReducer = combineReducers(ALL_REDUCERS);

type RootReducerState = ReturnType<typeof rootReducer>;

const accountAwareRootReducer = (state: RootReducerState | undefined, action: UnknownAction): RootReducerState => {
  const isForeignAdoption =
    !!state && externalTokenAdopted.match(action) && !tokensBelongToSameUser(state.auth.token, action.payload);
  if (isForeignAdoption) {
    state = rootReducer(state, logout());
  }
  state = rootReducer(state, action);
  // A logout pass resets each workspace slice's *present* through its own `logout` case, but
  // both undoable slices filter cross-slice actions out of history without emptying it — the
  // stacks keep the previous account's states, and ctrl+Z would walk the next account straight
  // back into them. The clears ride the same reducer call rather than the logout listener
  // because the synthetic pass above (cross-tab adoption) never reaches listeners; this is the
  // only spot both paths share. Two actions because canvas overrides `clearHistoryType` while
  // nodes uses redux-undo's default — which also covers any undoable slice added later.
  if (isForeignAdoption || logout.match(action)) {
    state = rootReducer(state, canvasClearHistory());
    state = rootReducer(state, ActionCreators.clearHistory());
  }
  return state;
};

const rememberedRootReducer = rememberReducer(accountAwareRootReducer);

const unserialize: UnserializeFunction = (data, key) => {
  const sliceConfig = SLICE_CONFIGS[key as keyof typeof SLICE_CONFIGS];
  if (!sliceConfig?.persistConfig) {
    throw new Error(`No persist config for slice "${key}"`);
  }
  const { getInitialState, persistConfig, undoableConfig } = sliceConfig;
  let state;
  try {
    const initialState = getInitialState();
    const parsed = JSON.parse(data);

    // We need to inject non-persisted values from initial state into the rehydrated state. These values always are
    // required to be in the state, but won't be in the persisted data. Build an object that consists of only these
    // values, then merge it with the rehydrated state.
    const nonPersistedSubsetOfState = pick(initialState, persistConfig.persistDenylist ?? []);
    const stateToMigrate = merge(deepClone(parsed), nonPersistedSubsetOfState);

    // Run migrations to bring old state up to date with the current version.
    const migrated = persistConfig.migrate(stateToMigrate);

    log.debug(
      {
        persistedData: parsed as JsonObject,
        rehydratedData: migrated as JsonObject,
        diff: diff(data, migrated) as JsonObject,
      },
      `Rehydrated slice "${key}"`
    );
    state = migrated;
  } catch (err) {
    log.warn(
      { error: serializeError(err as Error) },
      `Error rehydrating slice "${key}", falling back to default initial state`
    );
    state = getInitialState();
  }

  // Undoable slices must be wrapped in a history!
  if (undoableConfig) {
    return newHistory([], state, []);
  } else {
    return state;
  }
};

const serialize: SerializeFunction = (data, key) => {
  const sliceConfig = SLICE_CONFIGS[key as keyof typeof SLICE_CONFIGS];
  if (!sliceConfig?.persistConfig) {
    throw new Error(`No persist config for slice "${key}"`);
  }

  const result = omit(
    sliceConfig.undoableConfig ? data.present : data,
    sliceConfig.persistConfig.persistDenylist ?? []
  );

  return JSON.stringify(result);
};

const PERSISTED_KEYS = Object.values(SLICE_CONFIGS)
  .filter((sliceConfig) => !!sliceConfig.persistConfig)
  .map((sliceConfig) => sliceConfig.slice.reducerPath);

export const createStore = (options?: { persist?: boolean; persistDebounce?: number; onRehydrated?: () => void }) => {
  const store = configureStore({
    reducer: rememberedRootReducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        // serializableCheck: false,
        // immutableCheck: false,
        serializableCheck: import.meta.env.MODE === 'development',
        immutableCheck: import.meta.env.MODE === 'development',
      })
        .concat(api.middleware)
        // .concat(getDebugLoggerMiddleware({ withDiff: true, withNextState: true }))
        .prepend(listenerMiddleware.middleware),
    enhancers: (getDefaultEnhancers) => {
      const enhancers = getDefaultEnhancers();
      if (options?.persist) {
        return enhancers.prepend(
          rememberEnhancer(reduxRememberDriver, PERSISTED_KEYS, {
            persistDebounce: options?.persistDebounce ?? 2000,
            serialize,
            unserialize,
            prefix: '',
            errorHandler,
          })
        );
      } else {
        return enhancers;
      }
    },
    devTools: {
      actionSanitizer,
      stateSanitizer,
      trace: true,
      predicate: (state, action) => {
        if (actionsDenylist.includes(action.type)) {
          return false;
        }
        return true;
      },
    },
  });

  // Once-off listener to support waiting for rehydration before rendering the app
  startAppListening({
    actionCreator: createAction(REMEMBER_REHYDRATED),
    effect: (action, { unsubscribe }) => {
      unsubscribe();
      options?.onRehydrated?.();
    },
  });

  return store;
};

export type AppStore = ReturnType<typeof createStore>;
export type RootState = ReturnType<AppStore['getState']>;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export type AppThunkDispatch = ThunkDispatch<RootState, any, UnknownAction>;
export type AppDispatch = ReturnType<typeof createStore>['dispatch'];
export type AppGetState = ReturnType<typeof createStore>['getState'];
export type AppStartListening = TypedStartListening<RootState, AppDispatch>;

export const addAppListener = addListener.withTypes<RootState, AppDispatch>();

// To avoid circular dependencies, all listener middleware listeners are added here in the main store setup file.
const startAppListening = listenerMiddleware.startListening as AppStartListening;

startAppListening({
  matcher: isAnyOf(logout, sessionExpiredLogout, staleCredentialsDiscarded),
  effect: (_action, { dispatch }) => {
    dispatch(api.util.resetApiState());
    dispatch(changeBoardOperationInvalidated());
    cancelDeletion();
  },
});

startAppListening({
  actionCreator: externalTokenAdopted,
  effect: (action, { dispatch, getOriginalState }) => {
    if (tokensBelongToSameUser(getOriginalState().auth.token, action.payload)) {
      return;
    }
    dispatch(api.util.resetApiState());
    dispatch(changeBoardOperationInvalidated());
    cancelDeletion();
  },
});

addImageUploadedFulfilledListener(startAppListening);
addVideoUploadedListeners(startAppListening);

// Image deleted
addDeleteBoardAndImagesFulfilledListener(startAppListening);

// User Invoked
addAnyEnqueuedListener(startAppListening);
addBatchEnqueuedListener(startAppListening);

// Socket.IO
addSocketConnectedEventListener(startAppListening);

// Gallery bulk download
addBulkDownloadListeners(startAppListening);

// Boards
addImageAddedToBoardFulfilledListener(startAppListening);
addImageRemovedFromBoardFulfilledListener(startAppListening);
addBoardIdSelectedListener(startAppListening);
addArchivedOrDeletedBoardListener(startAppListening);
addGallerySelectionSourceListener(startAppListening);

// Node schemas
addGetOpenAPISchemaListener(startAppListening);

// Models
addModelSelectedListener(startAppListening);

// app startup
addAppStartedListener(startAppListening);
addModelsLoadedListener(startAppListening);

// Ad-hoc upscale workflwo
addAdHocPostProcessingRequestedListener(startAppListening);

// Filters
addPBRFilterListener(startAppListening);

addSetDefaultSettingsListener(startAppListening);